Conditional logic can be very cumbersome and difficult to read. A single if/else
block might be simple enough, but nesting several of them can lead to very complicated logic and difficult to read code.
Often, we can easily eliminate half of the branching through the use of guard statements and early returns. This lesson will take a function with a few nested if/else
blocks and refactor it to remove all of the else
s. The result will be simpler and, in my opinion, easier to read.
Kyle Shevlin: [0:00] Here I have a single function that takes a few options and goes through a series of if and else blocks in order to return values. Often using if and else blocks can be very difficult to read it due to their nesting and branching.
[0:14] Let's refractor this function to not need elses. I have a series of tests over here that will continue to run as we refractor this.
[0:22] The first thing we see is our last else block has a single value. What we can do is take this and then get it, and return it early using what's called a guard.
[0:33] If type does not equal date, and we'll scroll down here and we're going to copy this. We're going to paste it in place. Now we can get rid of this entire block. We're going to save our code. Our test will run and our test continue to pass.
[0:49] Because we're now doing everything that's not a date here, we no longer need to check if type is date. We know that this is type date, so we can remove this block here, and unnest one level of if and else blocks.
[1:04] We can do the same thing here we have the negation, value does not equal zero returns this, so this is if the value is zero. We can make another guard and early return to handle that case. Once again, we can copy, paste, remove this else block, our test continue to pass.
[1:24] Because we know after here, we've already returned the value must not equal zero in order to be here, so this condition no longer is necessary. We can remove that block and our test continue to pass.
[1:38] One final refactor we might like to do. Here, we have the negation value3 returns today or tomorrow. It is often easier to read this as the positive. So instead, we're going to flip this around. We're going to move tomorrow into the happy case, and today into the sad case. We'll clean this up, we'll save it, and our test still pass.
[2:04] In summary, by reversing the logic of our conditions and using early returns, we were able to remove all the else blocks from this code.