Clean Code: Chapter 3 - Functions

Posted by Andy Huggins on January 22, 2016

There are some pretty great examples, and if you are a coder you should read this book. Yeah it's chapter 3, but I can already tell that this book will be referenced in the future for quite some time.

Shorter functions are much preferred. There is no hard rule on number of lines, but it seems to be that anything over 10 is likely going to have something that could be moved to a function of it's own.

The big takeaway is that a function should do one thing. It should do it well, it should do it clearly and the name of the function should reflect what it does. As one programmer put it, clean code is code that works the way you would expect.

An interesting point was made that functions are verbs and classes are nouns. Seems like something worth noting.

Also a function should only have one level of indentation...possibly two on special occasions. This was made clear to me in this Laracasts episode: One level of indentation.

Basically, you can structure your code to only have one level of indentation, this keeps it simple. If within If within If with a few Else's quickly becomes very trying to understand.

Switch statements should be avoided except if they are not duplicated and buried in a class that returns polymorphism. This seems to make sense and is a pretty clear sign that more than one thing is being done in a function.

Generally, it is best to have no arguments to pass to a function, but one argument is ok, two should be special cases, and three should be avoided.

Although it was not a section, it seems that there is a hint of placing a function on the right object. I think this will be covered later in the book, but it is definitely hinted at in this chapter. Sometimes you can have a function on an object because it is convenient, but really it would be better to rewrite it so that the function is called on the object that it accepts as a parameter. So if you have a $user object that has a method $user->open(Account $account) would be better to have $account->open() instead. I'm sure this will be covered in more detail, but it is a good point.