Saturday, April 14, 2012

Coalesce and Inline Operators

As part of a platform review, I have been seeing a lot of code lately that has been in production for a while.  I know that sometimes people are just creating the code they know how to create and making the project run.  That is all good.  Sometimes it is good to try and learn a better way way to do some very basic things.  I know that personally the following options make code a bit more easy to follow and maintain.

Coalesce
There are a lot of long if statements that seem to be looking for the first usable value. (this is a composite of the idea...)


if (value1 != null)  
    variable = value1;  
else if (value2 != null)  
    variable = value2;  
else if (value3 != null)  
    variable = value3;  
else  
    variable = DefaultValue;  

Just to simplify and make more readable, try using the ?? (coalesce) operator.  Notice the nullable type restrictions, etc.


variable = value1 ?? value2 ?? value3 ?? DefaultValue;   


Inline If
Here is another one (again, just a composite)

if (something == somethingelse)  
  value = "1";  
else  
  value = "2";     

try making this one line, more readable.

value = (something == somethingelse) ? "1" : "2";      


I know that these are some basic ideas, but judging by the code bases I have been checking out, they are not widely used.  Perhaps, looking into some of these items as best practices would be beneficial.

1 comment: