Skip to main content
1 of 2
Bogdan
  • 3.7k
  • 13
  • 13

There are no hard rules for when to extract boolean conditions into their own function. It depends a lot on the logic happening in the code, how much code there is, how readable it is, if you need to reuse the condition some place else also, etc.

When it's about reusability, the answer it pretty much straight forward. If you need the same check in multiple places, it's a good idea to extract the condition in a function and reuse it.

Other cases are not as clear cut as reusability. Too many conditions in the code can make the code hard to read. You then extract the condition in variables to better expose the logic, so your brain doesn't need to focus on each if to evaluate the conditions (a properly named variable better expresses this). But if you have a lot of these variables, even if the logic would be easier to read, you can still have a large fucntions. Size of the method adds to it being less readable. So it might make sense to replace those variables with a function call. You will then have smaller functions, doing less things. Sometimes you can even replace related conditions with a single function. There is a lot to say about so I'll stop here and instead leave you with some resources to read:

  • Martin Fowler's book on Refactoring has a full chapter dedicated to simplifying conditionals;
  • if you don't have the refactoring book, you can read about the techniques here.
Bogdan
  • 3.7k
  • 13
  • 13