A Readable and “DRY” Approach to Guard Clauses?

preview_player
Показать описание
I experimented with a different approach to guard clauses...

🕗 Timestamps:
0:00 - Problem
1:16 - Solution
1:43 - Benefits
2:08 - Drawbacks
3:09 - Conclusion

➖➖➖➖➖➖➖➖➖➖

© Credits
Рекомендации по теме
Комментарии
Автор

My mom said my videos are too long, so here's a shorter one 😁

SingletonSean
Автор

DRY is the nightmare of any overthinker

nothappyz
Автор

mb monads? I think is better to write a flow what should be completed over file. That is give a make a easy append or remove precondition and more flexible.

testolog
Автор

- enums: When(Conditions.Condition1 | Conditions.Condition2)
- An array of Func<bool> like When(Condition1, Condition2, Condition3, () => DoSomething())
-- Or When(Condition1, Condition2, Condition3).ThenRun( () => DoSomething())

jok
Автор

I thought about it for a sec. I would probably just type the guard clause in every method and return null. First drawback that I thought of after watching your solution was "It's harder to debug". From experience I generally avoid passing Actions/Func as method parameters. If you want to overengineer a solution you could use decorator pattern, but it's overkill IMO.

xXAfekXx
Автор

If you are using a language with macros/preprocessor you can just use that to shorten the guards while not doing callbacks and probably improving speed by having everything inlined.

MariomasterNSMBHD
Автор

I think that’s why there are exceptions. But mostly still require a statement(a if or a function call to check and throw the exception), but no need to worry about return values/types.

If just want clean code, use code generators to write the checks. Annotate the code with checking expressions, and inserts into the function body.

Finally, if feeling fancy, this kind of things just state machines. Using a library to make state machine will definitely make it less code.

P.S. Golang error handling is awful IMO.

kice
Автор

Habibi you need a decorator pattern. That will solve your problem.

abeplus
Автор

I use this way if needed to log the issue only. If just for simple and only in several methods, yeah, if-else is better imo. Just copy-paste and don't overdo as well.

RizaMarhaban
Автор

don’t check/validate at every function, instead do it once only at the border to all of them (border to your app or class).

magne
Автор

Congrats, you've almost built a monad!

benqbenq
Автор

Hello Singleton very useful staff but you can make it even more readable using fluent interface / specification pattern mentioning that you want
prevaliation before executing the action

I tried to post a example in pastebin but the comment seems to be removed for some reason

ivandrofly
Автор

Hi Sean,
I dont like that approach, its very clever but it also should not ever be needed due to having a better design. Your class should know if its in a good state or not.

rlyonsiii
Автор

Callback are (almost) never more readable

nothappyz