My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
"Clean Code" Book Summary, Part 2-b: Functions continued.

"Clean Code" Book Summary, Part 2-b: Functions continued.

Amir Anwar's photo
Amir Anwar
·Feb 9, 2017

And the summary continues for the Clean Code book by Robert C. Martin.

This is the second part regarding functions or methods, please note that this summary is intended to be a quick reference for the rules listed in the book.

You can go to part 1 from here and Part 2-a from here.

Part 2-b: Functions:

"Master programmers think of systems as stories to be told rather than programs to be written." Author.

  • We should never use output arguments in functions, i.e. functions that takes a variable as its argument, then change its state, it is very confusing.
  • It is better that functions shouldn't have arguments at all!, or at least one argument, three arguments maximum.
  • We can convert two arguments of a 3 or more argument function to be part of a class like e.g.:
      Circle makeCircle(double x, double y, double radius);
      Circle makeCircle(Point center, double radius);
    
  • Or we can use argument lists if all arguments are of the same type:
      public String format(String format, Object... args)
    
  • Don't return a boolean as a validation for the successful operation of a function.
  • A try and catch block should exist alone in one function i.e. error handling is one thing to do, as we have said previously, functions should do only one thing.

A good quote from the book:

"When I write functions, they come out long and complicated. They have lots of indenting and nested loops. They have long argument lists. The names are arbitrary, and there is duplicated code. But I also have a suite of unit tests that cover every one of those clumsy lines of code. So then I massage and refine that code, splitting out functions, changing names, eliminating duplication. I shrink the methods and reorder them. Sometimes I break out whole classes, all the while keeping the tests passing. In the end, I wind up with functions that follow the rules I’ve laid down in this chapter. I don’t write them that way to start. I don’t think anyone could." the author

Go to Part 3