Return early, or branch – which do you prefer?

Recently I've come across quite a bit of code lately while conducting reviews that looks like so –

(for context, I typically work in C#, but this question honestly applies to most imperative languages I would assume — things would obviously be different in a purely functional world)

/* 1 - Branch in the function and limit scope */ public Bar DoStuff(Foo foo) { if (SomePredicate()) { // if someBool } } 

My knee-jerk refactor that I default to is something like this –

/* 2 - Branch in the function and return early */ public Bar DoStuff(Foo foo) { if (!SomePredicate()) return; // someBool is guaranteed } 

Although there's probably also merit in –

/* 3 - Branch outside of the function */ // calling code if (SomePredicate()) DoStuff(foo); 

I prefer 2, as it'll allow callers to simply invoke the function knowing they won't incorrectly execute code depending on `someBool` to be true if it is in fact false (as it'll return early if so). For some reason, as I've progressed in development branches & indentation blocks have seemed more & more like a code smell to me – thoughts/opinions? Generally curious, as I wouldn't want to be refactoring / advising code under shaky premises.

I've read a fair amount about code style / architecture, and I feel like the general consensus is: tell, don't ask. What that means is rather than rely on some predicates/branching logic to execute the right code, it should instead be structured to simply execute correctly (either by composition, inheritance, etc.). For example, I feel like there are a couple of examples in the classic Gang Of Four Design Patterns book where this type of problem would result in two subclasses inheriting from a common interface. One assuming SomePredicate() to be true, and the other assuming SomePredicate() to be false (however you feel about inheritance, which appears to have somewhat fallen out of style recently).

Anyway, generally curious on the community's thoughts – happy Friday everyone

submitted by /u/difelicemichael
[link] [comments]

from Software Development – methodologies, techniques, and tools. Covering Agile, RUP, Waterfall + more! https://ift.tt/3p5rRjL

Leave a comment

Design a site like this with WordPress.com
Get started
search previous next tag category expand menu location phone mail time cart zoom edit close