CLEAN CODE – A HANDBOOK OF AGILE CRAFTSMANSHIP

Bad code can function. But if the code is not clean, it can put a software development company on its knees. Over the world, outstanding resources are lost in the name of poorly designed code. But it does not have to be like this. In August 2008, acclaimed software expert Robert C Martin presented a comprehensive book named Clean Code. The book instils within you the core values of a software craftsman and approaches to designing clean code and making you a better programmer.

HOW THIS BOOK HELPED US?

This book helped us comprehend that becoming better software artisans and writing clean code is what we must do to regard ourselves as professionals. Clean code throws light on unit testing, formatting, debugging and utilising descriptive names, which help us write cleaner and more robust code for our clients. Writing clean code is a matter of personal habit and much of a skill. Over time, you’ll have to grow through experience and knowledge to write clean code.

THE BOOK EXPLAINED UNDER 60 SECONDS

The writer emphasises functions; they should be small, perform one task and have descriptive names. He argues that if a function requires many configuration arguments, consider integrating them into a single configurations options variable.

The book emphasises developers to stick to the Single Responsibility Principle, which states that a class or module must have one reason to change. This principle gave us a definition of responsibility and guidelines for class size. Classes must have one responsibility and one reason to change.

TOP THREE QUOTES

“Code without tests is not clean. No matter how elegant it is, how readable and accessible, it is unclean if it hath not tests.”

“Every system is built from a domain-specific language designed by the programmers to describe that system. Functions are the verbs of that language, and classes are the nouns.”

“Error handling is important, but if it obscures logic, it’s wrong.”

BOOK SUMMARIES AND NOTES

Chapter one: Clean Code

Clean code matters: wrong code will eventually bring a business down because, during more development, productivity steadily approaches zero.

The total cost of owning a mess increases over time. The more messy code becomes the fewer chances of cleaning it up. The team’s productivity decreases as the mess grow because they’re under pressure to meet a deadline or want to increase productivity.

It consumes time and resources to rebuild a system from scratch. Refactoring and gradual improvements are usually the better options to take. Keeping your code clean is cost-effective and a matter of professional survival.

You’d spend months trying to accomplish a task that would have only taken hours in messy code. Good code quickly rots wrong code because requirements change in approaches thwarts the original design.

Clean code is well-tested and performs one task effectively, as lousy code usually negligently does too much.

Messy codes slow down developers, yet all feel pressured to make a mess to meet deadlines. Usually, you’ll not make the deadline by making a mess. The only way to make the deadline is to maintain clean code.

Favourite quote of the chapter: “Writing clean code is what you must do to call yourself a professional. There is no reasonable excuse for doing anything less than your best.”

Chapter two: Meaningful Names

It’s undemanding to comment that names should disclose their purpose. Selecting good names consumes time but saves more than it takes. Take care of your chosen names and change them when you find finer ones.

Choosing a good name is complex, and the name of a function or variable should explain what it is, how it is used, and why it exists. If a name calls for a comment, it doesn’t reveal its intent.

You have to avoid leaving false clues that hide the meaning of code. Avoid words whose established meanings vary from your intended meaning.

Avoid using abbreviations in function names and single-character variable names, except for commonly used names like “i” for the counter variable in a loop.

Variables should be pronounceable so you can talk about them and say them out loud. You can only discuss them with your teammates if you can pronounce them.

Single-letter names and numeric constants have a specific problem. It takes work to locate across a body of text. Single-letter names can only be used as local variables inside short methods.

Favourite quote of the chapter: “A long descriptive name is better than a long descriptive comment.”

Chapter three: Functions

The first rule of functions is; they have to be minor, and the second rule is they should execute only one task. Functions should be insignificant to the extent of holding nested structures. Therefore, the indent level of a function must not be greater than one or two. This makes the functions easier to read and understand.

Functions ought to have as few parameters as possible. Parameters tend to make functions hard to comprehend and are on a lower level of abstraction. Avoid using parameters as best you can by introducing abstract helper classes or turning arguments into member variables.

To ensure that your functions perform one task, you must ensure that the statements within your functions are all at the same level of abstraction.

Use meaningful names to label your functions. Descriptive names explain what a function does. The smaller and more focused a function is, the easier it is to choose a descriptive name.

Favourite quote of the chapter: “You know you are working on clean code when each routine turns out to be pretty much what you expected.”

Chapter four: Comments

The actual use of comments compensates for your failure to express yourself in code. Comments are consistently failures. You ought to have them because you can only sometimes figure out how to describe yourself without them.

Clean and expressive code with few comments is much better than cluttered and complex code with many comments. Therefore, spend time cleaning the mess in your code rather than spending it writing comments that explain your mess.

Most comments are crutches and justifications for poor code. Comments can be avoided using distinctly named variables and extracting code sections into clearly named functions.

Don’t utilise Javadocs just for the sake of using them. Comments that explain what a method does, what arguments it takes and what it returns are usually redundant at best and misleading at worst.

Comments must include all the applicable information and context anyone reading the comments will need. Don’t be lazy when writing comments.

Favourite quote of the chapter: “Don’t comment bad code—rewrite.”

Chapter Five: Formatting

Ensure that your code is attractively formatted. Select a specific set of manageable rules that control the format of your code. Then, consistently implement those rules to your code. It’s better if you have a tool to implement those formatting rules.

Code formatting is essential. It’s too crucial to be ignored. Don’t count on humans to manually catch and correct every formatting error. But instead, use an automated code formatter and code linter. This is efficient and productive and saves time during code reviews.

Source files should be like a newspaper article. The name has to be simple but explanatory. The name should be sufficient to tell whether you’re in a suitable module. The upmost parts of your source file should offer high-level concepts and algorithms. Then, the details should increase as you move downwards.

Variables have to be declared close to where they’re used. For small functions, this usually is at the top of the function. Even for short functions, format them well instead of writing them in a single line.

Favourite quote of the chapter: “Code formatting is important. It is too important to ignore, and it is too important to treat religiously. Code formatting is about communication, and communication is the professional developer’s first order of business.”

Chapter six: Objects and Data Structures

You keep your variables private because you don’t want anyone else to depend on them. You want to keep the freedom to change their type or implementation impulsively. Many developers automatically add getters and setters to their objects, revealing their private variables like they were public.

Don’t add getters and setters by default, but rather provide an abstract interface to the data so that you can adjust the implementation without thinking about clients.

Objects put their data behind abstractions and reveal functions that work on that data out of sight. Data structures expose their data and don’t have meaningful functions.

The Law of Demeter states a module should not know about the object’s innards it manipulates. This means an object should not reveal its internal structure through accessors because to do so is to expose, instead of hiding, its internal structure. Since objects hide data and expose behaviour, adding new objects without changing the current behaviours is effortless. Data structures reveal data and have no unusual behaviour, making adding new behaviours to the existing data structures easy.

Favourite quote of the chapter: “In any given system, we will sometimes want the flexibility to add new data types, so we prefer objects for that part of the system. Other times we will want the flexibility to add new behaviours. So we prefer data types and procedures in that part of the system.”

Chapter seven: Error Handling

Error handling is essential, and there is usually much of it during programming. Still, it should not hide the principal intention of the code. Therefore, utilise expectations rather than return codes.

The exceptions should be informative and provide objective, context and error type detail to someone getting the error message would require troubleshooting effectively.

Exceptions define the scope of your program. When you implement code in the try portion of a try-catch-finally statement, you express that execution can terminate at any point and restart at the catch.

When you wrap third-party APIs in a thin layer of abstraction, it becomes easier to exchange one library for another in the future and mock the library during testing.

Favourite quote of the chapter: “Clean code is readable, but it must also be robust. These are not conflicting goals. We can write robust clean code if we see error handling as a particular concern.”

Chapter eight: Boundaries

Third-party code will assist you in getting more functionality delivered in less time. It’s not your job to test third-party code, but it should be your interest to write tests for the third-party code you use.

Learning tests are precise experiments that help increase your understanding. Learning tests confirm that the third-party packages you use operate the way you anticipate them to. There are no assurances that the third-party code will stay compatible with your needs when combined.

Good software accommodates change without significant investments and rework. When you use code beyond your control, exceptional care must be taken to protect your investment and ensure that future change is manageable.

Third-party boundaries are managed by having a few places in the code that refer to them.

Avoid letting too much of your code know about the third-party particulars. It’s better to rely on something you can control than something you can’t control.

Favourite quote of the chapter: “We should avoid letting too much of our code know about third-party particulars. It’s better to depend on something you control than on something you don’t control, lest it controls you.”

Chapter nine: Unit Tests

Test-Driven Development requires you to write unit tests before writing production code. You can’t write production code until you’ve written a failing unit test. Test code must be kelt as clean as production code with limited exceptions, commonly involving memory or efficiency.

Ensure to keep your tests clean or less; you’ll lose them. And in their absence, you lose the only thing that keeps your code reusable, flexible and maintainable. You won’t fear making code changes when tests are present, but every change is a feasible bug without them.

Readability is what makes a test clean. Readability maybe even more essential in unit tests than in production code. Clarity, simplicity and density of expression are what make tests readable. In a test, you have to say a lot with a few expressions as possible.

Usually, you’d like to test a single concept in each test function. You don’t want extended test functions that go testing one diversified thing after another.

Just like the production code, tests are also crucial to the robustness of the project. Tests are necessary because they enhance and preserve the code’s reusability, maintainability, and flexibility. Keep your tests clean, and work to make them meaningful and brief. Develop APIs that act as a domain-specific language that helps you write tests.

Favourite quote of the chapter: “Tests need to be written in a timely fashion. Unit tests should be written just before the production code that makes them pass.”

Chapter ten: Classes

Classes have to begin with a list of variables. Public static constants should come first, then private static variables, followed by private instance variables. Put the private utilities called by a public function right after it.

The first rule of classes is that they have to be small. Just like functions, being small is the principal rule for creating classes. But the real question is always, “how small?”. With functions, you calculate size by counting physical lines. With classes, you measure size by counting responsibilities.

Classes must have a small number of instance variables. Every method of a class should control one or more of those variables. The more variables a method influences, the more cohesive it is to its class.

Use many small classes rather than a few large classes in your application. This minimises the amount of information a fellow developer will need to comprehend when working on any given task.

Favourite quote of the chapter: “A class or module should have one, and only one, reason to change.”

HOW THIS BOOK CAN HELP SOFTWARE DEVELOPERS?

“Clean Code” by Robert C. Martin can help software developers improve the quality of their code. It provides practical advice and guidelines on how to write readable, maintainable, and efficient code. The book covers naming, commenting, formatting, and testing topics and emphasises the importance of simplicity, clarity, and consistency in coding practices. By following the principles outlined in the book, developers can reduce technical debt, increase productivity, and create more accessible software to understand, modify, and extend. It provides software developers with a comprehensive approach to coding that can help them improve their skills and reduce the cost of maintenance. This book helps programmers to write code that is easy to change and refactor in the future. It is a must-read for any software developer who wants to become a better programmer.

DevologyX OÜ
Harju maakond, Tallinn, Lasnamäe
linnaosa,
Vaike-Paala tn 1, 11415

+372 6359999
[email protected]
DevologyX Limited
Nakawa Business Park
Kampala
Uganda

+256206300922
[email protected]