ObservableDeveloper - Leonid Sorokin's Blog

.NET, Silverlight, ASP.NET, Web Services, SQL Server, Cloud Computing, and much more...

About the author

I am a .NET Software Developer, Consultant, and Trainer from Toronto, Canada specializing in web development with Rich Internet Applications on the Microsoft development tool chain.

My Photo

Microsoft Certified Professional Developer

To throw or not to throw Exceptions - that is the question

Today I had to make a decision whether I should be throwing an exception or not.

In my data access layer I had to have a SaveUser method that saves a user object by calling a corresponding SaveUser method on a REST web service.  The question arose regarding the return value of the method in my data access layer. Logically the return value should be a boolean, either the SaveUser operation succeeded or not.

Here is one possible method signature:

bool SaveUser(User user); // not such a good approach

However, this is not a good solution. Why? The return value should always be true, and false only in exceptional circumstances. 

In general, when saving data, it is much better to return nothing, and let exceptional situations be handled by the best candidate - exceptions.

Therefore, the SaveUser method should have the following signature:

void SaveUser(User user); // much better approach

If the web service returns an error, the data access layer should raise an exception and set the InnerException propety to the exception text returned by the web service. 

This is a much cleaner solution than returning true/false from the SaveUser method.


Categories: C# | .NET
Permalink | Comments (0) | Post RSSRSS comment feed

Null-Coalescing Operator in C#

I was reading a Silverlight related article when I stumbled on a really interesting operator. It is known as the Null-Coalescing operator, and it can be used instead of the more verbose ternary operator.

The Ternary/Conditional Operator can be used as follows:

int? currentCounter = null; // a nullable type

int counter = currentCounter != null ? currentCounter : default(int);

I also wrote code such as this many times, and at some point, you start asking yourself, isn't there a better/cleaner way? Obviously, accessing currentCounter twice is redundant.

With the Null-Coalescing Operator the above conditional operator expression can be shortened to this:

int counter = currentCounter ?? default(int);

In plain English, this would read "If currentCounter != null, then counter = currentCounter, otherwise counter = default(int)."

I think that, more than anything else, it simply results in cleaner looking code.


Categories: C#
Permalink | Comments (0) | Post RSSRSS comment feed