Sunday, October 11, 2009
Aliasing a class? Whoa!
Wednesday, October 7, 2009
“Nullable object must have a value.” – could be a sign of something serious
Figure 1 – A message that can leave you dumbfounded
Unfortunately, the capability of Visual Studio in detecting null nullable is limited only to uninitialized fields. If the nullable object is a property, then all you can do is sit and wait for the bomb to go off. In Figure 2, the properties SampleClass.NullableBool and Program.NullableBool are never checked by Visual Studio whereas _nullableBool cannot escape the scrutiny.Figure 2 – Visual Studio can help detect only uninitialized nullable fields
Figure 3 shows the most common mistakes that trigger the exception. The first case is when the Value property is called to extract the encapsulated native type. The second case is quite common among new programmers where instead of calling Value, a cast is performed on the nullable object.Figure 3 – Be on the lookout for lines similar to these
Bear in mind though that calling ToString() on a null nullable is perfectly legal as long as it’s initialized. It simply yields a blank which is what exactly we want in the UI.Figure 4 – It’s safe to call ToString as long as the nullable is initialized
There Could Me Something More
When you’re done cursing Microsoft, do yourself a favor and go back to your codes. The message could be a sign of a more serious type of bug lurking somewhere. This is because it’s possible that nullables are used in boolean conditions without the benefit of a prior nullability check. If this is the case and the coder does not call the Value property, the compiler does not complain at all. It simply evaluates the condition as false!Figure 5 – A null nullable is always evaluated as false
In the business rules of your application, it might be that a null is equivalent to a false and in this case, you could care less about codes similar to Figure 5. However, the fact that 3-value logic is already allowed to permeate in the application also means that null deserves a separate treatment altogether. A null could mean “I don’t know”, “not yet”, or “maybe”.Figure 6 – This block can wreak havoc in your application.
Defensive Coding
Nullable<T>.HasValue can be used to check if the value is null. You usually use this whenever a null value is treated differently as illustrated in the snippet below:Figure 7 – Using HasValue prevents exception and aids in the 3-value logic evaluation
In the rare cases where a null means false or any valid value of a type, one can use the coalesce C# operator ?? as shown here:Figure 8 – The coalesced operator is handy when null value can be interpreted in some other way
In the next release of .NET, I hope we could get a much more meaningful message, something like “Attempting to perform action to a Nullable<T> is not allowed when its value is null.” Whatcha think?Tuesday, June 30, 2009
OUTER JOIN in LINQ
I’m quite disappointed to find out that LINQ has an OrderByDescending() and the “VB-ish” ThenBy() but seems to forget a dedicated extension method for OUTER JOIN. Although not as straightforward as I wanted it to be, SelectMany offers a working solution.
For illustration, let’s consider the very naive model below. A left join from Child to Parent should yield 2 rows, with the second row having null values on the Parent columns.
Dragging the tables to your LINQ-to-SQL canvass produces the model below. From this we can issue our statements.
The solution uses “statement” syntax, not the SQL-like syntax you always see when someone touts about LINQ features. To help with the breakdown of the LINQ statement structure, I included the SQL syntax and highlight the equivalent parts.
Part labeled 1 is the projection statement with the LINQ version utilizing anonymous type. Notice that type inference compels me to convert the ParentId to nullable type. Not doing so would have led the compiler to use Int32 as the type for ParentId. If this happens, an exception would occur for the second row because the value assigned to that property would be null.
Part labeled 2 qualifies the join. The object from which SelectMany is called returns all the rows. This is exactly what we wanted with the Child table. Also notice that we made sure that the qualifier columns from both table have the same type. In order to achieve this, the Value property of the Nullable<Int32> is called from Child.ParentId. You can also achieve the same by converting the other side into nullable as shown here:
You also need to call the DefaultIsEmpty() on the right table, in this case the Parent table. If you don’t call this method, the compiler would just ignore those rows with null values in the Parent table, effectively reverting to an INNER JOIN. Weird isn’t it?
Running the small snippet gives exactly what we wanted.
Sunday, June 7, 2009
Delegate Contravariance. Say what?
.NET 2.0 started to apply a somewhat obscure programming concept called contravariance to delegates. Delegate contravariance, as what it’s being referred to, allows you to hook a method to a delegate which parameter is a descendant of the parameter in the method. If you’re confused, here’s what it means:
In the snippet above, you are able to hook OnAnyEvent even though the CancelEventHandler is defined with CancelEventArgs. This is because CancelEventArgs is a descendant of EventArgs. The EventArgs, under the virtue of polymorphism, can accept the CancelEventArgs passed by the TextBox control.
Where is it?
Delegate contravariance is not apparent in Visual Studio which, in my opinion, mainly contributed to its obscure nature and low adaption. If you hook an event to an existing handler at design time, you're shown only those which signature matches the event. In our example, you won’t see the OnAnyEvent contravariant delegate at all.
If you hook manually on the other hand, you’re provided hints which are not helpful either.
So the only way to apply delegate contravariance in your code is by brute force. Unless you have explicit knowledge about it, you would never know it’s there. And even to those who are already enlightened, the manual coding still puts them off.
Should you care?
If your codes perform the same routine in different events regardless of the event signature, the decision is no-brainer. I think this is contravariance raison d’ etre. But the thing is, this scenario is very rare. More often than not, you hook to an event because you wanted to execute specific routines and take advantage of the context properties. In our example, we hook to TextBox validating event to validate inputs and control the behavior of the focus using the CancelEventArgs.Cancel property. The question then becomes: Is it worth hooking more than one handler to a particular event to handle the generic and specific routines separately? My answer is NO. Additional handler is additional awareness layer. This practice compels you to always think that something else is hooking to an event, therefore complicating the debugging process. I rather convert the generic handler to a method which I can call within the other handler as shown here:
Should you adapt multi-handler approach thru contravariance, just remember that the order of calls follows the order of hooks. So if you wanted to fire the generic handler prior to the specific, you have no other choice but to hook both handlers by code because as you’ve seen a while ago, VS does not allow hooking of contravariant handler let alone 2 handlers, at design time. This necessitates slight modifications in the constructor as shown here:
The good thing is that the EventArgs hierarchy is still very shallow. My guess is it’s only two to three levels deep. So most probably you would only hook at most 2 or 3 handlers per event if you follow the event handler-decomposition path to cohesiveness. Still this is not a guard to bad practices because the very nature of .NET event does not prevent anyone from hooking handler to her heart’s content.
So what’s the next move?
My opinions on delegate contravariance are limited only to event-handling so I’m not going to conclude anything about its true merit. I’m still rummaging my old Windows application hoping to find sections I can refactor using this concept. Delegates are all over the place and viewing this concept only within the confine of UI programming is myopic. I’m sure I will find good uses of it nowadays that LINQ and lambda’s are starting to gain momentum.
Tuesday, June 2, 2009
Optional Params Anyone?
During my break today, I was able to skim on some articles about the upcoming C# 4.0. Pretty much everything is evolutionary but one feature stands out from the rest not because it’s revolutionary but because it’s needless and counterproductive. The C# team decided to add optional parameters support to C# ala VB. I’m not a fan of optional parameters and as a matter of fact, I abhor it like Dijkstra abhorred GOTO. It undermines the benefit of overloading. To stretch my point, let’s say you have a class Timer with alarm features and with the following overloads:
public void Start(DateTime startTime)
{
// more codes here
}
public void Start(DateTime startTime, TimeSpan elapsedTimeBeforeAlarm)
{
// If elapsed time is 0 or less, throw invalid argument exception
}
public void Start(DateTime startTime, DateTime alarmTime)
{
// If alarm time is prior to start time, throw invalid argument exception
}
As you can see, each method has distinctive purpose and logic based on their parameters. The first one does not set the alarm whereas the other two sets them but through different means based on the type of the second parameter.
A novice programmer can easily think of optional parameters to implement all of these. He could come up with something like this instead:
public void Start(DateTime startTime, TimeSpan elapsedTime=”0:00:00:00”
, DateTime alarmTime=DateTime.MinValue)
{
// Determine what combination and execute logic accordingly
// In addition, validation is also performed to the parameters
}
Wow! One method to serve them all! Nothing’s cool about this unfortunately. First of all, it’s fat because it’s no longer cohesive. The codes which check for the combination of the parameters supplied do not have anything to do with setting the alarm anymore. It’s difficult to maintain these convoluted codes. I’m not saying that this kind of coding is rampant but hey, it could happen.
Microsoft promised that the new incarnation of the .NET Framework will be a “real upgrade”. It will contain less new classes and more upgrades to existing ones. What I don’t expect are fixes for things which ain’t broke, let alone those that promote bad practices. Optional parameters is in that list. I just hope it’s the only one.
Saturday, May 30, 2009
Enum in Lieu of String Constants
Every now and then, we are faced with situations when using literals seems to be the only way to accomplishing things. Let’s take for example the case of untyped DataSet. One reason why I hated using untyped DataSet is the fact that Intellisense is unable to assist me when accessing the objects of the different collection within it. I'm talking about string indexers which is used to qualify the objects in collection as shown below.
DataTable tblPayers = aDataSet.Tables[“Pharmacy”];There might be typos in my codes already but most probably I’ll find out only during runtime. This situation is even aggravated when you have more than one parts of the codes accessing, let’s say, different columns of a DataTable. In order to be consistent with the indexer qualifier, a good practice is to declare those column names as constants. Ok, ok, some of you might think this is an overkill. Well, it is if you’re dealing with LastName, Birthdate, OrderNo but what if you’re in a totally unfamiliar territory where ClearinghouseSubmitterId, PayerLOB, NCPDPNo and other exotic creatures roam? Trust me, it will pay off sooner or later do it the “overkill” way. So to proceed, you will have something like this snippet:
// More codes here
selectedRow[“NCPDPNo”] = “123456”;
const string ClearinghouseSubmitterIdColumnName = “ClearinghouseSubmitterId”;I see nothing wrong with this approach and as a matter of fact, it’s a correct one. But there’s actually shorter and organized one albeit unconventional.
const string PayerLOBColumnName = “PayerLOB”;
const string NcpdpNoColumnName = “NCPDPNo”;
internal enum EnrollmentColumn { EnrollmentId, ClearinghouseSubmitterId, … };I know what you’re thinking right now. Enum is not built for this. I agree but as you can see, with the aid of Intellisense, enum becomes a convenient and safe way to code. First of all, it’s shorter to declare enum. You only need to type the name and the ToString() will take care of the rest. One thing to remember though is that the equivalent column or literal should not contain space. So enum is ruled out when you have columns like “Last Name” since space is an invalid token in .NET. Second, the code is a little more organized this time. The name of the enum can be the name of the table. Of course you can also employ other implementation like a static class with a bunch of read-only string get properties but again more coding is involved.
internal enum PayerColumn { NationalPayerNo, PayerLOB, … }
internal enum PharmacyColumn {NCPDPNo, Name, ….}
internal enum Table {Enrollment, Payer, Pharmacy,...};
public class AForm : Form
{
void Foo()
{
DataTable tblPharmacy = aDataSet.Tables[Table.Pharmacy.ToString()];
// Codes to retrieve selected row
selectedPharmacyRow[PharmacyColumn.NCPDPNO.ToString()] = “12345”;
}
}