Are you still using if else? [Transfer]

Source: Internet
Author: User
The main difference between process-oriented design and object-oriented design is whether to use lengthy if else judgment at the business logic layer. If you are still using the if else in large quantities, except for the interface presentation layer, even if you use a fully object-oriented language like Java/C, it only means that your thinking stays on the traditional process-oriented language.

Traditional thinking habits Analysis

Why does the business logic layer use if else? In fact, the user's goal is to reuse it, but this is a process-oriented reuse of programming,ProgramMembers only seeCodeReuse, because it can be seen that most of the Code in if else is repeated and only a few are different, so using if else can avoid code duplication and think it is a template pattern.

He Fan's error is: programmers only look at the code in the direction of the code running sequence. This kind of thinking is similar to water pipes or serial circuits, where water flows along the water pipes (code running order ), when there are several sub-managers, the sub-pipes are flowing, which is equivalent to the IF else of the Code.

When Oo is used, the code is first broken from the order up to down, which is equivalent to the order in which the code is run. The code structure is determined by the order in which it is executed. What is the decision? Designed by Oo; The design pattern will replace these if else, but at last these oo modules are always assembled by a service and other general classes in the running order. There is only one such module, which can contain transactions, it is generally a service, and the EJB is a session bean.

Once the requirements change, we may be more likely to be the various oo modules in the service, or even only change the execution sequence of the OO modules in the Service to meet the requirements.

Here we also see the idea of OO separation, which completely breaks down a main function in the previous process language and separates the running sequence from other logic of the Code, rather than being as messy as the process-oriented logic. Some people feel that OO is also in order. This is for sure. The key is that the running sequence should be separated separately.

If else does not exist, you can see whether you have separated the running sequence to the home.

Design mode switch entry

It is often reported that the design mode is good, but it is difficult for me to use. In fact, if you use if else to write code (except for display control), you are writing business logic, however, a simple judgment statement is used as a replacement for the actual situation.

Take the forum post that you are familiar with as an example. For example, forummessage is a model, but in practice the post is divided into two types: topic post (first root post) and reply (back to the previous post), there is a simple solution:
Create a forummessage and add istopic to the forummessage to determine the statement. Note that the introduction of a simple attribute here may lead to If else judgment everywhere in your program.

If we use another method of analysis and implementation, we can look at it as an object. In reality, there are two types of objects: topic stickers and replies. However, most of these two objects are consistent. Therefore, I set forummessage as an expression topic, and then create a subclass forummessagereply that inherits forummessage as a reply. In this way, I have determined that this model is a reply in a program, such as a service, I can directly go down to forummessagereply, which is a bit similar to the forced type conversion when I put the object into the collection and retrieve it. This method eliminates the possibility of the IF else judgment statement in the program.

This shows that incorrect analysis may also lead to misuse of the model.

We will discuss the example of a design pattern. We cannot use cases without business context. Otherwise, we cannot decide whether to use the pattern. The following are two examples of comparison:

First, there is no context for the first code case in this post. This article only describes a piece of code:

Main (){
If (Case ){

// Do with strategy

} Else (Case B ){

// Do with STRATEGY B

} Else (Case C ){

// Do with strategy C

}

}

This code is pure code and has no business functions. Therefore, in this case, it is difficult for us to determine which mode to use, that is, the policy mode must be used, it cannot escape the fate of using if else. The design pattern is not magic. It cannot make meaningless code simple, and it can only expand the business functions it embodies more easily.

Second. in this post, the author gave a packetparser business case. This code shows the business functions and analyzes data packets. The author also compares the usage of different modes, therefore, we still use the dynamic proxy mode or command mode to eliminate the possible if else

The above two cases show that the business logic is the starting point for us to use the design model, and when we break down the business logic, we may use if else for implementation, if you have such an attempt or already implemented the code, you should consider whether refactoring needs to be reconstructed.

If else replacement

In practice, which design modes can replace if else? In fact, the gof design pattern can be used to replace if else. We describe it as follows:

Status Mode
When there are various possible statuses of Data Objects, and this status will affect different service results, we should consider whether to use the status mode. Of course, before using the status mode, you must first have the concept of memory status, not the concept of database, because in the traditional process-oriented/database-oriented system, it is difficult to find the status, reading a value from the database and distributing code based on the value is a common task for beginners. ReferenceArticle: Status object: Database replacement
In the case of traditional language thinking, a class integer variable is used to identify the status:

Public class order {

Private int status;

// Description:

// Status = 1 indicates order but view;

// Status = 2 indicates that the file has not been processed;

// Status = 3 indicates that the unpaid payment has been processed

// Status = 4 indicates payment has not been delivered

// Status = 5 indicates that the product has been delivered.

}

The above class design undoubtedly uses the class as a function of the traditional language, which leads to a large number of if else in the program code.

Rule Mode
When you face severalAlgorithmWhen selecting a formula, you can consider the policy mode. In the traditional process language, the algorithm value is read from the database. The value 1 indicates policy 1, for example, saved to the database; A value of 2 indicates policy 2, for example, saved to an XML file. Here, if else is used as the switch for policy selection.

Command mode
The traditional process is: if the client sends the Code 1 or "A", then I call. java. If the code is 2 or "B", I will call B. if else is used to determine the code sent from the client, and then the corresponding table is specified in advance, and the corresponding class is called for processing.

MVC Mode
The misuse of the traditional language in MVC mode is similar to the command mode. In an action class, if else is used for frontend and backend scheduling, if the client sends any command, I will call the backend result; if the background processes any structure, we can decide what pages to push. However, now we do not need to make such a low-level error when using the MVC mode such as struts/JSF.

Responsibility Chain Model
The responsibility chain mode and command mode are optional. If you do not know what code will be issued by the client, there is no pre-defined table, then you can only write classes to open the package just as you try your luck. Unlike command, it is analyzed in the document of AOP vs decorator.

Proxy or dynamic proxy Mode
A proxy object can be a representative that meets certain conditions, such as permission verification. The traditional process-oriented thinking is that when a user logs on to a resource, he or she uses if else for judgment, only when certain conditions are met can access be allowed. In this way, the permission judgment is in disorder with the business data logic, and the proxy mode can be clearly separated. If it is not good, use dynamic proxy, or the following methods, such as AOP.

AOP or decorator Mode

In fact, the use of the filter can also replace the if else in our business. The filter can be used to filter and filter objects that comply with the filter conditions to intercept and do something, this is the function of a filter. The combination of multiple filters is actually the combination of if else.
Therefore, if you really cannot find any way, you can use a filter to regard the filter as a firewall. When the client has a request, it goes through a firewall of different nature, this firewall intercepts ports, which are security check interceptions, and so on. Filters are similar to various filters of red, blue, and white light. The red filter can only intercept the red color in the light. The blue filter blocks the blue color in the light, which is actually used to break down the light using the if else.

We use conditional filters to implement three-dimensional Signal Separation. If you use if Else, it means that you combine conditions 1/2/3/4 in the image, implement condition judgment in the same place.
To learn more about the implementation details and minor differences of filters, see: AOP vs decorator

Summary of OO design

There is also a pseudo-mode. Although the State mode is used, the IF else or switch mode is actually used inside the mode for status switching or important condition judgment, which undoubtedly requires further efforts. More importantly, you cannot live in a model and publish a book to people.

It is difficult to grasp the object-oriented thinking. At present, there are various explanations that refer to pulling up your hair, therefore, I think it is useless for beginners to read thinking in Java (Java programming ideology). It attempts to talk about OO programming ideology at the language level and is very unsuccessful. It can be used as a language reference, however, the learning materials for the OO ideology embodied in Java are wrong.

The OO programming idea is a kind of method *****. If there is no application comparison, you cannot understand the characteristics of this method, zen is an ancient party ****, and wuzen can be realized only by cutting water and cutting firewood.

So what application can oo idea be realized? It is a gof design model. The gof design model is equivalent to a software engineer's basic activities such as cutting water, cutting firewood, etc. So if a programmer can't even have a basic job, why does he live as an OO programmer? I am engaged in OO professional design and programming. If I do not master the basic skills of the design model, it is like a monk who is unwilling to pick water and cut firewood. Why is he based on this industry? The master has been driving down the hill for a long time.

Conclusion: If else can be used in a small place, such as a simple numerical value. However, if you follow your traditional habits, if else is also used to implement business functions, it means that your thinking may need to be reshaped. The richer your programming experience is, the more deep-rooted the traditional process thinking model is. It is difficult to change your thinking by yourself. We recommend that you receive professional brainstorm training.

To sum up one sentence: if you have made a lot of systems and haven't used if else for a long time, it means that you may actually enter the OO design stage. (This is my own practical evaluation standard ).

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.