As a qualified programmer, there are many reasons to write clean and readable code. Most importantly, you write code that many people will read again and again. When you look back at your code one day, you’ll see how important it is to write elegant code. Also, if someone reads your code, do you want to know how they feel when they see bad code? Therefore, spending a little more time writing elegant code may save you more time in the future.
So here are 11 basic rules for writing better code:
Keep it short and to the point
2. Never, ever use the same variable for different purposes
3. Make the names of variables and methods as descriptive as possible
4. Define variables as close to them as possible
5. Avoid confusing numbers
6. Treat the language you’re good at like a friend
7. Don’t go against the grain
8. Be careful of optimizing code too early
9. Refactor tested code often
10. Don’t indulge in excessive design techniques
11. Learn something new anytime, anywhere
Let’s expand on each point in detail.
Keep it short and to the point
Although many people follow this rule, it is still important. In general, it is best to write methods that are fully visible on the first screen. Imagine how distracting it would be if you had to scroll through the page to see the entire method. A method is best kept between 5 and 20 lines, but it depends on the situation, not the whole thing. Getter and setter methods typically require only one line of code, so they look more like accessors for class members.
2. Never, ever use the same variable for different purposes
A variable should only be used for one purpose. We can use constants (const in C++, final in Java) to help the compiler optimize code compilation. We can also use “this variable cannot be changed” to indicate to the program, so that we can write more readable code.
3. Make the names of variables and methods as descriptive as possible
A piece of easy to understand program code, should be anyone who looks at the code, can understand what the program is used for. So I recommend using abbreviations as little as possible, unless it’s an accepted shorthand practice, like the following:
src-source
pos-position
prev-previous
If you find descriptive abbreviations worthless, compare n, NS, NSISD with numTeamMembers, seatCount, numSeatsInStadium
Define variables as close to them as possible
When you’re building a house, you don’t want to put a hammer in someone’s yard. Instead, you want to put your building tools as close as possible. Same goes for defining variables.
intfoo=3; intbar=5; //bunchofcodethatusesbar//butdoesn’tcareaboutfoo//… baz(foo);
We can refactor the code like this:
intbar=5; //bunchofcodethatusebar//butdoesn’tcareaboutfoo//… intfoo=3; baz(foo);
You can get into a lot of trouble when you put a variable declaration too far away from where it’s used (even more than one screen). You’ll often scroll through the page looking for this variable, making it hard to keep the code coherent in your head.
5. Avoid confusing numbers
Any time you want to compare constants, define them as constant. One of the biggest headaches when debugging code between teams is the following code:
il4384
It would be nice to replace it with the following:
inputLengthMAX_INPUT_LENGTH
6. Treat your new language like a friend
Learning a new programming language is fun, and you’ll learn new and cool ways to solve problems. If you ask someone who is good at one language to learn another language, it will often be overwhelming. For example, if a Java developer is trying to learn Ruby, you should learn to solve problems the Ruby way, not the Java way of solving problems.
When you need to loop “Hello World” five times, your Java code should look like this:
for(inti=0; i5; i++){
System.out.println(Helloworld!) ; }
But in Ruby, you might write:
foriin(0.. 5)
putsHelloworld! end
This all looks good, but the perfect way to do it might look like this:
5.times{putsHelloworld! }
Don’t go against the grain
Each programming language has its own constraints. In general, you may be familiar with Java programming habits, but let’s take a look at some of them:
1. Method names start with a lowercase letter followed by words that start with a uppercase letter, such as veryLongVariableName.
2. The class name is usually a combination of words starting with a capital letter.
3. Constants are named as uppercase words separated by underscores, such as MY_CONSTANT
4. The opening curly brace should be on the same line as if
Break this rule only when you have to, and never break established coding conventions just because you don’t like it. If you’re part of a team and want to change some of the coding rules, that’s fine, but when you share your code with someone who doesn’t have the same habit as you, it can get tricky.
8. Be careful of optimizing code too early
Premature optimization is the root of all problems, at least according to the TV… Your first priority is to write code that is easy to understand, not quick to write. Unless your program is slow, it’s too early to talk about optimization. If you want to optimize your application, you have to figure out what’s wrong with your application. That’s why we need profilers.
The price you pay for optimizing code without finding the source of the problem is that you break the structure of your program, or at least the readability of your program. If you find that your application is running slowly, don’t blindly refactor the code. Find the root cause of the slowness first.
Don’t be a fool to solve problems that don’t exist.
Refactor tested code often
Nothing in this world is perfect. Even if you think your code is perfect, go back to it once in a while, and you might think to yourself, “How stupid!”
One way to improve code quality is to frequently refactor code that passes tests. By passed testing, I mean that the program works, and you can make sure of that either through automated testing or manual testing.
The first thing you want to do is make sure the program works, so we don’t have to write a perfect program the first time, just work, and then we can refactor it and make it perfect. This approach is very TDD, but the key is that you need to be familiar with every aspect of refactoring. If you are skilled with some advanced IDE, such as IntelliJ IDEA, your refactoring will be much easier.
After refactoring, you may run into a lot of problems and even break the normal program, which is why we use automated testing. When you’re done refactoring, running through the unit tests can avoid these headaches.
10. Don’t indulge in excessive design techniques
When I first encountered the concept of design patterns, I felt I had found the Holy Grail. These subtle design ideas will make your work easier and your design easier to understand because you can simply say “I used the observer model” instead of having to explain it. The problem arises, however, because some problems seem so natural and simple that you can apply those design pattern ideas everywhere. Why not make this class a singleton? Why not create some factory classes?
You end up with 10 classes, 15 interfaces, and a bunch of generics and comments, 97% of which doesn’t actually do anything. Design patterns are useful and can help you simplify your design, but that doesn’t mean you can use them everywhere. You can use design patterns, but don’t abuse them.
11. Learn new things by example
Programming is all about learning new things. When you learn a new library or programming language, you can’t wait to throw away old code and rewrite it. But there are plenty of reasons why you shouldn’t.
Similar problems arise when a new class library or framework is applied to an existing project. For example, if you’re writing Javascript for a Web project and you find jQuery in the middle of it, you can’t wait to put jQuery into it and throw away your Javascript code, even if you haven’t written any projects with jQuery.
The best way to do this is to learn to write simple examples using jQuery and learn all the techniques you will use in your project. Let’s say you want to use AJAX? Write some simple Examples of AJAX outside of the project, and once you’ve mastered it, you can remove the old code from the project.