Clean Code – Part 6

This post is part of clean code’s series, you can check the previous parts from here

Clean Code – Part 1
Clean Code – Part 2
Clean Code – Part 3
Clean Code – Part 4
Clean Code – Part 5

Today, I will cover Chapter 10

{Classes}

  • Class Organization

Following the standard Java convention, a class should begin with a list of variables. Public static constants, if any, should come first. Then private static variables, followed by private instance variables. Public functions should follow the list of variables.

  • Encapsulation

We like to keep our variables and utility functions private.

  • Classes Should Be Small!

The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that. With functions we measured size by counting physical lines. With classes we count responsibilities. The name of a class should describe what responsibilities it fulfills.

  • The Single Responsibility Principle [SRP]

It states that a class or module should have one, and only one, reason to change.
We want our systems to be composed of many small classes, not a few large ones.
Each small class encapsulates a single responsibility, has a single reason to change, and collaborates with a few others to achieve the desired system behaviors.

  • Cohesion

Classes should have a small number of instance variables. Each of the methods of a class should manipulate one or more of those variables.
A class in which each variable is used by each method is maximally cohesive.
When cohesion is high, it means that the methods and variables of the class are co-dependent and hang together as a logical whole.

  • Maintaining Cohesion Results in Many Small Classes
  • Organizing for Change

In a clean system we organize our classes so as to reduce the risk of change.

  • Open-Closed Principle [OCP]

Classes should be open for extension but closed for modification.

  • Isolating from Change

Needs will change, therefore code will change.
A client class depending upon concrete details is at risk when those details change.

  • Dependency Inversion Principle [DIP]

Classes should depend upon abstractions, not on concrete details.

Motivational Note

One day, someone gonna read your code and appreciate it saying “It’s a piece of Art” 😀

good_code

Advertisements

Clean Code – Part 5

This post is part of clean code’s series, you can check the previous parts from here

Clean Code – Part 1
Clean Code – Part 2
Clean Code – Part 3
Clean Code – Part 4

Today, I will cover Chapter 9

{Unit Tests}

Test code is just as important as production code. It is not a second-class citizen. It requires thought, design, and care. It must be kept as clean as production code.
– Robert C. Martin, Clean Code

  • Test Driven Development [TDD]

TDD asks us to write unit tests first, before we write production code.

  • Keeping Tests Clean

Having dirty tests is equivalent to, if not worse than, having no tests.
The problem is that tests must change as the production code evolves.
The dirtier the tests, the harder they are to change.

  • Clean Tests

Readability is perhaps even more important in unit tests than it is in production code. What makes tests readable? clarity, simplicity, and density of expression.

  • Asserts per Test

The number of asserts in a test ought to be minimized.

  • Single Concept per Test

We want to test a single concept in each test function. We don’t want long test functions that go testing one miscellaneous thing after another.

  • F.I.R.S.T.

Clean tests follow five other rules that form the above acronym:

1. Fast:

Tests should be fast. They should run quickly.

2. Independent:

Tests should not depend on each other.
You should be able to run each test independently and run the tests in
any order you like.

3. Repeatable:

Tests should be repeatable in any environment (ex. Production env, QA env .. etc)

4. Self-Validating:

Tests should have a boolean output. Either they pass or fail.

5. Timely:

The tests need to be written in a timely fashion. Unit tests should be written just before the production code that makes them pass.

Tests preserve and enhance the flexibility, maintainability, and reusability of the production code. If you let the tests rot, then your code will rot too. Keep your tests clean.
– Robert C. Martin, Clean Code

Next time you write your code, don’t forget about your tests .. or you will always assume that code works because it’s MAGIC 😀

Strip-Ou-sont-les-tests-unitaires-english650-final.jpg

Clean Code – Part 4

This post is part of clean code’s series

Clean Code – Part 1
Clean Code – Part 2
Clean Code – Part 3

Today, I am gonna cover Chapter 6 and 7

{Objects and Data Structures}

There is a reason that we keep our variables private. We don’t want anyone else to depend on them.
– Robert C. Martin, Clean Code

  • Data Abstraction

Hiding implementation is not just a matter of putting a layer of functions between the variables.
Hiding implementation is about abstractions! A class does not simply push its variables out through getters and setters. Rather it exposes abstract interfaces that allow its users to manipulate the essence of the data, without having to know its implementation.
Objects hide their data behind abstractions and expose functions that operate on that data.

  • Data/Object Anti-Symmetry

Objects hide their data behind abstractions and expose functions that operate on that data. Data structure expose their data and have no meaningful functions.
– Robert C. Martin, Clean Code

To understand this point, refer to the given example in Objects and Data Structures section.

{Error Handling}

  • Use Exceptions Rather Than Return Codes
  • Use Unchecked Exceptions

The price of checked exceptions is an Open/Closed Principle violation, Encapsulation is broken because all functions in the path of a throw must know about details of that low-level exception.

  • Provide Context with Exceptions

Create informative error messages and pass them along with your exceptions. Mention the operation that failed and the type of failure.

  • Don’t Return Null

If you are tempted to return null from a method, consider throwing an exception or returning a SPECIAL CASE object instead.
SPECIAL CASE object: means that you create a class or configure an object so that it handles a special case for you.

  • Don’t Pass Null

Returning null from methods is bad, but passing null into methods is worse.

So take care of Nullability 😀

java-8-the-good-the-bad-and-the-ugly-8-638

Important Note
Wrapping third-party APIs is a best practice. When you wrap a third-party API, you minimize your dependencies upon it. You can choose to move to a different library in the future without much penalty.
Another advantage of wrapping is that you aren’t tied to a particular vendor’s API design choices. You can define an API that you feel comfortable with.

Clean Code – Part 3

If you are new here, you should refer to the previous parts of this series to understand what is going on.

Clean Code – Part 1
Clean Code – Part 2

Today, I will talk about Chapter 3

{Functions}

Functions are the first line of organization in any program.
– Robert C. Martin, Clean Code

  • Small!

The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that.
Functions should hardly ever be 20 lines long.

  • Do One Thing

Functions should do one thing. They should do it well. They should do it only.

  • Reading Code from Top to Bottom: [The Step-down Rule]

We want the code to read like a top-down narrative. We want every function to be followed by those at the next level of abstraction so that we can read the program, descending one level of abstraction at a time as we read down the list of functions.

  • Switch Statements

We can make sure that each switch statement is buried in a low-level class and is never repeated. We do this, of course, with polymorphism.

  • Use Descriptive Names

The smaller and more focused a function is, the easier it is to choose a descriptive name.
Also don’t be afraid to make a name long. A long descriptive name is better than a short enigmatic name.
Be consistent in your names. Use the same phrases, nouns, and verbs in the function names you choose for your modules.

  • Function Arguments

Minimize the number of arguments.
Arguments are even harder from a testing point of view. Imagine the difficulty of writing all the test cases to ensure that all the various combinations of arguments work properly.
When a function seems to need more than two or three arguments, it is likely that some of those arguments ought to be wrapped into a class of their own.

  • Argument Lists

Sometimes we want to pass a variable number of arguments into a function.

  • Have No Side Effects

Side effects are lies. Your function promises to do one thing, but it also does other hidden things.

  • Command Query Separation

Functions should either do something or answer something, but not both. Either your function should change the state of an object, or it should return some information about that object. Doing both often leads to confusion.

  • Prefer Exceptions to Returning Error Codes

Returning error codes from command functions is a subtle violation of command query separation.

  • Extract Try/Catch Blocks

It is better to extract the bodies of the try and catch blocks out into functions of their own.

  • Error Handling Is One Thing

Functions should do one thing. Error handing is one thing. Thus, a function that handles errors should do nothing else.

  • Don’t Repeat Yourself

Duplication may be the root of all evil in software. Many principles and practices have been created for the purpose of controlling or eliminating it.

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.

Master programmers think of systems as stories to be told rather than programs to be written.
– Robert C. Martin, Clean Code

Watch what you write! or it will turn out to be a monster.

depressed-developer-6

Clean Code – Part 2

I talked in my previous post Clean Code – Part 1 that I will summarize some chapters from Clean Code book in a series of posts.

Today I will talk about Chapter 2

{Meaningful Names}

Names are everywhere in software. We name our variables, our functions, our arguments, classes, and packages. We name our source files and the directories that contain them. We name and name and name.
 Robert C. Martin, Clean Code

Here is some rules to follow while naming things in your code.

  • Use Intentional Reviling Names

The name of a variable, function, or class, should answer all the big questions.
It should tell you why it exists, what it does, and how it is used.

  • Avoid Disinformation

Programmers must avoid leaving false clues that obscure the meaning of code.
We should avoid words whose entrenched meanings vary from our intended meaning.

  • Make Meaningful Distinctions

It is not sufficient to add number series or noise words, even though the compiler is satisfied.
If names must be different, then they should also mean something different.
Distinguish names in such a way that the reader knows what the differences offer.

  • Use Pronounceable Names

It would be a shame not to take advantage of that huge portion of our brains
that has evolved to deal with spoken language. So make your names pronounceable.
If you can’t pronounce it, you can’t discuss it without sounding like an idiot.

  • Use Searchable Names

Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text.

  • Avoid Encoding

Encoded names are seldom pronounceable and are easy to mistype.
So don’t put types of variables into its names.

One difference between a smart programmer and a professional programmer is that
the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.
 Robert C. Martin, Clean Code

  • Class Names

Classes and objects should have noun or noun phrase names. A class name should not be a verb.

  • Method Names

Methods should have verb or verb phrase names like postPayment, deletePage, or save.
Accessors, mutators, and predicates should be named for their value and prefixed with get, set, and is.

Choose clarity over entertainment value.
Say what you mean. Mean what you say.
 Robert C. Martin, Clean Code

  • Pick One Word per Concept

Pick one word for one abstract concept and stick with it. For instance, it’s confusing to have fetch, retrieve, and get as equivalent methods of different classes.
The function names have to stand alone, and they have to be consistent in order for you to pick the correct method without any additional exploration.
A consistent lexicon is a great boon to the programmers who must use your code.

  • Don’t Pun

Avoid using the same word for two purposes. Using the same term for two different ideas is essentially a pun.

  • Use Solution Domain Names

Remember that the people who read your code will be programmers. So go ahead and use computer science (CS) terms, algorithm names, pattern names, math terms, and so forth.

  • Use Problem Domain Names

When there is no “programmer-eese” for what you’re doing, use the name from the problem domain. At least the programmer who maintains your code can ask a domain expert what it means.

  • Add Meaningful Context

You need to place names in context for your reader by enclosing them in well-named classes, functions, or namespaces.

The hardest thing about choosing good names is that it requires good descriptive skills and a shared cultural background.
– Robert C. Martin, Clean Code

But don’t overthink the naming too much or you will go BUST! 😀

Strip-Trouver-le-nom-de-variable-english650-final

Clean Code – Part 1

From about a month, I decided to read a book that I was always interested in. I think you can guess the book name from the title. Yup you guessed it right 😀 , It is Clean Code by Robert C. Martin, colloquially known as “Uncle Bob“.

Mmm, So …

What is Clean Code ?

The most beautiful definition that I quoted from the book is

Clean code always looks like it was written by someone who cares.
 Michael Feathers [1]

Uncle Bob see that we are authors of our code, and that means we have readers. And for sure it is authors responsibility to communicate well with their readers.

Most of our time as Software Engineers is spent in reading others or ours old code to be able to write new code.

So if we left our code cleaner than we found it, Can you imagine working on a project where the code simply got better as time passed ? Can you imagine the result of this incremental improvements ?

To know Uncle Bob’s detailed opinion about clean code, We will dig deeper in his book with a series of posts that will summarize some chapters.

Stay Tuned Yaaaay 😀

code-review-2

Caution
This book can’t promise to make you a good programmer. It can’t promise to give you “code-sense”. All it can do is show you the thought processes of good programmers and the tricks, techniques, and tools that they use.

To be good with clean code, You have to

Practice

Practice

Practice!


References

  1. Author of Working Effectively with Legacy Code