DEV Community

Discussion on: Keeping your code clean by sweeping out "if" statements

Collapse
 
capellablue profile image
Amanda

Oh, how guilty am I of writing an innocent if statement to handle errors..that turns into a big, complicated mess of conditionals!?😂 Very guilty. It's unintentional, usually, but as new cases present themselves, and I try to fit in with the surrounding code...it ends up being a heap of much needed refactoring/abstracting just to remove the bloat so the point of the function is clear and concise.

But is it always the case that lots of if/thens are code smelly? Eh... It's more like a waft of potential code smelly that requires more investigation.

I appreciate this discussion because sometimes, a deeply nested if/then parade is not very readable. But ... for me, readability and perf are balanced-- the need for each different in each situation.

I hear the preference for easy debugging. However, while if/thens are all in one file, I find lots of conditionals overwhelming for focus sake. I don't have much trouble searching my codebase and opening all the files to debug (as opposed to quick logs in one file's deeply nested if/then train), but I understand why this feels discombobulated. Nothing a good IDE hasn't made easier for me.

Also, concise comments are essential, in my opinion. If I refactor my if/thens...I just leave a good comment, and all is well for my future self and my team down the road should something need updated/fixed. If legacy code is disorganized, I can see why a preference to keep code in one area is preferred.

Overall: lots of If/thens aren't always smelly code. It seems project specific. Are you on a team that keeps code organized and well commented? Is this a pattern you can keep implementing throughout the code base to create a sense of overall design cohesiveness? Is the refactor excessive?

Thanks for good discussion!

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi Amanda, thanks for your feedback!

Don't feel guilty, we've all sure had our share implementing messy conditionals! The point I tried to make is much more about keeping the business rules as clear as possible than about whether or not we should use ifs, but I do think lots of ifs will most certainly get in the way.

I will try a different approach for the next post and see how it goes. It's been a very interesting discussion indeed, thanks for your input!