Clean Code with Java: Replace the logical condition using ENUM(if / else statements)
Hello everybody, we are going start the first part of Clean Code with Java session and today I am going to present one thing that it is really important when you are evaluate a Pull Request or try to understand a code. Sometimes when you arrive in an ongoing project is really hard to read and understand some codes, mainly when those codes have many if / else statements. I bring here a good to make your clean code with Java.
Since we can assume we have 4 types of operations in the TransactionType such as BUY, SELL, DEPOSIT, WITHDRAWAL. For each operation I have a rule to calculate a tax value. How would your first idea to implement this? Normally people tend to do if / else statement on this. Normally everybody tends to do like the example below. The code is hard to understand and is not clean.
What can we do to improve the code? Would you approve this PULL REQUEST? For sure, I wouldn't approve this because we know the if statement can cause trouble in your code and there are more elegant way to do a better code. Let's see a good way to do best code achieving the same results. Easy!!! Use ENUM.
1. Use of Enums
The use of Enums must be considered to no longer validation, in the otherwise, a short validation. I am telling this because if you have many variables to validate, the ENUM is going to be hard and more complex to understand as well. Also we can say that long values must be in Database. The TrasanctionType is a good example because is a short validation that we can bring to real world. I would consider this, for a small combination exactly like in this example. The first step you have to create the enum class. In this example, I created TransactionType enum class with abstract method called doTransactionOperation. Also we have the Account class with some operations.
The next step we need to implement the method doTransactionOperation. There are a business rule that calculate the Tax for each type of transaction. We can see that for BUY the tax is 0.15, for SELL the tax is 0.1, for the DEPOSIT the tax is 0.05 and for WITHDRAWAL the tax is 0.20.
As you can see the results achieved are the same and the code is clean enough to change faster than many if / else statement before. This can reduce the number of nested conditional logic delegating the responsibility for each Enum.
Let's go to the results:
Assume we have in the begin of the Account 1000.