Using Syntactic Sugar – When to Use or Avoid Syntactic Sugar

cclean code

Currently I am working on a school project written in C#. Some teammates just started in C# and some are already familiar with C#. Today I had a discussion on whether to use syntactic sugar like this in our code:

private _someClass;
public SomeClass SomeClass
{
    set => _someClass = value;
}

// Equivalent to:

private _someClass;
public SomeClass SomeClass
{
    set 
    {
        _someClass = value;
    }
}

Or this:

random ??= new Random();

// Equivalent to:

if (random == null)
    random = new Random();

Reasons we discussed for not using syntactic sugar like this were:

  • It is hard to read in general
  • For someone coming from another language e.g. Java, it is harder to see what is going on in the code.

Are these valid reasons? Does this happen in other languages? Are there some measures to decide what is the "cleaner" way of coding?

Best Answer

I disagree with

It is hard to read in general

especially to "in general". These language features may be hard to read for beginners when they see them the first time, but they were actually added to the language to make code more concise. So after one gets used to them (which should not last longer than using them half a dozen times) they should make the code more readable, not less.

For someone coming from another language e.g. Java, it is harder to see what is going on in the code.

Yes, but is your goal to program Java in C#, or to program C#?

When you decide to use a language, you will be better off learn the idioms of the language, especially the simple ones. When you work with real-world programs, you will encounter these idioms frequently and will have to deal with them, whether you like them or not.

Let me finally add, the ultimate measure for the readibility of your code is what your peer reviewer tells you. And whenever I am in the role of a reviewer who stumbles about a simple language idiom which is new to me, I usually take it as an occasion to learn something new, not as an occasion to tell the other devs what they should not use because I don't want to learn it.

Related Topic