Programming rules-4 Method Design Rules

Source: Internet
Author: User
Tags comparison table repetition

Abstract: Method Design Principles class design principles programming specifications Design Rules programming guidance see: overview
Name
4. Method

From the early process-oriented programming to the current object-oriented programming, it is always a method. process-oriented programming is called a function. In fact, object-oriented static methods are basically equivalent to functions; that is to say, regardless of the programming language, the method is the core of the software. The progress of object-oriented is to encapsulate methods (behaviors) and attributes so that behavior and attributes are organized in the form of classes, it can better express the application field. In fact, software systems are the abstract expression of the application field. Your expression is closer to the objective field, and your expressiveness will become stronger, the simpler the expression, the easier it is to understand.

Methods are expressions of behavior details. methods are organically organized to work together to form a software system. Although we place great emphasis on data structures and class architectures, they are indeed crucial in the system, but these constitute only the skeleton and trunk of the system, and the method is the soul of the system. The way is that the system has vitality and life. Since the method is so important, what principles should we follow when designing the method?

A good name from 4.1

We have already described the importance of a name. The name of a method must be able to properly describe what it is doing. Later we will introduce that the method must have a single function, this method also makes it easy to get a concise and loud name. When you cannot find a concise and good name, you can start a simple and well-known long name, this is much better than a confusing short name. When a more appropriate name is available, it is worthwhile to reconstruct it in time, the pursuit of a good name can help you improve your design. It is usually difficult for you to name your method properly, which often indicates that the responsibility of the method is unclear and requires splitting and re-designing.

4.2 do one thing and do one thing well.

This is very important. A method must be focused.Only do one thing and do one thing wellOnly one thing is to emphasize that the method should not do things unrelated to its responsibilities (do not do things for others, the software system does not need Lei Feng) and do one thing well, A strong method is required to take full and complete measures to handle this issue (do not push your own tasks to others, and the software system does not like to push them ), for example, check the validity of input data, handle various errors and exceptions, and check the validity of processed data.

4.3 The logic in the method body is at the same abstract level

This is a very important concept and method design guiding principle. We hope that we will understand its meaning and follow it. Most of us violate this principle in designing and writing methods, as a result, the methods are disordered and the layers are unclear, which is neither conducive to reading nor maintenance. In order to let everyone understand the meaning of this principle, the following is an example:

Taking the customer's background processing program for receiving cash from the bank as an example, this example is a highly simplified program, and the actual process is much more detailed than this. First, a withdrawal algorithm against this rule is provided. This method tries to include all the withdrawal business processing logic in a process (some programmers even think that writing code like this can be done in one go, it is a very good programming habit. Therefore, we must pay special attention to it. We must be aware that it is very bad and we must resolutely discard it ), we will find that the details of the withdrawal business logic are mixed with the business steps, which is very messy. In the future, any changes to the withdrawal processing logic will modify this method, this will cause more trouble for future maintenance and development. At the same time, such a program is not easy to read. It violates the principle that one method can only do one thing, the logic at different abstract levels is mixed together, so it is difficult to give readers a clear overall concept.

The following is the method for processing withdrawals after sorting:

Some programmers will immediately say that the more complicated you are, the better you are! Let's take a closer look:

1) The withdrawal (accno, amount, password) method has become simple and clear. From this method, we can clearly see the withdrawal process; it is almost exactly the same as the requirement description, and the details are hidden. In the future, no matter how the logic of the Legality check, debit account or credit account changes, this method is stable. You may also ask, this method seems to have done several things. Isn't it against the one-thing Principle? No, it only does one thing-Withdrawal processing, each action in itAll process steps at the same Abstraction Level. Note:Same Abstraction LevelThis is an important concept and an important principle of method design. The internal processing actions of a method must be at the same Abstraction Level and cannot be mixed.

2) After we have a consensus on the improvement of the withdrawal () method, let's take a look at the more benefits brought by this method. The details are hidden in the specific small method, and where to change in the future, this benefit has been mentioned earlier. The bigger advantage is that we have extracted a public method of debit, credit, and debit, and all kinds of funds-related businesses in the banking industry should eventually be recorded, or debit or credit, we have three unified accounting methods. You can say that you have established the Core algorithms of the core banking system, (Of course, the core accounting module of the actual system is more detailed and rich than this). In fact, other methods are also very versatile, this is the deep-seated purpose that we need to design based on the method design principles. It will bring us greater value.

 

4.4 The method should be short

With the preceding rules, this rule is quite natural. The shorter the method is, the better, and the shorter the method is, the purpose is to let you observe the first few rules. If you observe the previous rules, the method will naturally be short. to quantify the rules, it is required that the average method body cannot exceed 30 rows, up to 60 rows are allowed.

4.5 As few parameters as possible

The parameters of a method must be determined based on their responsibilities. To meet sufficient and necessary requirements, too many parameters mean too many responsibilities. violating the principle of doing only one thing will cause a number of troubles. Therefore, the following requirements must be met:

The parameter of the class method is preferably zero, followed by one, followed by two, and more than three are avoided as much as possible.

The static methods provided for other classes are determined based on their responsibilities. Unnecessary parameters must be deleted.

4.6 avoid side effects

The so-called side effect is that the method does what it shouldn't do. In fact, this is very serious. Some methods promise to do only one thing, but it quietly does something else, for example, Lei Feng is a good example in life. The software system never advocates the spirit of Lei Feng, but requires you to do your own thing well ). Or you have made unexpected changes to an attribute in the class, which is very destructive and may cause strange Time Series Coupling and order dependency. This error is very difficult to find and locate, this function is a lie.

4.7 eliminate duplicates

Repetition is the root of all evil in Software. In fact, repetition occurs not only in the logic of the method, but also in the data. For example, the pull-down code used by the front end is defined separately with the code used in the background program, therefore, we must strive to eliminate all duplicates.

The repetition in the Code is obvious, some are not obvious, some seem the same, the reality is different, some seem different, the reality is the same, how can we design clean, eliminate duplication, requires long-term practice and efforts, it reflects your abstract analysis and comprehensive capabilities. It requires us to analyze the business field as a whole, and extract and accumulate basic and shared stable business logic from it. The following are some simple methods:

1) When copying and pasting, you need to think carefully about whether you are making duplicates and whether there is a public method that needs to be extracted.

2) When the logic you write is similar in many forms, you need to think deeply. Here there may be implicit repetition, for example:

If (......) {

}

If (......) {

}

......

If (......) {

}

Such statements are often duplicated. The following code illustrates the problem:

.........

If(CtldInstanceofUbvdcpsgroup) // Group

ReturnControl.Makegroup(Type, P, (ubvdcpsgroup) ctld, objfct, BD );

If(CtldInstanceofUbvdcpssw) // Single Window

ReturnControl.Makesw(Type, P, (ubvdcpssw) ctld, objfct, BD );

.....................

If(CtldInstanceofUbvdguispace) // hide the placeholder Control

ReturnControl.Makespace(Type, P, (ubvdguispace) ctld, objfct, BD );

In this way, the handling process is long, monotonous and cumbersome, and there seems to be no better solution, but remember that there is no difficulty in the world, and such a bad structure will certainly find a good solution.

First, we create a control to describe the comparison between the class name and the actual class name of the control. ctldesandctlmap, control provides a method to create a control based on the class name.

Makectlbyname (); then add the followingCreatcontol () method:

Private StaticControl creatcontol (ubvdgui ctld, afcomcfgobj ctlcfg,

CharType, composite P, affrobjfactory objfct, afbindingdata BD ){

If(Ctld =Null)Return null;

String vdname = ctld. getclass (). getname ();

String ctlclzname = ctldesandctlmap. Get (vdname); // obtain the name of the physical control through the control description name

If(Ctlclzname =Null)Return null;

Control CTL =Null;

Try{

CTL = control.Makectlbyname(Type, P, ctld, objfct, BD, prsuc, ctlclzname );

ReturnCTL;

}Catch(Exception e ){

E. printstacktrace ();

Return null;

}

}

With the above preparations, the previous ugly and long code can be completed with the following line of code:

Creatcontrol (ctld, ctlcfg, type, P, objfct, BD );

In addition, you do not need to modify the program after adding new controls. You only need to add the corresponding comparison table. In this way, you can understand and understand the open and closed principles, open the new controls, and close the modifications; in addition, it is prompted that our application framework has provided a convenient basic method for key-Value Pair configuration. You need to obtain the configuration information through key-value pairs at the early stage of system startup, use this method.

This kind of repetition in the program needs to be noticed, and efforts should be made to eradicate this implicit repetition in a more elegant way.

There is also an ugly program process, called the value assignment sequence:

User. Name = Name;

User. Amount = amount;

......

User. Add = add;

A long and boring assignment sequence like this is also a bad code. There are two solutions: one is to encapsulate them in an underlying function, second, the parameter configuration is used to solve such tedious assignment problems. This not only avoids ugly code, but also achieves parameterization, such as our service call module, value assignment is performed according to the uniform service description.

4.8 polish your program

If you want to get high-quality programs, you must refine your programs repeatedly and rebuild and modify them. However, do not make the changes messy. You should repeat them under the guidance of rules, make the code concise, efficient, clear, and easy to read, eliminate duplicates, and focus on one thing.

5. Notes

Annotations are details of programming. Specific provisions should be clarified in coding specifications. Here are just a few guiding principles:

1) Concise and valuable

Comments are not the more the better. Annotations should be concise and clear. The key to comments is to describe the program intent so as to make value; put forward nonsense, for example:

A = 10; // initially, a or 10 is assigned to.

Such comments are nonsense, so it is best not.

2) annotations must be added to key locations and environments.

Comment before the class to introduce the class and describe its responsibilities and functions;

The comment before the method describes the functions and parameters of the method;

The comment in the method body must be commented on in key parts to describe the intention, for example, in the loop, Branch judgment, and other key points.

3) Remove out-of-date and program-inconsistent comments in a timely manner

We often find that a large number of comments that are inconsistent with the program exist in many programs. These comments do not remove in time, which may affect reading and judgment. Therefore, we must take the habit of deleting these comments in time, their existence is a kind of sin, which has infinite harm.

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.