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

The examples are only similar to the extent that they do the same. If you look at what intent they communicate - which is an important part of readability - the second example indicates that x>y is a "special case", which just obscures the simple logic of the function.


I agree that what they communicate is important, but I disagree that the early return communicates "x>y" as a special case.

Nothing about early return indicates a special case, but rather just indicate that a conclusion has been reached. A few examples:

    1. A function that compares two arrays, and first checks if they are null or if their lengths differ before checking their individual elements, and potentially recursing. The early returns are likely to be the hottest section of the function, with the element checking being the special case.
    2. A function that searches a list or tree for a node that matches a set of conditions. All but at most one run will use the early returns, making the corpus of the function the special case.
    3. A function that does some processing, with fast paths that handle the vast majority of data, but a slow path for when the fast paths do not apply. The fast path is an early return, but the slow path is the special case.
In other words, I believe that it is incorrect to consider an early return to be a special-case, and interpreting code like so might result in misunderstandings. You should look at the condition to see if it is a special case. The only thing an early return indicate is that the return value has been decided, and no further processing is needed.

I still think that all my examples communicate the exact same to the reader.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

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

Search: