Day 19 | #100DaysOfCode

Writing Clean Code To Avoid Pain

How to format your code and handle errors?

Dhananjay Trivedi


Formatting your Code

We are developers/engineers/coders, and our code should look like its written by an engineer. We must have some strict guidelines that we stick to while writing code and if we are working with some team, the team should have a meeting and should come down to a common understanding around standards of coding the whole team will strictly follow.

Why is this all-important? Code formatting is about good communication, and communication is the professional developer’s first order of business.

“Getting things working” is not your first order of business

Vertical code formatting should be like that of a newspaper, the top should give the heading, then as you start to read the first para you get a gist of the whole story without giving you the details and insights.

Similarly, your code should be like that, it starts from the top and should increase in its complexity as we move downwards.

There should be a blank line between concepts that separates them from each other. You know it will be hard if there would be no vertical lines between concepts. We call it vertical openness.

Logical closely related code in the same file should be at a minimum vertical distance with each other.

Variable declarations should be done as close to where they are being used exactly. If variables are not being reused/make them local / within functions.

If you don’t maintain proper vertical distance between different logics, your code will become confusing to whomsoever reads it. To understand one use-case, your user should clearly be able to understand the logic and data flow amongst various functions and classes.

INSTANCE VARIABLES should be declared at top of the class as they are being used by multiple functions as this is a well-known place to see where those variables are.

The calling function should be above the function being called, this gives a natural top to bottom flow to your program and also try not to exceed 120 characters per line.

Error Handling

Things can go wrong, and when they do, we as programmers are responsible for making sure that our code does what it needs to do.

Many codebases are completely dominated by error handling. This doesn’t mean that it's all that they do, but its actually very hard to identify the logic in between all the scattered error handling logic. It’s good to add error handling logic, but it’s bad if its spread all over the place.

Like we have mentioned before, you should always try to use Exceptions instead of an error code. For example,

Don’t ❌

var foodItems = getAllFoodItems()
if (foodItems.status == ERROR) {
} else if (status == FoodItemList) {

Do ✅

try {
var listOfFoodItems = getAllFoodItems()
} catch (your exception type) {

Use Unchecked Exceptions

There is no debate around that, Python, C#, C++, Ruby they all use unchecked exceptions and they all are used to build Robust Softwares. But you may ask why? whats the cost with checked exceptions?

The cost of using checked exceptions is the Open-Closed Principle. If you throw a checked exception in some method 3 classes below, you must declare that exception in the signature of each method between your method and the catch. If you do it in some middle classes, then you would be violating the Single Responsibility Principle.

You have to add a cascade of throws statements to all of the above higher functions, this removes Encapsulation property right away and violates the SRP.

Also, when you throw some Unchecked exceptions, it is recommended that you provide some context about why and where is this error coming, instead of just ‘Error occurred’.

Try to wrap multiple error classes into one, if you have to add catch blocks for multiple sorts of exception for one specific thing.

You can also simplify the logic, by using the concept of Sealed Classes. This is also called a SPECIAL CASE PATTERN as you make a class that handles the special cases for you, the client doesn’t have to deal with Exceptional Behaviour resulting in a much cleaner looking code.

Never return or pass ‘null’

Earlier I had the practice of passing null around and check if my object is null on the client-side and then handle some error cases. This is very bad, you must never pass or return null.

Every time you pass or return null from somewhere, the other side code gets bloated with one additional line to check for null. God forbid, in one of the cases you forget to check for null, your application spins out of control.

Why would you do that to yourself? Why bloat your own code and risk more null pointer exceptions?

Whenever you are tempted to return null, consider throwing an unchecked exception or return a special use case object like from the concept of Sealed Classes.

If you are calling a third party API which might return null, then create a wrapper class for that library so as to protect your application and yourself from null checks.

We will learn more about working with some foreign third party code in our next story, so make sure to follow and check back for that.

Passing null is even worse! Sadly there is no good way to deal with passing null as arguments, hence the only rational approach is to forbid passing null by default 😔