Reconstruction Method-Simplified conditional expression [1], reconstruction expression

Source: Internet
Author: User

Reconstruction Method-Simplified conditional expression [1], reconstruction expression

Total returned directory

Directory of this section

  • Decompose Conditional (decomposition condition expression)
  • Merge lidate Conditional Expression (merge condition Expression)
1 Decompose Conditional (decomposition condition expression) Summary

You have a complex condition (if-else) statement.

Separate functions from the if, else if, and else sections.

Motivation

Complex conditional logic often leads to an increase in program complexity. Writing code to check different condition branches and doing different things based on different branches often leads to excessive function length.

The conditional expression is divided into multiple independent functions. Based on the purpose of each small piece of code, the new function is named, and the code corresponding to the original function is changed to call the new function, in this way, you can clearly express your intention. For condition logic, breaking each branch condition into new functions can also highlight the condition logic, clearly show the role of each branch, and highlight the causes of each branch.

Example

Assume that you want to calculate the total price of a certain item, and the unit price of this item in winter and summer is different:

class Order{    public double Quantity { get; set; }    public double WinterRate { get; set; }    public double SummerRate { get; set; }    public double WinterServiceCharge { get; set; }    public double GetCharge(DateTime date)    {        double result;        if (date.Month < 3 || date.Month > 6)        {            result = Quantity * WinterRate + WinterServiceCharge;        }        else        {            result = Quantity * SummerRate;        }        return result;    }}

Now we extract the judgment conditions of each branch into an independent function:

class Order{    public double Quantity { get; set; }    public double WinterRate { get; set; }    public double SummerRate { get; set; }    public double WinterServiceCharge { get; set; }    public double GetCharge(DateTime date)    {        double result;        if (NotSummer(date))        {            result = WinterCharge(Quantity);        }        else        {            result = SummerCharge(Quantity);        }        return result;    }    private bool NotSummer(DateTime date)    {        return date.Month < 3 || date.Month > 6;    }    private double SummerCharge(double quantity)    {        return quantity * SummerRate;    }    private double WinterCharge(double quantity)    {        return quantity * WinterRate + WinterServiceCharge;    }}

This code shows the clarity of the entire refactoring.

Summary

In the above cases, many people will not refine the branch conditions. Because these branch conditions are often very short, it seems that there is no need to extract them. However, although these conditions are often very short, there is often a small gap between the Code intent and the Code itself. As shown above, the NotSummer (date) Statement better expresses its intention than the original code. The original code, I have to look at it, think about it, in order to say its role. Of course, it seems very simple here. Even so, the extracted functions are more readable.

2 merge lidate Conditional Expression (merge condition Expression) Summary

You have a series of conditional tests and get the same results.

Combine these tests into a conditional expression and extract the conditional expression into an independent function.

Motivation

There are often such checks in the Code: Check conditions are different, but the final behavior is consistent. If this is the case, use logic and logic or to combine them into a conditional expression.

There are two reasons for merging the conditional code. (1) the combined condition code will tell you that "there is actually only one condition check, but there are multiple parallel conditions that need to be checked", so that the purpose of this check is clearer. (2) This refactoring is often used to prepare for using the Extract Method.

Example: use logic or
class Amount{    public int Seniority { get; set; }    public int MonthsDisabled { get; set; }    public bool IsPartTime { get; set; }    double DisablilityAmount()    {        if (Seniority < 2)        {            return 0;        }        if (MonthsDisabled > 12)        {            return 0;        }        if (IsPartTime)        {            return 0;        }        //compute the disability amount        //your code here        return 1;    }}

In this Code, a series of condition checks are doing the same thing. For such code, the above check is equivalent to a statement that is logically or connected:

class Amount{    public int Seniority { get; set; }    public int MonthsDisabled { get; set; }    public bool IsPartTime { get; set; }    double DisablilityAmount()    {        if (Seniority < 2 || MonthsDisabled > 12 || IsPartTime)        {            return 0;        }        //compute the disability amount        //your code here        return 1;    }}

Now, we observe this new conditional expression and Extract it into an independent function using the Extract Method to express the conditions checked by the statement using the function name:

class Amount{    public int Seniority { get; set; }    public int MonthsDisabled { get; set; }    public bool IsPartTime { get; set; }    double DisablilityAmount()    {        if (IsNotEligibleForDisability())        {            return 0;        }        //compute the disability amount        //your code here        return 1;    }    bool IsNotEligibleForDisability()    {        return Seniority < 2 || MonthsDisabled > 12 || IsPartTime;    }}
Example: use logic and
class Rate{    public double GetRate()    {        if (OnVacation())        {            if (LengthOfService() > 10)            {                return 1;            }        }        return 0.5;    }    private bool OnVacation()    {        return true;    }    private int LengthOfService()    {        return 9;    }}

This code can be changed to the following:

class Rate{    public double GetRate()    {        if (OnVacation() && LengthOfService() > 10)        {            return 1;        }        return 0.5;    }    private bool OnVacation()    {        return true;    }    private int LengthOfService()    {        return 9;    }}

If the observed part only checks the condition and returns a value, you can use the ternary operator to convert this part into a return statement. Therefore, the following code:

if (OnVacation() && LengthOfService() > 10){    return 1;}return 0.5;

It becomes:

return (OnVacation() && LengthOfService() > 1) ? 1 : 0.5;
Summary

So when do we not need to merge expressions?

That is to say, we believe that these checks are indeed independent from each other and should not be considered as the same check, so we will not use this reconstruction item.

 

 

To Be Continued...

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.