Before learning about clean code let's know something about bad code. Let's say you are the first one to release an application in the market. And the application is superb and well-written. Now as time passes by with ever-changing times the requirement of your application changes as per customer's needs. Say your application is now used by more users than expected, Then you will have to scale it up. You will also have to make new releases in your application every week or perhaps every day. Now these activities go on for years and years and probably decades as well. In this time we see many developers who work on the application move out and we have new developers coming in who are not at all acquainted with the application. Now suppose the code is written without following certain standards it becomes a mess with time and even small changes added could make it even worse and you are stuck in a loop of tangled modules of code. This will turn out disastrous when the application is huge and monolithic making it hard to understand and maintain.
Now if you are into development you might have come across code with confusing method names, unwanted variable names, improper comments or improper error handling, it affects your efficiency as for adding new functionality you will probably have to go to the old code and analyse it and add improvements to it. This can be disastrous for development projects that have everchanging team structures affecting their efficiency and only adding pressure on the management to get stuck making them think that bringing in new resources for the project would be their last hope. This can even worsen in time when managements decide to migrate to newer technologies coming into the market as they would be now in a race to maintain their old and messy product while working on the development of their new application with the latest technologies.
Now that we know what is bad code let's look at what clean code is! Here are the different meanings of clean code as per different people:-
writing clean code is more important than just writing code.Here are few tips to write cleaner code in your coding life.
1. Descriptive Naming
We use names for almost everything that we code. We use names for file names, action words, URLs, method names, parameter names, variable names, folder directories and whatnot. Thus we must use names which are relevant to the context which we use. This not only helps the developers who are into it but also in future when that piece of code is being modified by new developers working on it.
Suppose you are writing logic for a session duration counter for your application,
which one would be easier to understand? Obviously, it's the second one. This goes on for class names, method names, package names, directory names, image files or some other configurable filenames. Use proper noun forms for your class names like UserAccount, PaymentBean etc. Also, it would be better to have method names with the action that they perform i.e. deleteUserInfo() is much better than simply delete(),and fetchActiveUsers() is much better than fetchList() as they are easier to under. Also if you are using action words for your method names, stick to one. For example, if you have multiple overloaded methods with the same functionality then instead of using multiple verbs like get, fetch, and retrieve it would be better to stick to one.
2. Well Defined functions
Considering the example of fetching data from a database based on user input, lets write pseudocode to achieve this task.
Now if you see this it just looks mess as we have multiple functions defined within a single class. This not only violates the single responsibility principle but also makes code difficult to understand. This can turn out to be more problematic if we have 1000s of lines of code to write. So, to solve this problem it is better to write the different functions in other classes and use them in your code accordingly. We can write an inputValidator class, then a class to fetch the data from the database and so on.
A good code is that which requires minimum comments. Comments are required only when code fails to express itself. Also for bad code, even comments might fail to express themselves. Our code should contain relevant informative comments. Also, too much commenting can make the code worse.
Avoid using comments when the purpose of the code is already served.
As you can see here since the variable name is clear enough to understand adding a comment to it makes no difference. At the same time avoid adding too much information as a comment.
4. Error Handling
Suppose you have written a code that loads a static message from a resource file for your application. Now imagine due to some human error the key you were using for a message has been deleted mistakenly. Now when the application comes to that stage and is unable to fetch that key it crashes. This will be problematic if there is nothing logged in your application logs. Therefore it is important to do proper error handling which helps in maintaining robust code, which is an important part of clean code. Clean code uses meaningful variable names, clear error messages, and a consistent error-handling approach to achieve this clarity.
Clean code uses proper logging mechanisms. It is important to log the proper error message along with timestamps as this can indicate in which bean file or method it occurred. This helps in debugging and monitoring the application, ensuring that issues can be identified and resolved quickly.
Testing is important for clean code. It ensures that your code behaves as expected and continues to do so as changes are made. Writing tests not only helps you catch and fix bugs but also improves the maintainability and reliability of your codebase. For example:- We write unit tests for individual functions or methods to ensure that they work as expected. We usually write all possible scenarios of testing(edge cases) to test our application for all possible cases of failures. It is recommended to use a testing framework to run tests. Make your assertions in tests clear and descriptive.
Tests are important for your application just like the production code is.Testing is an integral part of the software development process that goes hand-in-hand with writing clean and high-quality code.
Although we can include a variety of things like DRY, SOLID, updates handling, documenting, and refactoring, these are a few basic tips to help you write clean code.
It is important to write clean code in your development journey. Writing clean code not only makes your work easier but saves a lot of frustration and confusion for other developers working on the codebase. Clean code lets you bring creativity and saves a lot of time which can be used for development rather than wasting it just to analyse the code. So, if you are a beginner in your coding journey or a professional developer, remember that clean code is not a luxury but a necessity for success in the ever-evolving landscape of software development.