laitimes

Write if-else again, catch a fine of 1000

author:Civen

This article does not affirm or deny which way to write, but only provides you with some other coding ideas or some ideas worth learning.

Write if-else again, catch a fine of 1000

Design better software and replace If-Else's 5 methods, from getting started to advanced examples

If-else is often a poor choice, which leads to complex designs, poor code readability, and can lead to difficult refactoring.

However, it does make sense that If-Else has become a de facto code-branching solution. This is the first thing to teach to all aspiring developers.

Unfortunately, many developers never advance to a more appropriate branching strategy. Some people's mantra is: If-else is a hammer, everything is a nail.

I will show you some tips and patterns that will put an end to this terrible practice. The difficulty of each example increases.

# Completely unnecessary Else blocks

This is perhaps one of the most guilty of those junior developers. The following example is a good illustration of what happens when you think If-else is great:

Write if-else again, catch a fine of 1000

Simple if-else

Simply deleting the else' block simplifies this process, as shown below:

Write if-else again, catch a fine of 1000

Removed else

Looks more professional, right? You will find that there is actually no need for other blocks at all. As in this case, you want to perform some action if certain conditions are met and return immediately.

Value distribution

If you're assigning a new value to a variable based on some of the inputs provided, stop the If-Else nonsense, a more readable approach.

Write if-else again, catch a fine of 1000

Value assignment with if-else

Although it is simple, it is terrible. First, If-Else is easily replaced by switches here. However, we can further simplify this code by removing else entirely.

Write if-else again, catch a fine of 1000

If statements with fast return

If we don't use else, we'll be left with clean, readable code. Note that I also changed the style to a fast return instead of a single return statement. If the correct value has already been found, there is no point in continuing to test a value.

# Prerequisite check

In general, I find that it doesn't make sense to continue execution if the method provides an invalid value. Assuming we have had the DefineGender method since before, the input value required must always be 0 or 1.

Write if-else again, catch a fine of 1000

Method without value checks

There is no point in performing the method without proof of value. Therefore, we need to check some prerequisites before allowing the method to continue.

Applying the protective clause defensive coding technique, you'll examine the input values of the method and then proceed with the method.

Write if-else again, catch a fine of 1000

Check preconditions with guard clauses

At this point, 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, as it is no longer necessary to return unknown by default at the end.

Convert If-Else to a dictionary, avoiding If-Else altogether

Let's say you need to perform some actions that will be selected based on certain criteria, and we know that more actions must be added later.

Write if-else again, catch a fine of 1000

Perhaps someone is inclined to use the tried and tested If-Else. If you add a new action, you can simply add something else. Quite simply, however, this method is not a good design in terms of maintenance.

Knowing that we need to add new operations later, we can refactor If-Else into a dictionary.

Write if-else again, catch a fine of 1000

Readability has been greatly improved, and the code can be more easily deduced. Note that dictionaries are placed inside methods for illustrative purposes only. You may want to offer it from elsewhere.

Extend the application to avoid If-Else altogether

This is a slightly more advanced example. Know when to eliminate IFs even altogether by replacing them with objects.

Often, you'll find yourself having to expand some part of your application. As a junior developer, you might be tempted to do this by adding additional If-Else statements.

Take this illustrative example. Here, we need to display the Order instance as a string. First, we only have two string representations: JSON and plain text.

Using If-Else at this stage is not a big problem, if we can easily replace the others, as long as we mentioned earlier.

Write if-else again, catch a fine of 1000

Knowing that we need to extend this part of the application, this approach is absolutely unacceptable.

Not only does the above code violate the open/close principle, but it doesn't read well and can cause trouble with maintainability.

The correct approach is to follow the SOLID principles, which we do by implementing a dynamic type discovery process (in this case, policy mode).

The process of refactoring this messy process is as follows:

  • Use the public interface to extract each branch into a separate policy class.
  • Dynamically find all classes that implement a common interface.
  • Decide which strategy to execute based on the inputs.

The code to replace the example above is shown below. Yes, this is the way of more code. It requires that you understand how type discovery works. But dynamically scaling applications is an advanced topic.

I'll only show the exact part of the If-Else example that will be replaced. If you want to see all the objects involved, review this bullet point.

Write if-else again, catch a fine of 1000

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 build a dictionary with the name of the formatter's displayName as key and the type as value.

Then select the formatter type from the dictionary and try to instantiate the policy object. Finally, call the ConvertOrderToString of the policy object.