Jeffrey Way says “never use Else”

Lets assume that your company has some rule that worker did not work on Friday and believe in so much that they wont even allow in the plot if it is on Friday ..ha ha little silly

If the day is not Friday then we can move on to validating the post for the form. if the validation passes then we can create the post and pass in our input and finally maybe redirecting to the homepage . however what if validation did not pass and then you have else keyword and in that case may be you redirected to the back with validation error. finally we use else for it if day is Friday and in this case may be here we can throw an exception with message we do not work on Friday.

In that case we do it better . in those situation we perform defensive programming approach lets do it. First lets check validation is fail first that is why i moved that up just like in the example code and another code in the button and finally check if it is validate is fail. So if validation is fail go back and display the error other wise move forward and create the post and then do whatever you want to do and finally redirected whenever you want to go :D. Now lets apply defensive approach for top level condition ie, date , if the date is not the Friday then proceed to creating the post , however we could be write like this so if the date is equal to Friday then we need to throw an exception otherwise move forward .

Isn’t it clean and simple ? From the just little trick here we can replace the else condition entirely .

Sharing is caring!

Related Post