6

Where do you prefer your conditionals – inside or outside?

 3 years ago
source link: https://dev.to/rvisharma/where-do-you-prefer-your-conditionals-inside-or-outside-52c0
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for Where do you prefer your conditionals – inside or outside?

Where do you prefer your conditionals – inside or outside?

Dec 26

・1 min read

Cover photo by Emily Morter on Unsplash

Many times when i'm writing a piece of logic, i face this dilemma while calling a function. If a function needs to be invoked under certain condition, should i put the conditional check inside the function and do early return, OR first do an conditional check and the invoke.

Both have their pros and cons, IMO

Conditional inside the method

  • Pros - My execution path remains free of branches and the flow looks linear and simple to read.
  • Cons - The intent and actual execution would differ in some cases. carbon

Conditional before calling the function

  • Pros - Intent is clear, i want to invoke this function only when a certain condition is met.
  • Cons - Branches and readability. carbon (2)

What are your thoughts on this?

Discussion

Subscribe

pic

CollapseExpand

I face this dilemma as well as I like to avoid excessive branching if possible. However, If you follow the recommendations from Clean Code amazon.com/Clean-Code-Handbook-Sof... you should limit functions to do one thing ONLY and do it very well. For your example above, my advice would be to have one function for the mobile case, a different one for native, and have the name of the function clearly state that. Otherwise the outcome of doIt() is not clear. It can do something or not.

Comment button Reply


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK