Encapsulate conditionals

Conditionals play a vital role in code for performing business decisions. These conditionals should be easy to read.

If conditionals are complex then it might hamper readability. You would end up introducing more bugs if failed to understand its intent. Every time you visit this code, you will need to debug it to understand the intent.

Complex conditionals:

Complex conditional determines something to perform business rules

Look at above conditionals in if clause. It is clear that it is performing too many checks related to the package of the items. Please note that this package was ordered from an online e-commerce site and then performs important business decisions.

It will be difficult for the maintenance programmer to figure out each condition and know what question it tries to answer.

Let’s make the maintenance programmer’s life a little easy by writing readable code using encapsulate conditionals that have intuitive names and give the answer in yes/no format.

Better way:

Complex conditionals are extracted to a method. 
An intuitive name is given that tells what it is doing.
The complex conditional block would be simplified like this. It reads like perform business decisions if a package is eligible for a return.

Another complex conditional

Too many questions here.

Preferred way:

A simplified version with clear intent: can view editor?

Dattatray Kale | Being software craftsman
I am an application developer based in Pune, India. I am willing to wait for the right opportunity – Datta CV PRACTICES…blog.beingcraftsman.com

Dattatraya Kale

Aspiring agile software craftsman, clean code, polyglot, in love with different programming paradigm. I am on a never-ending journey towards mastery of software.

Leave a Reply