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

What are the ways to replace If-Else

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the methods to replace If-Else". In daily operation, I believe that many people have doubts about the method of replacing If-Else. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "what are the methods of replacing If-Else?" Next, please follow the editor to study!

5 ways to design better software and replace If-Else. Getting started to advanced examples lets me just say this: If-Else is usually a bad choice. It leads to complex design, poor readability of code, and may lead to difficulties in refactoring. However, it makes sense that If-Else has become the de facto code branching solution. This is the first thing to teach all aspiring developers. Unfortunately, many developers never move on to a more appropriate branching strategy. Some people's mantra is: If-Else is a hammer, everything is a nail. The inability to distinguish when to use a more appropriate method is one of the reasons to distinguish between juniors and juniors. I'll show you some techniques and patterns that will put an end to this terrible practice. Each example is more difficult. 1. Completely unnecessary Else blocks, which may be one of the most sinful for junior developers. The following example is a good example of what happens when you are thought to be great with If-Else. > Simple if-else simply delete else `block to simplify this process. Doesn't Removed else look more professional? You will often find that no other blocks are actually needed at all. As in this case, you want to perform some actions and return immediately if certain conditions are met. two。 Value allocation if you want to assign new values to variables based on some of the inputs provided, stop If-Else nonsense-a more readable approach. Simple as it is, Value assignment with if-else is terrible. First of all, If-Else can easily be replaced by switches here. However, we can further simplify this code by completely removing the else. > If statements with fast return if we don't use else, we will leave clean readable code. Note that I also changed the style to a quick return rather than a single return statement-there is no point in continuing to test a value if the correct value has been found. 3. In general, I find that there is no point in continuing execution if the method provides an invalid value.

Suppose we have the DefineGender method from before, which requires that the input value provided must always be 0 or 1. > it makes no sense for Method without value checks to execute this method without value validation. Therefore, we need to check some prerequisites before allowing the method to continue. By applying the protective clause defensive coding technique, you will check the input value of the method and then continue to execute the method. > Check preconditions with guard clauses so far, we ensure that the main logic is executed only when the value falls within the expected range. Now, IF has also been replaced by ternary, because it is no longer necessary to return "unknown" by default at the end. 4. Convert If-Else to dictionary-completely avoid If-Else assuming that you need to perform some actions that will be selected based on certain conditions, and we know that we will have to add more actions in the future. Maybe some people tend to use the tried and tested If-Else. If you add a new action, you can simply add something else. It's simple, but, in terms of maintenance, this approach is not a good design. Knowing that we need to add new operations in the future, we can ReFactor If-Else into a dictionary. Readability has been greatly improved, and the code can be more easily inferred. Note that the dictionary is placed inside the method for illustrative purposes only. You may want to provide it from somewhere else. 5. Extended applications-avoid using If-Else altogether this is a slightly more advanced example. By replacing them with objects, you know when or even eliminate If completely. Often, you will find that you have to extend some parts of the application. As a junior developer, you may be inclined to do this by adding additional If-Else (that is, else-if) statements. Take this illustrative example. Here, we need to display the Order instance as a string. First, we have only two string representations: JSON and plain text. Using If-Else at this stage is not a big problem, if we can easily replace others, as mentioned earlier. This approach is absolutely unacceptable knowing that we need to extend this part of the application. The above code not only violates the "on / off" principle, but also doesn't read well and can cause problems with maintainability. The right way is to follow the SOLID principle-we do this by implementing a dynamic type discovery process (in this case, a policy pattern). The process of refactoring this messy process is as follows: use the common interface to extract each branch into a separate policy class to dynamically find all the classes that implement the common interface to decide which policy to implement based on the input to replace the code shown in the above example. Yes, this is the way to more code. It requires you to understand how type discovery works. But dynamically extending applications is an advanced topic. I only show the exact part of the If-Else example that will be replaced. Review this point if you want to view all the objects involved. Let's take a quick look at the code. The method signature remains the same because the caller does not need to know about our refactoring. First, get all the types in the assembly that implement the common interface IOrderOutputStrategy. Then, we set up a dictionary where the displayName of the formatter is named key and the type is value. Then select the formatter type from the dictionary and try to instantiate the policy object. Finally, the ConvertOrderToString of the policy object is called. At this point, the study of "what are the ways to replace If-Else" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Development

Wechat

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

12
Report