Andrei Dascalu
1 min readJun 22, 2020

--

It's common to use guard clauses but ...

if (condition)

throw something

else

do something else

can be rewritten as

if (condition)

throw something

do something else

A throw breaks execution and hands it over to the error handling/bubbling system of whatever language/platform you are using.

the ELSE is not needed and can be deleted. It's pretty common knowledge that any code that any code that respects the S does not need ELSE clauses (at most IF guards, but never IF/ELSE). This also means that any legacy code with multi-level if guards can be refactored to use a single level and break logic away to other methods (if needed).

So the problem you are 'solving' is to replace if statements and use a state machine as a solution.

A state machine is a nice pattern, sure, but it should solve an application need (eg: can you represent your logic in state transitions? should you do that?) but not be used as a generic refactoring tool.

If you have a number of 'if' guards that gets you think 'OMG, that's way too many', perhaps try good ol' fashion refactoring while keeping SOLID in mind rather than jump to state machine.

--

--