Skip to content

Instantly share code, notes, and snippets.

@vicapow
Last active December 15, 2015 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vicapow/5312339 to your computer and use it in GitHub Desktop.
Save vicapow/5312339 to your computer and use it in GitHub Desktop.

how to be kind to your future self and others

avoid if statement hell.

this:

if(thing){
    if(someThingElse){
        if(thisOtherThing){
            if(oneMoreThing){
                doSomethingUseful()
            }else{
                return oneMoreError
            }
        }else{
            return thisError
        }
    }else{
        return someOtherError
    }
}else{
    return someError
}
// 17 LOC, 327 characters

should be:

if(!thing){
    return someError
}
if(!someThingElse){
    return someOtherError
}
if(!thisOtherThing){
    return thisError
}
if(!oneMoreThing){
    return oneMoreError
}
doSomethingUseful()
// 13 LOC, 191 characters

but this can be ever better if we remove the curly brackets.

if(!thing) return someError
if(!someThingElse) return someOtherError
if(!thisOtherThing) return thisError
if(!oneMoreThing) return oneMoreError
doSomethingUseful()
// 5 LOC, 163 characters

avoid negation in if/else statements.

(note that the above heuristic should take priority over this one)

if(!aThing) itsNotAThing()
else itIsAThing()

what your brain sees: if (not) a thing its not a thing else it is a thing

if(aThing) itIsAThing()
else itsNotAThing()

what your brain sees: if a thing it is a thing else its not a thing

its very easy for brain compilers to miss small none alphabet characters (since its most often actively ignoring other none alphabet characters like (, ) , {, } and ; ) your brain compiler is also very fast at reading words since it already has a lot of experience reading books

function names should be legible but not verbose. optimize for readability / length

if(friend(person)) doSomething(person)

what your brain reads: "If friend person do something person" - wtf?

should be

if(isFriend(person)) doSomething(person)

what your brain reads: "If is friend person do something person" - ok..

even better

if(person.isFriend()) doSomethingWith(person)

what your brain reads: "If person is friend do something with person" - sweet

worse

if(person.isFriend()) doSomethingWithThePersonThatIsMyFriend(person)

what your brain reads: "If person is friend do something with the person that is my friend person" - ok

this might be easier for your brain to read but it's much less memorable. Brain compilers are terrible at dealing with long function names

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment