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 😀
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.