HACKER Q&A
📣 adversaryIdiot

Are there any ways to avoid conditional logic?


sitting here at work staring at about 30 lines of conditional logic.

got me thinking, is there a design paradigm that will avoid conditionals all together and yet achieve the same thing? Using java and SQL if it makes any difference.


  👤 prologger Accepted Answer ✓
Write it in Prolog, then you won't have to worry about conditionals.

👤 mindcrime
To some extent you can replace conditional logic with polymorphism in languages that support it (Java does).

See, for example:

https://refactoring.guru/replace-conditional-with-polymorphi...

Note that this can be made to work for simple conditionals. It's probably not going to help if you have really complicated conditions, the kind where you need to break out your old discrete math book and draw a truth table and use DeMorgan's Law and all of those other "rules of inference" to work out what happens.

Note also that there are (practical) limits to this in general. Creating lots of classes and overridden methods just to get rid of some conditional logic has the potential to make things even more byzantine and confusing, not less. But done well, and in limited doses, it can be a viable strategy.


👤 exabrial
I think the biggest thing is composition over inheritance, and try to put your state into a container like CDI (Using Scoped beans).

If those design paradigms don't work, we've actually had a bit of luck using BPMN and executing it via Drools. This is not "easy" per say but our processes and decision tree were not simple either.

Wishing there was a simpler and modern BPMN like language that supported CDI directly.


👤 KenPainter
In some database apps I can replace all conditionals with loops over sets. If the set is empty nothing happens. The same can be done in other situations which i prefer because it's really robust but it requires such a change in thinking that I don't require it of my team and have not thought about it in a long time.

👤 Victerius
What does your code look like? Is it like

    if case=1 then (...)
    if case=2 then (...)
If you have a unique outcome for each case, you'll probably have to take the long way. Without knowing what your code looks like though, it's difficult.

Feel free to fudge variable names, function names, etc.


👤 PaulHoule
Is the problem conditional logic or pretzel logic?