Writing clean if else statements
Using if else chaining some time looks more complex, this can be avoided by writing the code in small blocks. Use of conditional statement increases the code readability and much more. One best practice should be handling error case first. Below shown example shows how to handle error cases and simplify the if else logic.
updateCache()- It’s a method in which on the basis of some class level variables decision is taken for update main db.
updateBackupDb()- It’s a method to update the DB.
Using this type of if else is harder to debug and extend any feature in existing function.
In below code the boolean variables has been identified and based on that
code is broken into small blocks using if and return statement.
1. If update is not ready then this is not required to enter in method
just exit from this method.
2. Similarly is force update boolean is false then perform the task in if statement
– updating the cache and returning from this method.
3. In the last step rest all task is done updating backup db and updating main db.
Note- What major consideration is taken in above optimization version is simplify the if else based on the conditional statement.
The benefit of this type of easy blocks of code is – for the next developer it is very easy to debug/understand/extend this method.
Explaining this idea via existing JAVA API code example
This code snippet is taken from Java Doc:-
JDK sub string code JAVA API
Existing code from above API- this is written perfect.
If any one use if else as shown in below example after modifying above logic, it will be very complex but at the end producing same result so i would not prefer to implement as shown below –
After seeing above two examples it can be observed that error handling is done while entering in method. This is good practice to handle error condition first.
Overall if if else can be used in small blocks based on requirement that will remove code complexity and code will be easy to use/debug/maintain/extend.