A Beginner's Guide To Writing Clean Code
Julius Olajumoke
Posted on November 10, 2020
When writing code, we are most times tempted to focus more on making our code work and sacrificing the most important thing of making it's intents clear and readable for others to understand.
Writing code is an art, writing clean code is a beauty
Knowing the ever growing rate that which collaboration happens among developers especially through Open Source, it is needful we have a conversation about writing clean code
In this post, I explained the fundamentals to writing clean code and I strongly recommend you go through it. Some of the ideas in this post are gotten from Clean Code, written by Robert C. Martin also known as "Uncle Bob".
Concise Variable Name
Naming variable should be clear enough to understand and self explanatory without writing a line of comment. The use of "intention-revealing" names should be paramount, although it might take time to get a good name for your variable but it saves more in return. A concise variable name should answer all big questions about it use and place in your code. It should tell you why it exists, what it does and how it is used.
Best Practice for Naming Variables
Use Pronounceable Names - adopt this method of "if you can't pronounce it you can't discuss it" remember the goal is to write clean code that can communicate our intent to other people.
Use Searchable Names - single-letter names and numeric constants have problem of not easily located in code especially when it becomes larger. For example using a variable e is a poor choice on which a programmer might need to perform search.
Avoid Disinformation
Disinformation should be avoided at all cost because it makes the code difficult to understand and most times gives false information about your code. Avoid using keywords, ambiguous words, inconsistent spellings and disinformative names. An example of disinformation is the use of a lowercase L and uppercase O you will see that they look almost entirely the same with constant one and zero.
int a = l;
if(O == l)
a = O1;
else
l = 01;
Naming Classes
When naming a class and an object, it is expected to be a noun or noun phrases like Customer, WikiPage, Account and AddressParser. Words like Manager, Processor, Data or Info should be avoided in the naming of a class. Also, class name should not be a verb.
Naming of Methods
Method names should be a verb or verb phrase like getAccount, getCurrency or save. Accessors, mutators and predicates should be named for their value and prefixed with get, set, and is according to the javabean standard.
customer.setName("mike");
Writing Functions
The first rule of writing functions is that they should be small and very small. Making functions small, means that it’s intent can easily be communicated to a casual reader.
Also functions should do only one thing. Functions doing one thing can only be possible if the functions are small. Although it might be difficult to denote if a function is doing multiple things or not but can be possible by extracting another function with a different name. If you can get one, then you can create a function.
For example this function below gets a user details checks if they exists to avoid duplicate entries and adds the user if it is not existing.
function registerUser($fullname, $email, $password){
if(userExist($email)){
return "User already exists";
} else {
addUser($fullname,$email, $password);
}
}
The above function example is not up to 10 lines of code but performs 3 different functions and these functions are encapsulated into the if else conditional statement.
Best Practice for Writing Functions
Avoid too Many Arguments — arguments in a function should not be more than two and three or more should only be used with special justification. Too many arguments becomes difficult when testing, imagine the difficulty in writing all the test cases to ensure that all the various combinations of arguments work properly. One of the ways to reduce arguments is by declaring instance variable.
Error Handling — as earlier stated that functions should always do one thing. Error handling is one thing, thus a function should be written to handle errors and nothing else.
Writing Classes
The first rule of classes is that they should be small the second rule is that they should be smaller. This should not be confused with functions. With functions we measure size by counting physical lines, with classes we measure size by counting responsibilities.
Also the name of a class should describe what responsibilities it fulfills. In fact, naming is probably the first way of helping determine the class size. If we can not derive a concise name for a class, then it’s is likely to be large. For the example below a DailyReport class has responsibilities of sending account enrollment, transactions and users report daily.
public class DailyReport extends Base_Controller {
public function accountReport(){}
public function transactionReport(){}
public function usersReport(){}
}
Best Practice for Writing Classes
- Adopting the Single Responsibility Principle — it states that a class or module should have one and only one reason to change. This principle gives us both a definition of responsibility and guidelines for class size.
- Cohension — classes should have a small number of instance variables and the methods in the class are allowed to manipulate one or more of those variables. A class in which each variable is used by each method is maximally cohesive.
Comments
The proper use of comments is to compensate for our failure to express ourself in code. Ideally comments are not needed at all. If your code needs comment it means you are doing something wrong.
Don’t comment bad code — rewrite it. — Brain W. Kernighan
Modern programming language have English words through which code can be self-explanatory if well written. So when you find yourself in a position where you need to write a comment, think it through and see whether there isn’t some way to turn the table and express yourself in code.
Legal comments i.e copyrights and license statements are not put into consideration here because they are necessary.
Avoid Code Repetition
Code repetition is considered to be the root of all evil in programming. Duplicate code simply means changing things in multiple places when change is required and they are usually error prone.
Avoid leaving Code in Comment
Leaving code in comments, makes your code scary to read and understand. If you are not using the code, simply delete it. In cases where this codes are extremely important you can make use of version control like Git and Subversion.
Conclusion
Writing clean code is not something that can be acquired overnight but it can be achieved as you consciously make the effort by adopting these principles when writing code.
Thanks for reading this and I believe it was helpful.
Kindly follow for more stories.
I am a Full stack developer and I am open to any remote position. Check me out on Github
Posted on November 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.