Skip to content

Instantly share code, notes, and snippets.

@bearzk
Created February 19, 2021 13:11
Show Gist options
  • Save bearzk/5edc35c7c937c006cbe97e3c5b4ef4b3 to your computer and use it in GitHub Desktop.
Save bearzk/5edc35c7c937c006cbe97e3c5b4ef4b3 to your computer and use it in GitHub Desktop.
Tech Academy Session 2021 #01

Tech Academy Session 2021 #01

Code Smells 01/??

nested conditions, long condition block

I have to hold my breath for too long, maybe not so good for my health.

if (a) {
	if (b) {
		if (c) {
			return act(a, b, c)
		} else {
			return act(a, b)
		}
	} else {
		return act(a)
	}
} else {
  return undefined;
}

flatten it! guard it!

if (!a && !b && !c) {
	return undefined;
}

if (!b) {
	return act(a)
}

if (!c) {
	return act(a, b)
}

return act(a, b, c)

benefit: good for health? requires less focus to understand.

switch statements

switch (condition)
	case condition1:
	    actThisWay()
	case condition2:
		actThatWay()
	case condition3:
		actAnotherWay()
// simple actions -> strategies configuration
const mapping = {
	condition1: actThisWay,
	condition2: actThatWay,
	condition3: actAnotherWay,
}

const func = mapping(condition);
func();
// complex actions -> polymorphism, move methods, push methods deeper, push decision to later point in time
class A {
	act() // actThisWay
}

class B {
	act() // actThatWay
}

class C {
	act() // actAnotherWay
}

const instance = selectInstance(condition);

instance.act()

benefit: less distraction

if (!modelId || !modelType) {
    return undefined;
  }

const model = selectModel(modelType);

return model.fullTransitionUrl(modelId, task);

Trick

Flip it!

flip it, push methods deeper

ah? do I implement canRead on user? user has to know details about everything?

class User {
	canRead(thing) {
		if (thing is that) {
			decideThisWay()
		}
		if (thing is another thing) {
			decideAnotherWay()
		}
	}
}

user = getUser();
user.canRead(thing);
class Thing1 {
	canRead(user) {
		decideThisWay()
	}
}

class Thing2 {
	canRead(user) {
		decideAnotherWay()
	}
}

user = getUser();
user.canRead = (thing) => thing.canRead(user); // flip it!

user.canRead(thing1) // thing1.canRead(user);
user.canRead(thing2) // thing2.canRead(user);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment