Clean Code
Every developer would like to write code that works, but there is a more important thing than writing working code which is writing clean code.
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
— Martin Fowler
Importance of naming
We define functions, variables, and classes with names, do not differ whatever you named that should explain the meaning and intention of them.
Let`s assume that we give a name for a function, when another developer read the function name, that person should understand the intention of the function.
We should give more attention to naming when we are writing code. Let`s examine below example.
public List<int[]> getThem(int[][] arr, List<int[]> theList) {
List<int[]> res = new ArrayList<>();
for (int[] x : theList) {
int a = x[0];
int b = x[1];
if(a < 0 || b < 0 || a >= arr.length || b >= arr[0].length){
continue;
}
if(arr[a][b] == 1) {
res.add(new int[]{a, b});
}
}
return res;
}When you read this code, could you imagine anything that the code is doing? If you know basic java, you could understand the code with that knowledge normally, but this is not easy with this version. Let`s improve the naming and try again.
public List<Point> getFlaggedPoints(int[][] grid, List<Point> directions) {
List<Point> flaggedCells = new ArrayList<Point>();
for(Point point : directions) {
if(point.x < 0 || point.y < 0
|| point.x >= rowLength || point.y >= colLength){
continue;
}
if(grid[point.x][point.y] == 1) {
flaggedCells.add(new Point(point.x, point.y));
}
}
return flaggedCells;
}Can you see the difference between the two examples? We can read the getFlaggedPoints method easily now. All the logic is same with getThem method, but we have better naming in the getFlaggedPoints for functions and variables.
Another important point when giving the name is that do not use repeated names in the same project which can cause confusion and hard to track when reading the code in the whole project.
Comments
If we want to use comment to explain the function what it does, it is also red flag to tell us that we did not name the function enough well to express the intention. Function names should explain themselves without comments.
It does not mean that we should not use comments at all, but general logic for the necessity of the comments is that they should not be necessary to explain the functions.
One example of redundant comments is
/* findRoom methods which return Room when find suitable with id */
public Room findRoom(int id) { ... }Functions
Functions always should do one thing. First of all, we need to question that is this function doing only one thing? Is it small enough?
public String findAvailableRoom(Hotel hotel, Room room, int person, int budget) {
Room selectedRoom;
for (int i = 0; i < hotel.getRooms().size(); ++i) {
Room eachRoom = hotel.getRooms().get(i);
if (eachRoom.numberOfPerson() > person) {
if(eachRoom.available) {
for(Rate rate : eachRoom.getRates()) {
if(rate < budget) {
selectedRoom = eachRoom;
}
}
}
}
} return selectedRoom.getName();
}
findAvailableRoom function has five indent level which is too much for a function which means it has nested a lot. Besides that we should consider the level of abstraction in the function to understand whether function is doing one thing. For example, numberOfPerson() method has low level of abstraction, but getRooms() method has high level of abstraction. If we will use the single level of abstraction methods in the same function, like basic operations append() , that helps to reduce the complexity of the function.
for loops or if statements should do only function calls.
The Law of Demeter
The law of demeter is a design principle which suggests that a calling object should not have a knowledge about internals of the caller object. Law of demeter has four rules about which methods accessible from calling object. Let`s assume that we have an object called Person ;
- Any methods inside the
Personclass - An object passed as an argument to
getAddressDescription - An object created by
getOccupationfunction - An object instance variable in the
Personclass
class Person { private Language language;public String getFullName() {
return this.getSurname + this.getFirstName; //First rule
}private String getSurname() { … }
private String getFirstName() { … } public String getAddressDescription(Address address) {
return address.getDescription(); //Second rule
}private void getOccupation() {
Occupation occupation = new Occupation();
occupation.description(); // Third rule language.getCount(); // Fourth rule
}}class Occupation {
public void description() { … }
}
- We can call the
getSurnameandgetFirstNamefunctions insidegetFullNamewhich mean Person call any function belongs toPersonclass. - In the
getAddressDescriptionfunction, we can callgetDescriptionfunction because it is passed as argument withAddressobject which means we can call any function belongs toAddressobject. - In the
getOccupationfunction, we can invoke thedescriptionfunction because it is initiated withOccupationobject. - In the
getOccupationfunction, we can call any function belongs toLanguageclass, because it is instance variable ofPersonclass.
Classes
Get Hatice Kumru’s stories in your inbox
Join Medium for free to get updates from this writer.
The same rule we learned in the functions chapter will apply in here also, classes should be small. To understand if a class is small enough, we can check the name of the class. If the class name describes all the responsibilities of that class and it has explanatory name, that is indication that we have a small enough class.
Single Responsibility Principle(SRP) states that
A module should be responsible to one, and only one, actor.
— Robert C. Martin
If we will not follow this principle, we will continue to add responsibilities to our classes and after a while, we have fat, meaningless, and complex classes. Then we will have such side affects;
- It will be hard to find which method in which class
- Increase maintenance time
- There are no boundaries for classes anymore
- It will decrease the readability of the code
Cohesion
Cohesion means that every function, instance variables in the same class serve the same purpose and responsibility.
To make our code more clean and readable, we always aim to high cohesion.
Example of high cohesion with Room class
class Room {
private int roomId;
private String roomName;
public void setRoomName(String roomName, int roomId) { ... }
public String getRoomName() { ... }
public String getRoomRate(int roomId) { ... }
public String getRoomCapacity(int roomId) { ... }
public String getRoomAmenities(int roomId) { ... }
}Example of low cohesion with Room class
class Room {
private String employeeName;
private String address;
private int numberOfRooms;
private String roomName;
public int getRoomCount() { return numberOfRooms; }
public String getAddress() { return address; }
public void setEmployeeName(String employeeName) { ... }
public void setRoomName(String roomName, int roomId) { ... }
public String getRoomName() { ... }
}The usage of instance variables is a good indication of cohesion.
Low cohesion example with Hotel class
class Hotel {
private String employeeName;
private int employeeId;
private Double employeeSalary;
private int numberOfRooms;
private String roomStatus;
public String getEmployeeName() { ... }
public void prepareEmployeeShift(String employeeName, int employeeId) { ... }
public Double setEmployeePayslip(String employeeName, int employeeId, Double employeeSalary) { ... }
public int calculateAvailability(int numberOfRooms, String roomStatus) { ... }
public int calculateMonthlyBudget(int numberOfRooms, String roomStatus) { ... }
}In Hotel class, we have five instance variables and three of them are used mostly used in three methods, and the rest of two variables are used in the two methods. This can show us, Hotel class has two different responsibilities and should be separated as two different classes like Staff and Room .
Order of dependent functions
Functions call other functions. To increase readability, we should put close to callee functions to caller functions based on the order of usage. Let’s examine vertical formatting with this example;
class Order {
public void makeOrder() {
if(getPayment()) {
prepareOrder();
} else {
informCustomer();
}
}
public void getPayment() {}
public void prepareOrder() {}
public void informCustomer() {}
}Boy scout rule
There is a general term coming from Boy Scouts of America;
Always leave the campground cleaner than you found it.
We would like to apply this rule to our codebase. When you have a task in any project, do small changes to leave cleaner than before. It does not have to be big changes. You can do small things like renaming a variable or function, extracting one function into smaller pieces, and so on and that will create a big impact on the project in time.
References
- Clean Code by Robert C. Martin







