Home Backend Development PHP Tutorial Foreign media review: 11 tips for improving programs_PHP Tutorial

Foreign media review: 11 tips for improving programs_PHP Tutorial

Jul 13, 2016 pm 05:42 PM
Why readability media us Skill have clear of program illustrate

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. :)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486022.htmlTechArticleThere 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 the next day...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

Can JS run without H5? Can JS run without H5? Apr 06, 2025 am 09:06 AM

Is JavaScript available to run without HTML5? The JavaScript engine itself can run independently. Running JavaScript in a browser environment depends on HTML5 because it provides the standardized environment required to load and execute code. The APIs and features provided by HTML5 are crucial to modern JavaScript frameworks and libraries. Without HTML5 environments, many JavaScript features are difficult to implement or cannot be implemented.

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

Why can custom style sheets take effect on local web pages in Safari but not on Baidu pages? Why can custom style sheets take effect on local web pages in Safari but not on Baidu pages? Apr 05, 2025 pm 05:15 PM

Discussion on using custom stylesheets in Safari Today we will discuss a custom stylesheet application problem for Safari browser. Front-end novice...

What are the advantages of H5 page production What are the advantages of H5 page production Apr 05, 2025 pm 11:48 PM

The advantages of H5 page production include: lightweight experience, fast loading speed, and improving user retention. Cross-platform compatibility, no need to adapt to different platforms, improving development efficiency. Flexibility and dynamic updates, no audit required, making it easier to modify and update content. Cost-effective, lower development costs than native apps.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

Why does a specific div element in the Edge browser not display? How to solve this problem? Why does a specific div element in the Edge browser not display? How to solve this problem? Apr 05, 2025 pm 08:21 PM

How to solve the display problem caused by user agent style sheets? When using the Edge browser, a div element in the project cannot be displayed. After checking, I posted...

Why does my A-tagged image automatically download when it links to the same-origin image? Why does my A-tagged image automatically download when it links to the same-origin image? Apr 05, 2025 pm 03:39 PM

Regarding the problem of automatically downloading images when tag links with same origin, many developers will encounter the image after clicking when using tag links with same origin...

See all articles