Encapsulate conditionals

Dattatray Kale
Technogise
Published in
2 min readAug 19, 2019

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?

Originally published at https://beingcraftsman.com on September 7, 2018.

--

--

Dattatray Kale
Technogise

Software Craftsman & Cloud Engineer with 13+ years' expertise. Proficient in React, Angular, .NET, Node.js, Java, AWS, Azure. Proven leader in team building.