Software - Syntactic Sugar

by Elliott
5 minutes
Software - Syntactic Sugar

Syntactic sugar in software development is defined as code that makes software easier to read (https://en.wikipedia.org/wiki/Syntactic_sugar). But sadly it is usually the opposite.

What happens many times is a developer reads about a new way to write a bit of code, or a new feature in the language, and think, "all the other programmers will think I am smart if I use this new thing."  Or "This code shortcut will allow me to make this three line set of logic fit on only one line." The result from this is usually what we call syntactic sugar. 

Syntactic sugar causes cancer of the semicolon. -- Alan Perlis

But many people are calling it syntactic saccharin now. Here is a code example:

     model.IsEmailAddressEdited = TempData["IsEmailUpdated"] is bool isEmailUpdated && isEmailUpdated;

In plain English this means that if the dynamic value of TempData["IsEmailUpdated"] is a boolean (true or false), then create the variable isEmailUpdated and set it to the value of  TempData["IsEmailUpdated"]. If that happened, set model.IsEmailAddressEdited to the value of the new variable isEmailUpdated.

It is not simple to understand what this code does. The automated code analysis system SonarCloud marks this code as as a major problem and requests the developer, "[c]hange this condition so that it does not always evaluate to 'true'." If an automated system cannot understand the code, what hope does a junior programmer have?

That is a lot of logic in one line of code. Which being one one line means that you cannot put a break point within the statement. 

Here is the code that I replaced it with.

     if (TempData["IsEmailUpdated"] is bool)
{
model.IsEmailAddressEdited = TempData["IsEmailUpdated"];
}

This is much more readable, and is simpler to debug. Plus automated systems and future programmers can easily understand what it does. And remember that you as a programmer may have to maintain your code in the future, when you don't remember what it is supposed to do. For your own sake, and the sake of others, please avoid syntactic saccharin.