Home > Article > Backend Development > Foreign media review: 11 tips for improving programs_PHP Tutorial
There are many reasons why we should write clear and readable programs. The most important point is that you only write the program once, but you will read it countless times in the future. When you come back to your code the next day, start reading it. When you show your code to someone else, he or she must read your code. So, spend a little more time when writing it and you'll save a lot of time when reading it.
Let’s look at some basic programming skills:
Keep the method as short as possible
Never, ever use the same variable for multiple purposes
Use self-describing variable and method names
Define variables as close to where they are used as possible
Reject mysterious numbers
Be kind to your language
Don’t go against the rules
Be wary of premature optimization
Actively refactor tested programs
Don’t be overly obsessed with techniques
Learn new knowledge through practice examples
Now, let us expand on each point and explain it in detail.
1. Keep the method as short as possible
Although many people follow this rule, it is still very important. The method you write should always fit on one screen. If you need to scroll, it distracts you and you don't see the entire context. The optimal length is 5-20 lines, depending on your situation. Of course, getters/setters are usually one-line methods, but they are more like accessors than real methods.
2. Never use the same variable for multiple different purposes
A variable should always serve only one purpose. By making the variable constant (const in C++, final in Java), the compiler can optimize the compilation, and make your code clearly express that this variable cannot be changed, and the readability of your program will become better. .
3. Use self-describing variable names and method names
Your code should be able to be easily understood by anyone looking at it. Try not to use abbreviations unless you have special habits, like the following:
src - source pos - position prev - previous
If you think descriptive names aren’t that valuable, compare n, ns, nsisd with numTeamMembers, seatCount, numSeatsInStadium.
4. Define variables as close to where they are used as possible
When building a house, you don’t want to put your hammer in someone else’s yard. You want to keep them as close to hand as possible. The same goes for defining variables.
int foo = 3;int bar = 5;// A large section of code that uses "bar", // but "foo" is not used // ...baz(foo);
This code can be simply restructured into
int bar = 5;// A large section of code using "bar", // but not "foo" // ...int foo = 3;baz(foo);
This does become a problem when you place the declaration of a variable too far (more than a screen away) from the first time it is used. Remembering the context becomes difficult and you need to scroll to find where the variable comes from.
5. Reject mysterious numbers
When you want to compare something with a constant value, remember to define the value as a constant. There’s nothing more frustrating than trying to guess what your colleagues wrote:
il < 4384
How does it feel to change the form?
inputLength < MAX_INPUT_LENGTH
6. Be friendly with your language
Learning a new language is fun and you can learn a new way to complete tasks. When a person who is already expert in one language learns another language, there is a big negative effect. Let's say you are a Java developer trying to learn Ruby. You should learn to solve problems in Ruby's way, rather than using Java's way of solving problems.
When you need to repeat "Hello world!" 5 times, in Java, you might do this:
for (int i = 0; i < 5; i++) { System.out.println("Hello world!");}
In Ruby, you might be tempted to write:
for i in (0..5) puts "Hello world!"end
This looks fine, but there is a better way:
5.times { puts "Hello world!" }
7. Don’t go against the grain
Each language has its own different conventions. Generally speaking, what people hear the most is Java's coding specifications. Let’s take a look at some of these customs:
Method names should start with a lowercase letter, followed by words in uppercase letters (veryLongVariableName)
Class names should be composed of words with the first letter capitalized
Constant names should be in all capital letters and connected with underscores (MY_CONSTANT)
The opening brace should be on the same line as the if statement
Only break these rules when you have a necessary reason. Don’t break them just because you are unhappy. If you just change some of these habits in the team, that's fine, but when you take your code out and share it with other programmers who are not prepared for these thoughts, problems will arise.
8. Be wary of premature optimization
Premature optimization is the root of all problems, at least that's what the TV says... The first thing you should care about is writing code that is easy to understand. The program I originally wrote was not required to be fast. Unless your program is very slow, it's too early to talk about optimization. If you want to optimize something, you first need to know what the problem is. This is why we need profilers.
If you try to optimize the program without knowing where the problem is, the result will inevitably be that the program will be broken, or at least your code will lose readability. If you think something is slow, don't blindly rewrite the code. You should first find evidence of the slowness.
Don’t foolishly solve problems that don’t exist.
9. Actively refactor tested programs
Nothing will be perfect. Even if you feel like you actually wrote a perfect piece of code, you may look back a few months later and wonder, "How could you be so stupid?"
A good way to improve a program is to refactor it, but only after the program has been tested. You first need to make sure that the program is good and runnable, and you can do this through automated testing or manual testing.
Initially, all you need is for the program to be available. Don't expect to write a perfect program the first time, you just need to make it work. Then refactor it to make it perfect. For those of you who know Test Driven Development (TDD), this will look familiar. The key here is that you have to get used to refactoring. If you are using a powerful integrated development tool like IntelliJ IDEA, the refactoring work will become much easier.
After refactoring, you may create some bugs, causing problems with certain functions. That's why it's important to write automated tests. Whenever you refactor, just run all the test cases and you'll know exactly what went wrong.
10. Don’t be overly obsessed with techniques
When I first read about design patterns, I thought I had found the Holy Grail. These carefully designed ideas have a significant effect in making your design easy to understand, because you can simply say "I am using the 'Observer Pattern'" without having to explain it from beginning to end. So, any questions? Everything looks so natural and simple that you start using design patterns everywhere. Why not make this class a singleton? Why not create some factory classes?
So for a script that can be written in 80 lines, you end up using 10 classes, 15 interfaces, plus a lot of paradigms and markers. 97% of code doesn't do anything. Design patterns are a very useful tool for simplifying your design, but that doesn't mean you should use them everywhere. You should use them, but not abuse them.
11. Learn new knowledge through practice examples
Programming is a process of learning new knowledge. When you learn a new library or language, you may be tempted to throw away the old code and rewrite it using your newfound knowledge. There are many reasons why you shouldn't do this.
This is also the case when adding new class libraries or frameworks to existing applications. Let's say you wrote a Javascript web application, and during the process, you discovered jQuery. Now you are suddenly eager to throw away your Javascript program and rewrite it in jQuery, even though you have never used it before.
The best way is to write some simple examples with jQuery first, and in this way learn all the knowledge you will use in the application. Need AJAX? Make some small examples outside of your project. When you understand it completely, throw away the examples and apply them to your product.
If you are very concerned about programming technology, I strongly recommend you to read the book "Code Encyclopedia" written by Steve McConnell. It will change your understanding of programming forever. :)