Development

Improving conditions clauses – working on the code

It’s fascinating how very small changes can improve code readability. Bellow you can find some examples, which are often present in unexperienced programmers code.

Conditional operators:

Let’s say that we have a condition which looks like in this example

What is wrong with this code? The intention of the “if” condition is unclear – there is no explanation why we compare to specified numbers and what are those numbers.

Let’s see how it can be improved for better redability by using  “Don’t make me think” principle:

It takes more lines of code now, but it’s clear what the “$this->isWeekend($day)” condition is checking.

This is quite simple example, but many times the defined condition rules are more complex and this type of solution will make their intention clean for programmer.

Indentations:

“… if you need more than 3 levels of indentation, you’re screwed anyway, and should fix your program.” – Linux Torvalds, Linux kernel coding style

I like this rule a lot. It’s one of the code smells easy to find which say, that something needs to be improved in the code. So what does it mean? Let’s look at the example:

What is wrong? You have too many nested code block here, which should be extracted to separated function or even object (depends on the logic).

Let’s see how it can be improved for better redability:

Guard Clauses:

Many times I see code which look like that:

It’s not so bad, and after a while it started to be even quite clear what is it responsible for. But can it be improved? Yes – and there are few ways how it can be done. First step – try to use early return and remove “else” block. After that the code will look like that:

So a little bit less lines of code. now let’s change the if-elseif statements into guard:

Very small change, but great impact – don’t you think?

Subsequent articles

  • Static Factory Methods aka Named Constructors: Read more…
  • Improving conditions clauses – few small things with hudge impact: Read more…