Saturday, 10 September 2011

What is strong-typing versus weak-typing? Which is preferred? Why? Post title

Strong type is checking the types of variables as soon as possible, usually at compile time. While weak typing is delaying checking the types of the system as late as possible, usually to run-time. Which is preferred depends on what you want. For scripts & quick stuff you’ll usually want weak typing, because you want to write as much less code as possible. In big programs, strong typing can reduce errors at compile time.

In strongly-typed programming languages you usually have to declare variables prior to using them. Strong-typing is the strict enforcement of [type] rules. All types (int, short, long, string) are know at compile time and are statically bound. So C# is a strongly-typed language because variables must be assigned a type before you use them. If you came from the ASP world then you will remember having to use either Javascript or VBScript. Variables that you declare in either of those languages can hold any data type which makes it weakly-typed.
But lets take this up a level. Instead to talking about programming languages, lets talk about strongly-typed/weakly-typed objects. The DataSet object is a great example. If we use a weakly-typed dataset, the developer needs to know the name of the table and the name of the field being requested. Since we are just passing strings, this code will compile and will not show any possible problems (like typing the name of the table wrong) until run time.
  string s = (string) myDataSet.Tables["Customers"].Rows[0]["CustomerID"];
If our Dataset is Strongly-Typed, we are able to access the names of the tables and columns directly. Any errors are caught at compile time.
  string s = myDataSet.Customers[0].CustomerID;
I am not really going to argue which is better, I will leave that up to you. I will leave you with this question though; would you rather catch your errors at compile time, or run-time?

No comments:

Post a Comment