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-02-24 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 ways to replace if-else". In daily operation, I believe many people have doubts about which methods to replace 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 to answer the questions of "what are the ways to replace if-else?" Next, please follow the editor to study!

Design better software and replace 5 ways of If-Else, from getting started to advanced examples

If-Else is often a bad choice, resulting in complex design, poor readability of code, and can lead to refactoring difficulties.

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.

I'm going to show you some techniques and patterns that will put an end to this terrible practice. Each example is more difficult.

Completely unnecessary Else block

This is perhaps 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 the else `block to simplify the process, as shown below:

Removed else

Doesn't it look more professional? You will find that there is no need for other blocks at all. As in this case, you want to perform certain actions and return immediately if certain conditions are met.

Value distribution

If you want to assign new values to variables based on some of the inputs provided, stop If-Else nonsense, a more readable method.

Value assignment with if-else

Simple as it is, it 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'll have clean readable code left. Notice that I also changed the style to a quick return instead of a single return statement. If you have found the correct value, there is no point in continuing to test a value.

Prerequisite check

In general, I find it pointless to continue 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.

Method without value checks

There is no point in executing this method without value verification. Therefore, we need to check some prerequisites before allowing the method to continue.

Using 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

At this point, we ensure that the primary logic is executed only if 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.

Convert If-Else to dictionary and avoid If-Else completely

Suppose 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.

Extend the application to 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 correct approach is to follow the SOLID principle, and we do this by implementing a dynamic type discovery process (in this case, a policy pattern).

The process of refactoring this confusion is as follows:

Use the common interface to extract each branch into a separate policy class.

Dynamically find all classes that implement a common interface.

Decide which policy to execute based on the input.

The code that replaces the above example is as follows. 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