Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Guard clauses are things that return early for trivial or problematic cases. Like https://en.wikipedia.org/wiki/Guard_(computer_science)#Flatt...

They're one of those good practices that look like bad practice to everyone who just got a CS degree. Seems ex-students are unsettled by asymmetry or want to minimize the number of return statements.



Particularly for high performance code when branch prediction is taken to account


Oh, guard clauses might also use continue statements in loops


Why am I even in this function if it shouldn't happen?


Because a lot of languages can't easily express the semantics of "you're not allowed to call the function this way". I mean, suppose you have a function that takes two integers, but the second must be greater than the first. Most type systems don't have any way to represent that at all, let alone conveniently.


Related: don't write if(arg == null) throw ArgumentNullError; at the top of every function. If it's not supposed to happen then just let it throw the error naturally when you dereference it. In C it's even worse because you turned an easily caught segfault into a silent nop.


If the criteria for it not happening is too complicated to expose to the caller




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: