Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upgrade if-else coder

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article shows you how to upgrade if-else coder, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.

Start with if-else.

I always say that we should not be an if-else coder. The if-else here does not mean that we cannot use if-else when we are in coding, but that we should not simply use if-else to implement the branch process of the business, because it is easy to pile up a mountain of shit with such random code.

The difference of business is the root of if-else. Take the commodity business of Retail pass as an example. The implementation of business logic is different in different processing scenarios. As shown in the following figure, the difference in commodity business is mainly reflected in the type of commodity, the way of sale and the way of warehousing.

Combined with the differences in these three dimensions, there are as many as 23 2 = 12. That's why codes like if (combo) blabla,if (giveaway) blabla,if (real warehouse) blabla can be seen everywhere in the old code.

So how to get rid of these pesky if-else? We can consider the following two ways:

Polymorphic extension: the reuse and extension of code is realized by using the polymorphic feature of object-oriented.

Code separation: different process codes are used for different scenarios. This is clear, but not maintainable.

1. Polymorphic extension

Polymorphic extensions can be inherited and combined. Inheritance does not use too much words, combination is a bit like a strategic pattern, that is, the parts that need to be extended are encapsulated, abstracted into objects that need to be combined, and then extended, such as the ability extension point of star rings.

Here, let's take an example of inheritance. When a product is on the shelf, it is necessary to check whether the product is available for sale. The Item needs to check itself, while the CombineItem needs to check each sub-item.

Using procedural coding, it is easy to write code like this:

Public void checkSellable (Item item) {if (item.isNormal ()) {item.isSellable (); / omit exception handling} else {List childItems = getChildItems (); childItems.forEach (childItem-> childItem.isSellable ()); / / omit exception handling}}

However, this implementation is not elegant, does not satisfy OCP, and lacks explicit expression of business semantics. Better still, we can explicitly express the relationship between CombineItem and Item through the model.

In this way, on the one hand, the model correctly reflects the entity relationship and becomes clearer. On the other hand, we can use polymorphism to deal with the differences between CombineItem and Item, resulting in better scalability. After refactoring, the code becomes:

Public void checkSellable (Item item) {if (! item.isSellable ()) {throw new BizException ("the status of the goods cannot be sold and cannot be put on shelves");}}

two。 Code separation

The so-called code separation means that we separate them with different orchestration code for different business scenarios. Taking goods on the shelves as an example, we can write:

/ * 1. General merchandise on shelves * / public void itemOnSale () {checkItemStock (); / check inventory checkItemSellable (); / check availability checkItemPurchaseLimit (); / check purchase restriction checkItemFreight (); / / check freight checkItemCommission (); / check commission checkItemActivityConflict (); / / check activity conflict generateCspuGroupNo (); / / generate item group number publishItem (); / release goods} / * 2. The combined merchandise is on the shelf * / public void combineItemOnSale () {checkCombineItemStock (); / / check inventory checkCombineItemSellable (); / / check availability checkCombineItemPurchaseLimit (); / / check purchase restriction checkCombineItemFreight (); / / check freight checkCombineItemCommission (); / / check commission checkCombineItemActivityConflict (); / / check activity conflict generateCspuGroupNo (); / / generate item group number publishCombineItem (); / / release goods} / * 3. The giveaway is on the shelf * / public void giftItemOnSale () {checkGiftItemSellable (); / / check the availability status of publishGiftItem (); / / release goods}

This way, of course, can also eliminate if-else, independent of each other, but also clear. But reusability is a problem.

3. Multidimensional analysis

If you are careful, you may have found that in the above case, the business processes of ordinary goods and combined goods are basically the same. If you use two sets of orchestrated code, a little redundancy, this repetition will not be conducive to the maintenance of the later code, there will be scattered changes (a business logic needs to be modified in many places).

At one extreme, if only checkSellable () is different between an ordinary commodity and a combination of goods, everything else is the same. There is no doubt that it would be more appropriate for us to use polymorphic (inheritance) CombineItem and Item to deal with differences.

On the other hand, the situation of free gifts on the shelves is just the opposite, and the process is very different from that of other goods. On the contrary, it is not suitable to share a set of process code with them, because it will increase the cost of understanding for others. It is not as clear as setting up a separate process.

So, the question is, when are we going to use polymorphism to handle differences, and when are we going to use code separation to handle differences?

Next, I'm going to focus on one of the methodologies of multidimensional analysis for you today: Matrix analysis.

We can create a matrix where the columns represent the business scenario and the horizontal columns represent the business actions, and the contents represent the detailed business processes of the business actions in this business scenario. For our merchandise business, we can get the following matrix:

Through the above matrix analysis, it is not difficult to see that common products and combinations can reuse the same set of process orchestration codes, while the business of giveaways and inventory products is relatively simple, so it is more suitable to have a set of independent orchestration codes. Such a code structure will be easier to understand.

Dimensional thinking

1. The importance of multiple dimensions

The above case is not made up by me, but a true story that I am discussing with Zhang Wen (my colleague) about how to deal with business differences.

I remember thinking about this question all the time after discussing with the university and driving back, and then suddenly an inspiration came to me when I was waiting for the red light at the second intersection. Unable to restrain my excitement, I sent a message to Zhang Wen while driving and said, "I have come up with a very NB methodology that can solve the problem of how to choose between 'polymorphic extension' and 'code separation'."

In fact, I know that I am excited not only to solve this problem. I was excited that for the first time I really realized the importance of multi-dimensional thinking. Thus there is an opportunity to upgrade from a "single-dimensional" creature to a "multi-dimensional" thinker. Mom doesn't have to worry about me being hit by dimensionality reduction anymore:)

Structured thinking is useful, useful, very useful, but it focuses more on things in one-way dimensions. For example, I want to disassemble the business process, I want to break down the work schedule given to me by my boss, and I want to comb through the test cases, which are all one-way dimensions.

Complexity is usually not only the complexity of one dimension, but also the cross-complexity of multiple dimensions. When the problem involves many elements and the relationship between them is very complex, the two dimensions will certainly be clearer than one, which is why matrix thinking is a higher-level way of thinking than structured thinking.

In fact, from the Chinese vocabulary, it is not difficult to see that a person's level of thinking is positively related to his thinking dimension. When we say that this person is very "axial" and "single-minded", we are actually saying that he has only one-dimensional linear thinking. Therefore, the more the perspective of observing things, the richer the dimensions, the higher the level of thinking will be.

two。 Multidimensional thinking everywhere

With these insights, I began to systematically sort out the data on multi-dimensional thinking and analysis, and found that this way of thinking is really ubiquitous. The more I found, the more I wondered why I didn't realize until now why such an important way of thinking.

1) Boston matrix

For example, when doing product analysis, there is a Boston matrix to analyze the prospects of product development.

2) order element analysis

At that time, when I was in the business of issuing orders in 1688, there were many scenarios in which buyers enjoyed different benefits (as shown in the table below). At that time, we also used matrix to express this complex relationship, but we did not think of raising it to the level of methodology at that time.

3) data cross analysis

In data analysis, dimensional analysis is very important, especially when there are many dimensions, we can do cross-analysis through Pearson product moment correlation coefficient, so as to make up for some problems that can not be found by independent dimensional analysis.

Simple correlation coefficient matrix

4) Analytical matrix

Recently, I happened to see Alan Shalloway's "Design pattern parsing: Design Patterns Explained", which is a very classic book about OOP, in which Chapter 16 is devoted to "Analytical Matrix". The author created this methodology because there are too many elements involved in the business and too much information. He needs a new way to organize huge amounts of data.

My path is different from that of Alan, but we both come to the same conclusion. Thus it can be seen that this way of matrix analysis is indeed a sharp tool for the analysis of complex business, the more business scenarios, the more complex the cross-relationship, the more need for such analysis.

5) organizational formation

Production relations determine productivity, for a manager, how to effectively set up the organizational structure is the key to determine whether the team can cooperate efficiently. So we can see that there are relatively large adjustments to the organizational structure and personnel arrangements in the company every year.

For the technical team, we are used to dividing the scope of work by area, which has the advantage of human responsibility and clear responsibility. However, the domain is only a dimension, and our work is usually carried out in the form of a project, which usually spans multiple areas. Therefore, when we do team organization planning, we can look at it through the two dimensions of business domain and business project.

For example, in the merchandise team I am in charge of, I will divide my responsibilities in the following form.

6) time dimension

In addition to work, the importance of multi-dimensional thinking can be seen everywhere in life.

For example, we say that it is shameful to waste and should lick the plate cleanly. Don't you know that after adding the time dimension, your current licking disk may cost more resources and energy to lose weight, which will lead to more waste.

We say the code is ugly because we want to support the business "quickly". With the addition of the time dimension, this temporary compromise leads to unexpected bug, online glitches, and endless 996.

7) RFM model

Simple thinking is "point", such as licking the disk and code stacking is the current "point"; better thinking is "line", and after adding the timeline, it is not difficult to see that the "point" is problematic; more comprehensive thinking is "face" (two-dimensional); more systematic thinking is "volume" (three-dimensional); for example, the RFM model is a very good three-dimensional model. Unfortunately, in terms of expression, we human beings can only simulate three-dimensional space in two-dimensional space, otherwise four-dimensional may be more useful.

Summary of complex Business Governance

In the preface, I have already said that multidimensional analysis is an upgrade of the previous methodology. Coupled with the previous methodology, the complete methodology should be "business understanding-- > domain modeling-- > process decomposition-- > multidimensional analysis."

In order to make it easier for you to understand, let me make a simple series and explanation of these methodologies.

1. Business understanding

Understanding the business is the starting point of all work. First of all, we need to find the core elements of the business, understand the core concepts, and comb the business process.

For example, in the retail commodity domain, we need to know what is Item, what is CSPU, and what is CombineItem. In the order field, we need to know that the constituent elements of the order (order) are goods, discounts and payments. In the CRM world, we need to understand customers, opportunities, contacts, Leads, and so on.

Here, I would like to stress once again the importance of language, language is the carrier of our thinking, as Wittgenstein said: "whatever can be said, can be said clearly."

You should not let go of any vague business concept, be sure to understand it thoroughly and give it a reasonable name (Ubiquitous Language). Only in this way can we understand the business more clearly and carry out the follow-up work better.

two。 Domain modeling

In software design, model refers to entities, as well as the relationship between entities, here we need to have a good abstract ability. Be able to find the essential core of a transaction through numerous and complicated appearances.

No matter how complex the business area, its core concepts should not be too complex, grasp the core, we grasp the main line, the business is often carried out around these core entities.

For example, although the commodity domain is very complex, its core domain model is nothing more than the following figure:

3. Process decomposition

About process decomposition, in Ali Advanced Technical expert Methodology: how to write complex Business Code? "it has been elaborated in great detail, so I will not repeat it here.

To put it simply, process decomposition is to decompose the business process in detail, using a structured methodology (first deduction, then induction), and finally form a pyramid structure.

For example, in the commodity field, there are a series of actions (processes), such as creating goods, putting goods on the shelves, reviewing goods on shelves, checking products off shelves, modifying goods, deleting goods and so on. There is a very complex business logic behind each action. We need to sort out these processes in detail and then decompose them step by step. Finally, a pyramid structure is formed as follows:

4. Multidimensional analysis

With regard to multidimensional analysis, I will take the two-dimensional matrix analysis as an example. I think I should have made it clear before.

The complexity of business is mainly reflected in the complexity of the process and the interrelation and dependence of multi-dimensional elements. Structured thinking can help us sort out the process, while matrix thinking can help us sort out and present multi-dimensional relevance and dependence. The combination of the two can show the whole picture of complex business in a more comprehensive way. So that our governance can be targeted, there are rules to follow.

Since it is a methodology, I will try to give a framework of matrix analysis here. Just imagine, if our business is simple, there is only one business scenario and no branch process. Our system won't be too complicated. The reason for the complexity is that various business scenarios superimpose, depend on, and influence each other.

Therefore, when we do matrix analysis, the vertical axis can choose to use the business scenario, and the horizontal axis is an alternative dimension, which can be the business process affected by the scenario (such as the commodity process matrix diagram in the article). It can also be the business attributes affected by the scenario (such as the order component matrix diagram in the article), or any other "things" of a different nature.

Through the matrix diagram, we can clearly show the differences of business in different scenarios. Based on this, we can customize the best implementation strategy to meet the differences, which may be polymorphic extension, separate code, or others.

This is the essence of matrix analysis, and its essence is a methodology of multi-dimensional thinking.

Send words after the article

Finally, I would like to say that the world is entropy-increasing (that is, everything is slowly falling apart), and controlling complexity is a responsibility and mission that we practitioners cannot shirk.

The development of the software industry is only a few decades, and it is still a young discipline. Software engineering is like a child who has just learned to walk, very immature and sometimes naive.

But after all, there are still decades of precipitation, there are still some good methods and practices to refer to, my summary of precipitation is only on the basis of predecessors, just a little bit more. But even this little bit, it is not easy to come by, in which the cold and warm, only you can understand. It can be said that along the way, it is a continuous test of mental, mental and physical strength.

Mental strength refers to the ingenuity of not making do with it, the determination not to compromise, the curiosity that is not satisfied, and the persistence of not giving up.

Brainpower refers to those necessary thinking ability, learning ability, thinking ability, thinking ability.

The reason why "business understanding-- > domain modeling-- > process decomposition-- > multidimensional analysis" is physical, because implementing them is like filling in blanks, as long as you are willing to take the time, no matter how complex the business can become clear step by step.

Once sorted out and guided by COLA, it is possible for us to write clear and readable code and upgrade from an if-else coder to a complexity conquer.

The above is how if-else coder is upgraded. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report