clean-code-php icon indicating copy to clipboard operation
clean-code-php copied to clipboard

How to handle un/happy paths

Open szepeviktor opened this issue 3 years ago • 6 comments

if (error) unhappy path;

happy path;

Happy path should not be in a conditional.

Would you welcome a PR?

szepeviktor avatar Jun 19 '22 20:06 szepeviktor

A similar example has already been described. https://github.com/jupeter/clean-code-php#avoid-nesting-too-deeply-and-return-early-part-2

It may be worth giving a more detailed example of the Return early pattern. https://szymonkrajewski.pl/why-should-you-return-early/

peter-gribanov avatar Jun 20 '22 09:06 peter-gribanov

Hello Peter! Thank you for your response.

This issue is about putting unhappy path in a conditional, and writing happy path as normal flow.

if (!error) happy path;

unhappy path;

:x: This uses Return early pattern but makes you feel that the unhappy path is the desired one. Does it make sense?

szepeviktor avatar Jun 20 '22 10:06 szepeviktor

I like Szymon's article ❤️

szepeviktor avatar Jun 20 '22 10:06 szepeviktor

The Return early is not only about Fail fast. It's normal to prioritize processing successful conditions over failing ones. But in practice, there are more cases in which it is more convenient to process an erroneous case first.

peter-gribanov avatar Jun 20 '22 11:06 peter-gribanov

So what do you suggest?

szepeviktor avatar Jun 20 '22 11:06 szepeviktor

I see the most optimal solution to rewrite the description of Avoid nesting too deeply and return early (part 2) rule and rename it to Return early pattern. In the comments, you can mention the Fail fast pattern for linking these patterns and alternative search.

peter-gribanov avatar Jun 20 '22 11:06 peter-gribanov