How to write clean code
How to write clean code
How to write clean code? Lessons learnt from “The Clean Code” — Robert C. Martin
There are two things- Programming and Good Programming. Programming is what we have all been doing. Now is the time to do good programming. We all know that even the bad code works. But it takes time and resources to make a program good. Moreover, other developers mock you when they are trying to find what all is happening in your code. But it’s never too late to care for your programs.
This book has given me a lot of knowledge on what are the best practises and how to actually write code. Now I feel ashamed of my coding skills. Though I always strive to better my code, this book has taught a lot more.
Now, you are reading this blog for two reasons. First, you are a programmer. Second, you want to be a better programmer. Good. We need better programmers.
Characteristics of a Clean code:
4. Runs all the tests
5. Contains no duplication
6. Minimize the number of entities such as classes, methods, functions, and the like.
How to write Clean code?
Meaningful Names
Use intention revealing names. Choosing good names takes time but saves more than it takes.The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.
Eg- int d; // elapsed time in days.
We should choose a name that specifies what is being measured and the unit of that measurement.
A better name would be:- int elapsedTime. (Even though the book says elapsedTimeInDays, I would still prefer the former one. Suppose the elapsed time is changed to milliseconds. Then we would have to change long to int and elapsedTimeInMillis instead of elapsedTimeInDays. And for how long we’ll keep changing both the data type and name.)
Class Names — Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class. A class name should not be a verb.
Method Names —Methods should have verb or verb phrase names like postPayment, deletePage, or save. Accessors, mutators, and predicates should be named for their value and prefixed with get, set.
When constructors are overloaded, use static factory methods with names that describe the arguments. For example,
Complex fulcrumPoint = Complex.FromRealNumber(23.0); is generally better than Complex fulcrumPoint = new Complex(23.0);
Pick One Word per Concept —Pick one word for one abstract concept and stick with it. For instance, it’s confusing to have fetch, retrieve, and get as equivalent methods of different classes. How do you remember which method name goes with which class? Likewise, it’s confusing to have a controller and a manager and a driver in the same code base. What is the essential difference between a DeviceManager and a Protocol- Controller?
Functions
The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. This implies that the blocks within if statements, else statements, while statements, and so on should be one line long. Probably that line should be a function call. Not only does this keep the enclosing function small, but it also adds documentary value because the function called within the block can have a nicely descriptive name.
Function arguments
A function shouldn’t have more than 3 arguments. Keep it as low as possible. When a function seems to need more than two or three arguments, it is likely that some of those arguments ought to be wrapped into a class of their own. Reducing the number of arguments by creating objects out of them may seem like cheating, but it’s not.
Now when I say to reduce a function size, you would definitely think how to reduce try-catch as it already makes your code so much bigger. My answer is make a function containing just the try-catch-finally statements. And separate the bodies of try/catch/finally block in a separate functions. Eg-
This makes the logic crystal clear. Function names easily describe what we are trying to achieve. Error handling can be ignored. This provides a nice separation that makes the code easier to understand and modify.
Error Handling is one thing — Function should do one thing. Error handling is one another thing. If a function has try keyword then it should be the very first keyword and there should be nothing after the catch/finally blocks.
Comments
If you are writing comments to prove your point, you are doing a blunder. Ideally, comments are not required at all. If your code needs commenting, you are doing something wrong. Our code should explain everything. Modern programming languages are english like through which we can easily explain our point. Correct naming can prevent comments.
Legal comments are not considered here. They are necessary to write. Legal comments means copyright and licenses statements.
Objects and Data Structures
This is a complex topic so pay good attention to it. First we need to clarify the difference between object and Data Structures.
Objects hide their data behind abstractions and expose functions that operate on that data. Data structure expose their data and have no meaningful functions.
These 2 things are completely different. One is just about storing data and other is how to manipulate that data. Consider, for example, the procedural shape example below. The Geometry class operates on the three shape classes. The shape classes are simple data structures without any behavior. All the behavior is in the Geometry class.
Consider what would happen if a perimeter() function were added to Geometry. The shape classes would be unaffected! Any other classes that depended upon the shapes would also be unaffected! On the other hand, if I add a new shape, I must change all the functions in Geometry to deal with it. Again, read that over. Notice that the two conditions are diametrically opposed.
Now consider another approach for the above scenario.
Now we can easily add new Shapes i.e. data structures as compared to previous case. And if we have to add perimeter() function in only one Shape, we are forced to implement that function in all the Shapes as Shape class is an interface containing area() and perimeter() function. This means:
D ata structures makes it easy to add new functions without changing the existing data structures. OO code(using objects), makes it easy to add new classes without changing existing functions.
The complimentary is also true:
Procedural code(using data structures) makes it hard to add new data structures because all the functions must change. OO code makes it hard to add new functions because all the classes must change.
So, the things that are hard for OO are easy for procedures, and the things that are hard for procedures are easy for OO!
In any complex system there are going to be times when we want to add new data types rather than new functions. For these cases objects and OO are most appropriate. On the other hand, there will also be times when we’ll want to add new functions as opposed to data types. In that case procedural code and data structures will be more appropriate.
Mature programmers know that the idea that everything is an object is a myth. Sometimes you really do want simple data structures with procedures operating on them. So you have to carefully think what to implement also thinking about the future perspective that what will be easy to update. As for in this example, as any new shape can be added in the future, I will pick OO approach for it.
I understand it’s hard to write good programs given the timeline in which you have to do your tasks. But till how long you’ll delay? Start slow and be consistent. Your code can do wonders for yourself and mostly for others. I’ve started and found so many mistakes I’ve been doing all the time. Though it has taken some extra hours of my daily time limit, it will pay me in the future.
This is not an end to this blog. I will continue to write about new ways to clean your code. Moreover, I will also write about some basic design patterns which are must know for every developer in any technology.
In the mean time, if you like my blog and learnt from it, please applause. It gives me motivation to create a new blog faster 🙂 Comments/Suggestions are welcomed as always. Keep learning and keep sharing.
7 Tips To Write Clean And Better Code in 2020
Software engineering is not just all about learning a language and building some software. As a software engineer or software developer, you are expected to write good software. So the question is what makes good software?. Good software can be judged by reading some piece of code written in the project. If the code is easy to understand and easy to change then definitely it’s a good software and developers love to work on that.
It’s a common thing in development that nobody wants to continue a project with horrible or messy code (It becomes a nightmare for sometimes…). Sometimes developers avoid writing clean code due to deadline pressure. They rush to go faster but what happens actually is they end up with going slower. It creates more bugs which they need to fix later going back on the same piece of code. This process takes much more time than the amount of time spent on writing the code. A study has revealed that the ratio of time spent reading code versus writing is well over 10 to 1.
It doesn’t matter if you are a beginner or an experienced programmer, you should always try to become a good programmer (not just a programmer…). Remember that you are responsible for the quality of your code so make your program good enough so that other developers can understand and they don’t mock you every time to understand the messy code you wrote in your project.
What Makes a Clean Code: Before we discuss the art of writing clean and better code let’s see some characteristics of it…
“Clean code is simple and direct. Clean code reads like a well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”
-Grady Booch (Author of Object-Oriented Analysis and Design with Applications)
How to Write Clean and Better Code?
1. Use Meaningful Names
You will be writing a lot of names for variables, functions, classes, arguments, modules, packages, directories and things like that. Make a habit to use meaningful names in your code. Whatever names you mention in your code it should fulfill three purposes…what it does, why it exists and how it is used. For Example:
In the above example, you need to mention a comment along with the name declaration of a variable which is not a characteristic of a good code. The name that you specify in your code should reveal it’s intent. It should specify the purpose of a variable, function or methods. So for the above example, a better variable name would be:- int number_of_users. It may take some time to choose meaningful names but it makes your code much cleaner and easy to read for other developers as well as for yourself. Also, try to limit the names to three or four words.
2. Single Responsibility Principle (SRP)
Classes, Functions or methods are a good way to organize the code in any programming language so when you are writing the code you really need to take care that how to write a function that communicates it’s intent. Most of the beginners do this mistake that they write a function that can handle and do almost everything (perform multiple tasks). It makes your code more confusing for developers and creates problems when they need to fix some bugs or find some piece of code. So when you are writing a function you should remember two things to make your function clean and easy to understand…
The above two points clearly mention that your function should follow single responsibility principle. Which means it shouldn’t have nested structure or it should not have more than two indent level. Following this technique make your code much more readable and other developers can easily understand or implement another feature if your function fulfills a specific task.
Also, make sure that your function should not have more than three arguments. More arguments perform more tasks so try to keep the arguments as less as possible. Passing more than three arguments makes your code confusing, quite large and hard to debug if any problem would be there. If your function has try/catch/finally statement then make a separate function containing just the try-catch-finally statements.
Take care of your function name as well. Use a descriptive name for your function which should clearly specify that what it does.
In the above example the function name clearly shows that it’s purpose is to perform subtraction for two numbers, also it has only two arguments. Read more about writing a good function from the link 7 Common Programming Principles That Every Developer Must Follow and SOLID Principle.
3. Avoid Writing Unnecessary Comments
It’s a common thing that developers use comments to specify the purpose of a line in their code. It’s true that comments are really helpful in explaining the code what it does but it also requires more maintenance of your code. In development code move here and there but if the comment remains at the same place then it can create a big problem. It can create confusion among developers and they get distracted as well due to useless comments. It’s not like that you shouldn’t use comments at all, sometimes it is important, for example…if you are dealing with third party API where you need to explain some behavior there you can use comments to explain your code but don’t write comments where it’s not necessary.
Today modern programming languages syntax are English like through and that’s good enough to explain the purpose of a line in your code. To avoid comments in your code use meaningful names for variables, functions or files.
Good code is its own best documentation. As you’re about to add a comment, ask yourself, “How can I improve the code so that this comment isn’t needed?” Improve the code and then document it to make it even clearer.
-Steve McConnell
4. Write Readable Code For People
A lot of people especially beginners make mistake while writing a code that they write everything in a single line and don’t give proper whitespace, indentation or line breaks in their code. It makes their code messy and difficult to maintain. There’s always a chance that another human will get to your code and they will have to work with it. It wastes other developers’ time when they try to read and understand the messy code. So always pay attention to the formatting of your code. You will also save your time and energy when you will get back to your own code after a couple of days to make some changes. So make sure that your code should have a proper indentation, space and line breaks to make it readable for other people. The coding style and formatting affect the maintainability of your code. A software developer is always remembered for the coding style he/she follow in his/her code.
How to write clean code
Writing clean code is like writing poetry. Poetry that is easily understood, has transformational power, and is written in a concise manner.
Clean code means a scalable organization. It’s the difference between a junior dev and a senior engineer. It means being able to pivot plans without much chaos.
1. Your code being readable is as important as it being executable
The majority of the cost of a software project is in long-term maintenance. Therefore, the code you write should clearly express your intent so that new developers can easily hop in and understand what is going on and why. The clearer the author can make the code, the less time others will have to spend understanding it. This reduces defects and shrink the cost of maintenance.
2. Later equals never
Let’s be honest. We’ve all said we’d go back and clean it up later and then forgot about it. Don’t leave scraps of useless code that no longer serve a purpose. They confuse other devs and provide no value. When changing a feature, always make sure to delete the old code. Tests should notify you if you’re breaking stuff elsewhere anyways.
3. Functions should be small
When it comes to a function’s arguments: the ideal number is 0. Then goes 1, then 2, but more than 3 should be avoided where possible.
4. Duplication is the evil of all code
Duplication is the enemy of a well-designed system. It represents additional work, additional risk, and additional unnecessary complexity.
5. The only good comment is the one you found a way not to write
«Nothing can be quite so helpful as a well-placed comment. But comments are, at best, a necessary evil.»
The proper use of comments is to compensate for our failure to express our self in code. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not cause for celebration.
Thing is, comments often lie. Not always, and not intentionally, but too often. The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong.
The reason is simple: programmers can’t realistically maintain all of them so all too often they become separated from the code they describe and become orphaned blurbs of ever decreasing accuracy. Usually comments are crutches or excuses for poor code or justifications for insufficient decisions, amounting to little more than the programmer talking to him/herself.
6. An object exposes behavior but not data
A module should not know about the innards of the objects it manipulates. Objects hide their data and expose operations. This means that an object should not expose its internal structure through accessors because to do so is to expose, rather than to hide, its internal structure. There’s no need for everyone to see you naked.
7. On testing
Test code is just as important as production code and as such, it must change and grow as the production code evolves. Keeping tests clean is so important because without them, you lose the very thing that keeps your production code flexible, maintainable, and reusable. If you have tests you do not fear making changes to the code and without tests, every change is a possible bug. Tests eliminates the fear that cleaning code will break it.
Readability keeps tests clean because they are an opportunity to explain to other devs the intent of the original author in plain English. This is why we want to test only a single concept in each test function so that the test is descriptive, reads easier, and is easier to track when it fails. Clear separation and good test writing help define expectations and keeps the scopes clear.
How to do this: Follow the FIRST Principles:
8. On error handling and exceptions
Each exception that you throw should provide enough context to determine the source and location of the error. Although you usually get a stack trace from any exception, a stack trace can’t tell you the intent of the operation that failed.
You should avoid passing null in the code whenever possible. And if you are tempted to return null from a method, consider throwing an exception. Set error handling as a separate concern, something that is viewable independently of our main logic.
9. On classes
Classes should be small, but rather than counting lines, we should count responsibilities. The names of classes are key to describe which responsibilities it fulfills. Our systems should be composed of many small classes, instead of a few large ones, where each small class encapsulates a single responsibility. Each class has a single reason to exist and collaborates with a few others to achieve the desired system behaviors.
There is seldom a good reason to have a public variable. Loosening encapsulation is always a last resort and there should be a small number of instance variables at all. Good software designs accommodate change without huge investments and rework. Narrowing the scopes of variables allows us to do this more easily.
10. On format
Each blank line is a visual cue that identifies a new and separate concept.
Local variables should appear at the top of the function.
Instance variables should be declared at the top of the class.
Principles of software development
In summary, follow these practices and your code will be clean:
«You should name a variable using the same care with which you name a first-born child.»
The hardest thing about choosing good names is that it requires good descriptive skills and a shared cultural background. Clean code is read and enhanced by any developer.
The name of a variable, function, or class, should answer all the big questions: why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent as it should. Programmers must avoid leaving false clues that obscure the true meaning of the code.
Longer names trumps shorter names, and any searchable name is better than a constant in the code base. Single-letter names can only be used as local variables inside short methods: the length of a name should correspond to the size of its scope. Methods should be verbs or verb phrases; a class name should not be a verb.
b) Minimal dependencies: We should avoid letting too much of our code know about the third-party particulars. It’s better to depend on something you control than on something you can’t control. If you do, it ends up controlling you.
c) Tidiness: A piece of code should be where you expect to find it. Code bases should be intuitive to navigate through; developer’s intentions feel clear.
d) Cleaning: Don’t litter your code with useless code scraps or lines of code that capture history or wishes of the future. Reduced duplication, high expressiveness and early building of simple abstractions.
e) Standardization: Your code should keep a consistent coding style and set of practices across repositories.
f) Self-discipline: you frequently reflect on one’s work and are willing to change and improve. However, you don’t fall into the hype too fast. Study new stacks with depth and purpose.
Truth is, keeping your code clean is key to maintaining innovation and organizations alive. As systems scale and grow, it is inevitable that old technology practices and hacks get left behind in the code. Keeping your code base clean is more than a nice gesture for other devs. It’s a necessity for long-term survival. The cleaner your code, the happier the devs, the better the product, the longer it lasts.
How to write clean code that increases work productivity
Vishal Sahu
November 15, 2019 | 1325 Views
A good program is only as good as the readability of its code. As Robert C. Martin rightly says in his book, Clean Code.
The most common reason for not writing clean code is the lack of time. As a developer, you will spend much more time reading code than writing it. Well-written code saves a lot of time while performing code reviews or refactoring code.
Here are a few coding standards and guidelines that are considered as industry best practices for writing clean code:
1) Limited use of global variables in your code
Global variables have their pros and cons and their use largely depends on the complexity and size of your application. If you have a large application then using an un-scoped global variable causes multiple side effects since there’s no way to tell who modified it and when its value changes. This poses a huge problem for apps while unit testing, alpha, and beta testing, debugging or while refactoring code.
2) Standardization of headers for different modules
Writing code that has good maintainability and readability follows a standard format for writing headers with necessary bits of information such as:
module creation date
audit trail capturing modification history with author-name
different functions that are part of the module along with their input and output params
any global variables that are used in the module
3) Writing meaningful variable and function names
Writing meaningful names for variables, constants and functions makes the code self-documenting. It’s best to use a standard naming convention across the entire application/organization. Few best practices for naming conventions for better code readability are:
The names should be simple and read like English. Avoid unnecessary abbreviations that complicate code
Use precise and meaningful names that explain the purpose (what it does) and the intent of a variable or function.
Example: deleteAddress, deleteSupplier, createPotentialSupplier
Keep code names consistent basis the action performed by the function. For example, all functions performing a delete action should start with deleteSomething. This cannot be a mix of removeSomething and deleteSomething across the codebase.
Use camelCase for variable and function names.
Avoid using digits for variable or function names
Maintain a distinct identifier between local and global variables
4) Indentation
Imagine you walk into a hypermarket and everything is in a disarray and it’s very difficult to find what you’re looking for. Well-organized code is very much similar to a well-arranged hypermarket and this can be achieved with indentation. Indentation makes code readable. Indentation is achieved by correctly using white spaces in certain scenarios such as:
A space after each comma between parameters, arguments and function names
Well-spaced nested and conditional statements
Each brace starting on a new line with an exact indentation between the corresponding opening and closing braces.
5) Error Handling and Reporting
Try-catch(ing) everything! There’s a huge amount of time savings that can happen with robust error handling methods that report failures in a format that makes it easy to debug. You should return exceptions rather than error codes with each exception having sufficient context to detect the root cause of the error and the location within the codebase. You should maintain informative logs that capture the date and time of events while your app is in production. These logs will act as your go-to sheet for tracking and debugging. Also, you can prioritize errors and raise flags basis the criticality and impact of the error.
6) Single Responsibility Principle (SRP)
SRP states that focus on doing one thing. For programming, this translates that each function should be limited to performing a single task with no more than 4 lines. Each class, on the other hand, should not be more than 100 lines. A limitation like this forces you to think and write powerful code which will do more compared to elongated nested IF statements.
7) Unit Testing with all you got
A lot of initial bugs can be identified with the unit and integration testing done via automation. A huge repository of automated test cases can test for core business functionality, logic and structure of the code. This will result in a much more stable code that is submitted for review. Each aspect of your code that contains logic needs to be unit tested. If this isn’t the case, it’s likely to fail in the future until your customers report it as a bug.
8) Separation of Concerns (SoC)
SoC is in line with the Single Responsibility Principle. The goal here is to ensure that you do not write giant functions that look after multiple “concerns”. SoC is a design principle that states the need for logically breaking a computer program into distinct sections, wherein each section addresses a separate concern. A concern is a bundle of instructions and information that can impact the code in a program. For example, think of a single function that validates n arguments, calculates their results and then prints the results. In this scenario, as per SoC, you can break this function into a primary function that validates the arguments and various helper functions that perform the task of calculating and printing the results. Each programming language provides in-built mechanisms to achieve SoC, as OOP languages can implement SoC by using objects.
9) Test-driven development (TDD)
Test-driven development is a practice that instructs developers to write code from scratch only if an existing automation test has failed. With a TDD approach, you tend to avoid duplication of code and the final codebase is clean, simple and bug-free. The TDD process is a cyclic approach as follows:
Execute the test
If the test fails, write a new code. If not, no need for a new code.
Execute the test again
10) Discourage using the GOTO statement
Using the GOTO statement is highly discouraged as it breaks the logical flow of the program and makes it unstructured and difficult to trace while debugging.
11) Target minimum length for your functions
The length of your functions should be as small as possible. Aim to write optimized code where one function performs only one task. This approach makes the code more readable and understandable.
12) Document your code
This should ideally take care of itself if you follow the previous 9 points. However, you still need to add appropriate comments which make the code more understandable. Well commented code also serves a dual purpose of making the code base searchable while code review, code refactoring or debugging.
How to review clean code that increases productivity
It’s important to perform code reviews as it improves the overall code quality and makes it more stable. However, a code review needs to be a well-defined activity that is part of a planned process rather than two programmers casually reviewing and debugging code. There are a few programming best practices for code review.
1) A well-defined code review process
2) Set of rules governing the code review process
3) Ask the right questions
Code review must be done with well-defined goals and clear expectations. You should know what you’re looking for and the parameters you’ll be reviewing such as:
4) Test first, Review later
You need to test your code before you submit it for review. This will help save time while reviewing as many errors might get resolved after initial testing and a more stable codebase is committed to the dev environment.
5) Certain Don’ts you need to be wary of while performing Code Review
Don’t exhaust yourself in code reviews – At a given point of time, you should spend a maximum of 60 minutes or a maximum of 400-500 lines of code per review. Don’t overengineer code reviews – Use the 80/20 rule (Pareto principle) logic while reviewing code, wherein you focus on getting 80% of the results from 20% of your effort.
6) Static code analysis
A lot of tasks performed while manually reviewing code can be automated using third-party static code analyzers. Static code analysis is the process of identifying errors by running it against standard coding rules in your source code. This is an automated code review process. Static code analysis helps in three ways:
Code Refactoring – Best Practices
Code refactoring is the process of redesigning or restructuring the existing codebase without changing its external intended output. Code refactoring takes place in a controlled manner with small transformations (refactoring) made to a series of elements in the codebase whose cumulative effect is significant. By making small increments you ensure that the system does not break post refactoring and unit tests are conducted after each refactoring.
Few programming best practices and techniques for code refactoring are:
1) Make the code more readable and understandable
2) Implement DRY (Don’t Repeat Yourself)
3) Remove redundancies in the form of unused core or unwanted comments. This should be deleted.
4) Optimize your code for performance.
5) Code refactoring should allow for:
Take a deeper look at your GOTO statements, nested IFs, and your choice of queries to request data from the database. Refactoring these will significantly improve performance.
Benefits of Code Refactoring:
While our codebase is forever upgrading, we can all strive to write cleaner code by authoring the cleanest version possible in the first go itself. Let’s strive to code better!
TechAhead, a leading mobile app development company is known to deliver high quality mobile apps for all platforms and frameworks. Contact our experts now to take your business to the next level.
Written by
Vishal Sahu
Vishal is an experienced, hands-on software architect involved in the architecture, design, and implementation of service-oriented architectures, mobile apps, and web-based systems. He has significant experience and expertise in application, integration, and architecture.
How to write Clean Code?
Lessons Learned from Robert C. Martin
Table of Contents:
Overview
“Master programmers think of systems as stories to be told rather than programs to be written” — Uncle Bob.
Clean Code — A Handbook of Agile Software Craftsmanship is a must-read book for developers, especially when you want to be a better software developer. This book explains what is the clean code and best practices to help you write clean code.
Clean Code: A Handbook of Agile Software Craftsmanship
Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Every year…
It helps me enhance coding skills and make remarkable in my career path. And through this article, I want to share my lessons learned and summarize the key points of the book, I think it very useful to you.
About the Author
What is Clean Code?
Have many definitions about Clean Code by well-known and deeply experienced programmers asked by authors, they thought what?
Bjarne Stroustrup, inventor of C++ and author of The C++ Programming Language:
I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.
Grady Booch, author of Object Oriented Analysis and Design with Applications:
“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”
“Big” Dave Thomas, founder of OTI, godfather of the Eclipse strategy:
Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal depen- dencies, which are explicitly defined, and pro- vides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.
Based on the above definitions and my coding experience, main Characteristics of Clean Code includes:
In the next section, I’ll share about how to write Clean Code.
Meaningful Names
Everything in an application has a name, from variables, functions, arguments, classes, modules, to packages, source file, directories.
Naming things is the most common problem of every developer. As Phil Karlton said that:
“There are only two hard things in Computer Science: cache invalidation and naming things” — Phil Karlton
Names are the powerful way you communicate your code’s intent to developers who read your code, including yourself. Choosing good names takes time but make your code better and cleaner. It makes your code easy to read by other developers, as well as yourself in the future.
And in this book, Uncle Bob share some simple rules to create good names:
Should:
Use intention-revealing Names
That means choosing names that reveal intent, the name should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent. It makes your code easier to understand and change later.
Use Pronounceable Names
Humans are good at words and words are, by definition, pronounceable.
If you can’t pronounce it, you can’t discuss it without sounding like an idiot. This matters because programming is a social activity.
Class Names
Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class.
A class name should not be a verb.
Method Names
Pick One Word per Concept
Using the same word per concept will help developers more easy to understand the code.
Should NOT:
Encodings
Encoded names are seldom pronounceable and are easy to mistype.
Mental Mapping
Readers shouldn’t have to mentally translate your names into other names they already know. This problem generally arises from a choice to use neither problem domain terms nor solution domain terms.
One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.
Avoid using the same word for two purposes. Using the same term for two different ideas is essentially a pun.
Functions
How do you make a function communicate its intent? There are some best practices help you write good functions easy to read and change.
Small
The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that.
Do One Thing
Functions should do one thing. They should do it well. They should do it only.
Function Arguments
Functions should have Don’t Repeat Yourself (DRY)
Duplication is a problem in software. Many principles and best practices have been created to reduce duplication code.
Use a Descriptive Names
Same with rule meaningful names which explained in the above section.
“Master programmers think of systems as stories to be told rather than programs to be written” — Uncle Bob.
If you apply well these above rules, your functions are readable, easy to understand, nicely organized and to tell the story of the system.
Comments
“Don’t comment bad code — rewrite it.”
— Brian W. Kernighan and P. J. Plaugher
Comments do not make up for bad code.
Unit Tests
Test code is just as important as production code.
The Test Driven Development (TDD): is a software development process that relies on the repetition of a very short development cycle: requirements are turned into very specific test cases, then the software is improved to pass the new tests, only.
Uncle Bob describes TDD with 3 laws:
Tests are very important to an application as the production code is, because it makes your code is clean, flexible and maintainable. If you have tests, you do not fear change to the code and reduces bugs.
Unit tests help me get more deep sleep!
Conclusion
In this article, I shared with you about useful lessons learned about Clean Code from Robert C. Martin(Uncle Bob). It’s very essential for every developer who wants to be remarkable in the career path.