Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicate code by passing a method or something?

Tags:

c#

.net

oop

I have two methods exactly like each other but just in a line imagine :

    public void ApplyHorizontalScale(int x, int Y)
    {
        // Code 1
        forecast.Formula = Method1(X, Y);
        // Code 2
    }


    public void ApplyVerticalScale(int x, int Y)
    {
        // Code 1
        forecast.Formula = Method2("Foo");
        // Code 2
    }


    int Method1(int x , int y)
    {
        return x+y;
    }

    int Method2(string s)
    {
        return Foo.Length;
    }

The problem is Code 1 and Code 2 have been repeated twice! how can I have something like :

public void ApplyScale(int x, int Y, WhichMethod)
{
        // Code 1
        forecast.Formula = WhichMethod();
        // Code 2
}

please notice that Method1 and Method2 have different signature and also one of them is accessing a private member.

like image 515
Javid_p84 Avatar asked Sep 21 '26 16:09

Javid_p84


2 Answers

ApplyVerticalScale and ApplyHorizontalScale are perfectly good methods - you don't need to combine them into one "God" ApplyScale public method.

You should refactor the internals of the method to call some private ApplyScale (or similar) method that contains Code1 and Code2 once, with each method passing whatever it needs to apply scale in that particular orientation.

like image 94
starskythehutch Avatar answered Sep 24 '26 06:09

starskythehutch


This is one way to do it

public void ApplyScale(int x, int Y, bool isHorizontal)
{
    // Code 1
    if(isHorizontal)
    {
       forecast.Formula = Method1(X, Y);
    }
    else
    {
       forecast.Formula = Method2("Foo");
    }
    // Code 2
}

You can also use enum instead of the isHorizontal flag

like image 36
Vamsi Avatar answered Sep 24 '26 05:09

Vamsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!