Underutilised in C#

I find that there are many underutilised features of C#. The following is short list of some of the features I would like to see being used more often.

The ?? operator

When using lazy loading or singleton constructs we often write code similar to this:

    public Address Address
    {
      get

      {
        if (address == null)

        {
          address = loadAddress();
        }
        return address;
      }
    }

This MSDN page explains that the ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. Using ?? we could get the same functionality, with fewer lines of code:

    public Address Address
    {
      get
      {
        address = address ?? loadAddress();
        return address;
      }
    }

Is Null or Empty

Are you getting tired of writing code like this?

if (name == null || name.Equals(string.Empty))
{
// Do something
}

You really should not be using that, replace it with this:

if (String.IsNullOrEmpty(name))
{
// Do something
}

Using this will often allow us to use the ternary operator e.g.

    public string Name
    {
      get
      {
        return (String.IsNullOrEmpty(name) ? UNSPECIFIED : name);
      }
    }

List(T).AsReadOnly

To prevent modifications to a list, return the list wrapped in a read only wrapper. This aids in encapsulation and helps to prevent unwanted changes to collections. This MSDN page provides a good example.

Advertisements

12 thoughts on “Underutilised in C#

  1. Surely the ? operator returns the first argument if the predicate evaluates to True, the second if it evaluates to False. So the example should read

    get { return (!String.IsNullOrEmpty(name) ? name : UNSPECIFIED);}

    or better

    get { return (String.IsNullOrEmpty(name) ? UNSPECIFIED : name);}

  2. Immo you are correct, my code would not have worked correctly.
    It is now fixed.
    This reminds me of another underutilised feature – Unit Testing 😉

  3. Good point Ben, you can use

    return address ?? loadAddress();

    If you want to use caching loadAddress() must set the address variable. I did not want to hide that assignment therefore I explicitly stated the assignment here.

    As for the indentations…don’t ask. They were there when I made the post. After I corrected some of my amazing spelling, poof the indentations were gone!

  4. I detest the use of ?? because many software engineering newbies mess it up completely or take it too far (and then mess it up completely). Either a ? is forgotten somewhere, or they start combining multiple logical statements all into 1 line (“ultra cool trick”). Too much of this kind of code becomes extremely difficult to comprehend. And debugging logical mistakes requires a longer than required time in a Debugger Step view, if you are lucky enough to have a debugger!

    I am not entirely convinced by your “Is Null or Empty” argument either. These are 2 separate tests that must be performed, perhaps in a special sequence (like null first, then empty?). In this particular instance I am okay with your argument. However many software engineering newbies (again) get carried away and start combining logically different tests all over the place leading to a big mess to be maintained and typically to big bugs also when code like this must be maintained (and some tests get moved around into different sequences)!

    I do like your tip on the AsReadOnly though – thank you!

  5. Rob, I am glad you like the AsReadOnly feature it is really nice. I assume it stems from all the CSLA activity.

    I disagree with your objections to using ??.

    “Either a ? is forgotten somewhere”
    1. You say ‘somewhere’ as if it is hard to tell where the second ? is or should be – they go directly next to each other!
    2. If you leave out a ? the compiler will complain.

    “…many software engineering newbies mess it up completely or take it too far…”
    1. Yes newbies can get smart with this and make code that is hard to read and maintain. Newbies can also use dot notation to make long chains of referenced objects. Should we stop using dot notation and OOP? Newbies can also abuse if statements, case statements and just about any other logical construct. Should we drop all logical constructs? No, we should make the logical structures smarter, more functional as in F# and Erlang. Thus reducing lines of code and generally reducing errors for those who apply good programming practices. We should not be stuck with a set of constructs which are newbie safe.

    2. Do I think newbies should use the ?? operator ? Yes, most definatly! Newbies should use and abuse as much of the language as possible. This will allow them to learn from their own mistakes and to apreciate good programing standards. Ofcourse this should be done while studying or working on personal projects. Programmers\hackers who have not gained a sense of what is good practice should not be hired. They are simply not ready for production code wich needs to be maintained. Professional developers should be able to use ?? resposibly.

    I also disagree with your objections to “Is Null or Empty”

    “These are 2 separate tests that must be performed, perhaps in a special sequence (like null first, then empty?).”
    1. This built in function performs the tests in exactly that order! Hence the name IsNullOrEmpty. Obviously if different actions are required for a null and a empty string then you can break up the tests. That is not the case here, as you agreed.

    “…However many software engineering newbies (again) get carried away…”
    1. In adition to my comment about newbies stated above, a newbie will write unmaintable code with or without this function. We should note that this function combines two tests into one. The poor newbies code will actually be a bit cleaner if he/she had to use this function – the newbie may even begin to see the light with regards to functions…and this may even lead to an understanding of ‘seperation of concerns’!

    Newbies let loose! But do it in your own back garden…

  6. Daryn

    In sequence:
    1: Okay, fine. So long as the compiler complains!! (I am used to other languages where a ? is just as legitimate as a ?? and the compiler does not complain) when the engineer makes a logical mistake.

    2: So you reckon that people have enough time during studies or to work on personal projects in order to gain enough experience to be hired and then are ready to maintain production code. I disagree. Production code comes in all flavours, sizes and shapes. There is no way a person not working on a real project, writing or maintain production code, gets experience at some of the true horrors of horrible production code. Nor, because it is self study, is there any reason for a person to see a different view and form a different set of brain patterns that will allow them to grow beyond their own boundaries. It is only working with people…on real projects…that you get paid for. “Necessity is the mother of all inventions” and drives the creative spirit (insight) if your pay cheque, bonus, client or company is on the line….

    1: Glad you noticed I drew a distinction between okay, fine: IsNullOrEmpty, and my concern that the newbie would get the wrong idea and start combining logically different tests under utility methods.

    1: Hmm learning by doing == experience. See my response for 2: above and consider that a newbie with good guidelines that are well understood by the newbie, and sufficient mentoring will not write much unmaintainable code.

  7. Rob, I really do not see what all this fuss is about.

    In your comment you said “I am used to other languages where a ? is just as legitimate as a ?? and the compiler does not complain”. I should have said that I was talking about C#, maybe I should have stated this somewhere – like in the title of the post.

    This is the point – there are some nice constructs in C# that will help you write readable and maintainable code. Some of these constructs are listed in the post.

    The proof is in the pudding – if you look at the first comment by Immo you will see that he noticed a logical error with my code. As embarrassing as this is, it proves the point that using these constructs will enable other people to read, understand and fix your code (if\when required).

    Now lets move on with our lives…

  8. Pingback: How To: Add a Block of Code to My Blog « Daryn’s Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s