How to write better code: 11 core points

Source: Internet
Author: User

As a qualified programmer, there are too many reasons to encourage you to write neat and readable code. The most important thing is that many people will read the code again and again in the future. When you look back at your code one day, you will understand how important it is to write elegant code. In addition, if someone else reads your code, do you want to know how crazy people will feel when they see the bad code. Therefore, spending more time writing elegant code may save you more time in the future.

The following are 11 basic rules on how to write better code:

  • 1. Keep the method brief

  • 2. Never use the same variable for different purposes

  • 3. Make the names of variables and methods as much as possible to describe the functions to be implemented.

  • 4. Define variables as close as possible to them

  • 5. Do not show confusing numbers

  • 6. Treat your language as if you were a friend.

  • 7. Do not go against the regular

  • 8. Be careful when optimizing code too early

  • 9. Rebuild the tested code frequently.

  • 10. do not indulge in excessive design skills.

  • 11. Learn new knowledge anytime, anywhere

Next we will introduce each point in detail.

1. Keep the method brief

Although many people follow this rule, it is still important. In general, it is best to write a method that can be fully displayed on the first screen. Imagine how distracting it is if you need to scroll the page to see the whole method. It is best to keep a method between 5-20 rows. Of course, you should also decide based on the actual situation, not generalize. For getter and setter methods, only one line of code is required, so they look more like accessors of class members.

2. Never use the same variable for different purposes

A variable can only be used for one purpose. We can help the compiler optimize code compilation by using constants (const identifiers in C ++ and final identifiers in Java, you can also identify "this variable cannot be changed" to the program, so that the code we write has better readability.

3. Make the names of variables and methods as much as possible to describe the functions to be implemented.

An easy-to-understand program code can be understood by anyone who has read the code. Therefore, we recommend that you use as few abbreviations as possible, unless it is recognized as a shorthand for the program, as shown below:

src - source pos - position prev - previous

If you think the descriptive shorthand method is of no value, you can compare N, NS, nsisd, numteammembers, seatcount, numseatsinstadium.

4. Define variables as close as possible to them

When you are building a house, you do not want to place a hammer in the courtyard of another person's house. On the contrary, you will keep the tools for building a house as close as possible, and define variables in the same way.

int foo = 3; int bar = 5; // bunch of code that uses "bar" // but doesn‘t care about "foo" // ... baz(foo);

We can refactor the code like this:

int bar = 5; // bunch of code that use "bar" // but doesn‘t care about "foo" // ... int foo = 3; baz(foo);

When you declare a variable too far (or even more than one screen) from where it is used, it will indeed bring you a lot of trouble. You will often scroll through the page to find this variable, making it difficult for you to maintain consistency between codes in your brain.

5. Do not show confusing numbers

When you compare constants, you must define them as the constant type. When debugging code between teams, the following code appears:

il < 4384

How nice is it to replace it with the following code:

inputLength < MAX_INPUT_LENGTH
6. Treat your language as if you were a friend.

Learning a new programming language is a very interesting thing, from which you can learn new things in a cool way. The other is to let a person who is very professional with a certain language learn another language. In many cases, it may make people feel overwhelmed. For example, if you want a Java guru to learn Ruby, he should solve the problem in Ruby instead of continuing to use Java's solution to the problem.

When you need to output "Hello World" five times in a loop, the Java code should be like this:

for (int i = 0; i < 5; i++) {     System.out.println("Hello world!"); }

But with Ruby, you may write:

for i in (0..5)   puts "Hello world!" end

These seem good, but the most perfect method is as follows:

5.times { puts "Hello world!" }
7. Do not go against the regular

Every programming language has its own constraint habits. In general, you may know a lot about Java programming habits. Let's take a look at some of these habits:

  • The method name starts with a lowercase letter followed by a word starting with an uppercase letter, such as verylongvariablename.

  • Class names are generally a combination of words starting with an upper-case letter.

  • Constants are all uppercase words separated by underscores (_), for example, my_constant.

  • The left braces should be the same line as if.

This rule can be broken only when it is forced. do not violate the agreed encoding conventions because you do not like this practice. If you are a member of the team and want to change some coding rules, you can also, but when you share your code with teammates who do not like you, the tough issue is coming.

8. Be careful when optimizing code too early

Early optimization is the root cause of all problems, at least on TV... Your primary task is to write code that is easy to understand without requiring you to write it quickly. It is too early to talk about optimization unless your program runs slowly. If you want to optimize your program, you must first find out the program problems, which is why we need the profilers tool.

Optimize the code without finding the source of the problem. The price you pay for doing so is to destroy the program structure and at least lose the readability of the program. If you find that the program runs slowly, do not blindly refactor the code. First, find the root cause of slow running.

Never be dumpfounded to solve a non-existent problem.

9. Rebuild the tested code frequently.

There is no perfect thing in the world. Although you think that your code has been well written, you may want to read it frequently for a while. Maybe you will yell at yourself: "How can it be so silly !"

There is a way to improve the quality of code, that is, code that passes tests is often reconstructed. Through testing, I mean that the program should work normally. You can ensure this through automated testing or manual testing.

First, you need to ensure that the program can run normally. For the first time, we don't need to write a perfect program. We can use it. Then we can refactor it slowly to make it perfect. This development method has the taste of TDD. The key is that you need to be familiar with every aspect of refactoring. If you are familiar with some advanced ides, such as intellij idea, Your refactoring work will be much simpler.

After reconstruction, you may encounter many such problems and even destroy normal programs. This is why we need to use automated testing. After reconstruction, you can run the unit test once to avoid these headaches.

10. do not indulge in excessive design skills.

When I first came into touch with the concept of design patterns, I felt that I had found the Holy Grail ". These exquisite design ideas can make your work more smooth, and make your design easy to understand, because you can simply say "I used the observer model ", the weekly chapter of different major fees is explained. However, the question is, because some problems seem too natural and too simple, you will apply those design patterns to any place. Why not design this class into Singleton )? Why not create some factory classes?

So you can use 80 lines of code to complete the script. As a result, you use 10 classes, 15 interfaces, and a bunch of generics and comments, the Code 97% does not actually do anything. Although the design pattern is very useful and can help you simplify the design, it does not mean that you can use them everywhere. You can use the design pattern, but you cannot abuse it.

11. Learn new knowledge anytime, anywhere

Programming is a job to learn new things at any time. When you learn new class libraries or programming languages, you can't wait to drop old code and rewrite them. However, there are many reasons why you shouldn't do this.

A similar problem occurs when a new class library or framework is applied to an existing project. For example, if you are writing JavaScript For a web project, but you have found jquery in the middle, you can't wait to apply jquery and drop the original JavaScript code, even if you have never used jquery to write any project.

The best way is to use jquery to learn some simple examples and learn the technologies used in your project. For example, do you want to use Ajax? Write some simple examples of Ajax outside the project. After you have mastered it, you can remove the old code from the project.

If you are keen on programming, I strongly recommend you read the code complete written by Steve McConnell, which will change your programming thinking forever.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.