Should else be avoided? If so, should return true and return false that use to come together really be avoided too?
They're basically suggesting that you avoid functions like this:
public bool IsEdible() {
if (this.ExpirationDate > Date.Now &&
this.ApprovedForConsumption == true &&
this.InspectorId != null) {
return true;
} else {
return false;
}
}
Instead, Clean Code suggests that you do something like:
public bool IsEdible() {
return IsFresh() && IsApproved() && IsInspected();
}
That's not to say that conditionals are evil; everything in moderation is fine. Know when to use the tools in your toolbox, but don't bring out the hammer just because something looks like it might be a nail.
Likewise, if your function tries to bite off more than it can chew, you should break it up into multiple functions:
public void EatAndDiscard(Fruit f) {
try {
f.Peel();
} catch (NoPeelerAvailableException e) {
basket.Notify("fruit " + f.Name + " could not be peeled");
this.WaitFor(this.Peeler);
}
this.Consume(f);
Scraps<Fruit> s = f.GetScraps();
s.Dispose();
}
Instead, try something like:
public void Consume(Fruit f) {
Peel(f);
Eat(f);
Discard(f);
}
It says that functions should have one level of abstraction. Is high-level like ruby or like less indenation level and is low-level like assembly or more indentation level?
"Level of abstraction" is a somewhat nebulous concept, but essentially it means that a method talks about everything at the same plane of understanding. For example, here are some statements about the same problem that are at different levels of abstraction, ordered roughly from lowest to highest:
- A salesman wants to visit N different cities around the country without visiting any city twice, winding up at the same place he started, and in as short a distance as possible.
- A salesman wants to make a closed tour of N cities that requires him to travel the least distance possible.
- Find a closed tour on a graph of N vertices that minimizes the cost.
- Find the shortest Hamiltonian tour on N vertices.
If you were writing a method and you used a HamiltonianTour
object in the same breath as a Salesman
object, that would be a good clue that you were talking about the problem at two different levels of abstraction. This is bad, because it suggests you're not thinking about the problem in a consistent way, which in turn means you may be overcomplicating things.
Having multiple levels of abstraction means that the method is trying to think about things or anticipate situations it probably shouldn't be responsible for, or at least could delegate to somebody else. If your function looks like it has a lot of special conditions or talks about things at too many different levels, it could probably be simplified.