如何避免代码重复

发布于 2024-10-05 14:51:35 字数 223 浏览 6 评论 0原文

我有三个几乎执行相同的 C# 方法。更具体地说,有大量的代码重复,但最终它们执行不同的功能。

这显然是非常低效的,那么减少代码重复的最佳方法是什么?我应该将其全部放在一种方法中并使用 switch & 吗?最后的不同功能的枚举?或者,是否有某种方法可以拥有 3 个独立的类并从另一个类继承共享位?我已经阅读了相当多的相关内容,并且根据我所能收集到的信息,这仅用于从完全不同的类别中获取属性。

I have three C# methods that almost perform identically. More specifically there is a large amount of code repetition but at the end, they perform different functions.

This is obviously very inefficient, so what's the best way to cut down on code duplication? Should I place it all in one method and use a switch & enum for the different functionality at the end? Alternatively, is there some kind of way you can have 3 separate classes and inherit the shared bit from another? I've done a fair bit of reading about this and from what I can gather, this is only used to gain properties from a whole different class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

柏拉图鍀咏恒 2024-10-12 14:51:35

如果没有看到代码,很难给出具体的示例,但听起来您想将委托实例传递到方法中

Without seeing the code its hard to give a concrete example, but it sounds like you want to pass a delegate instance into the method.

仄言 2024-10-12 14:51:35

从我的角度来看,你应该坐下来,拿着一张纸和一支笔。画出你的方法执行的每一个功能。请记住,函数/方法应该做且仅做一件事

在分解每一项功能后,您将开始看到重复的事情,这些应该被分组在一个功能中。

From my point of view you should sit down with a piece of paper and a pen. Draw out every piece of functionality your methods perform. Remember that a function/method should do one and only one thing.

After you brake down every piece of functionality you will start to see things that are repeated, these should be grouped together in one function.

温柔戏命师 2024-10-12 14:51:35

我有三个 C# 方法,主要是
做相同的事情。有很多
代码重复但最后,他们
两者执行不同的功能。

通过阅读这一行,我认为您的三种方法根据一些不同的场景有不同的实现。

所以我建议看一次策略模式,这可能会有用。 查看此处

I have three C# methods that largely
do identical things. There is much
code repetition but at the end, they
both perform different functions.

by reading this line , i am thinking your three methods are having different implementation based upon some different scenarios.

so i would suggest to see Stratgey Pattern once which may be of useful. See here

半衬遮猫 2024-10-12 14:51:35

这是一个好兆头,表明它让你烦恼。

这显然是非常低效的

低效率(一点额外的内存使用)是当今最不重要的部分。至关重要的是,这是一场维护噩梦。例如,如果您在例程中发现错误并修复它,您也需要记住修复重复的代码。您肯定希望尽可能剔除重复的代码。

或者,是否有某种方法可以拥有 3 个独立的类并从另一个类继承共享位?我已经阅读了相当多的相关内容,并且根据我所能收集到的信息,这仅用于从完全不同的类中获取属性。

子类可以直接访问其超类的所有公共成员和受保护成员。例如,如果您有一个带有 Poop() 方法的 Animal 类,则 Dog 和 Cat 子类可以共享该便便代码。

但是剥这只猫的皮有很多的方法。如果没有更多细节,很难说什么是最好的。

It's a good sign that it bugs you.

This is obviously very inefficient

The inefficiency (a little extra memory usage) is the least important part these days. What's crucuial is that it's a maintainence nightmare. For instance, if you find a bug in the routine and fix it, you need to remember to fix the duplicate code, too. You definitely want to factor out duplicate code when you can.

Alternatively, is there some kind of way you can have 3 separate classes and inherit the shared bit from another? I've done a fair bit of reading about this and from what I can gather, this is only used to gain properties from a whole different class.

A subclass can directly access all public and protected members of it's superclass. For instance, if you had an Animal class with a Poop() method, Dog and Cat subclasses could share that pooping code.

But there are a lot of ways of skinning this cat. Hard to say what's best without more detail.

雨落□心尘 2024-10-12 14:51:35

你能做如下的事情吗:

    public void MethodBase()
    {
        Console.WriteLine("1");
        Console.WriteLine("2");
        Console.WriteLine("3");
        Console.WriteLine("4");
        Console.WriteLine("5");
    }

    public void Method1()
    {
        MethodBase();
        Console.WriteLine("Method 1");
    }

    public void Method2()
    {
        MethodBase();
        Console.WriteLine("Method 2");
    }

    public void Method3()
    {
        MethodBase();
        Console.WriteLine("Method 3");
    }

Can you do something like the following :

    public void MethodBase()
    {
        Console.WriteLine("1");
        Console.WriteLine("2");
        Console.WriteLine("3");
        Console.WriteLine("4");
        Console.WriteLine("5");
    }

    public void Method1()
    {
        MethodBase();
        Console.WriteLine("Method 1");
    }

    public void Method2()
    {
        MethodBase();
        Console.WriteLine("Method 2");
    }

    public void Method3()
    {
        MethodBase();
        Console.WriteLine("Method 3");
    }
旧街凉风 2024-10-12 14:51:35

没有适用于所有情况的解决方案,请向我们展示代码。

问题在于,当您将代码放入一个函数并在内部某处切换一小部分行为时,就会增加代码的复杂性,有时保留一些重复的代码比保留一些重复的代码更好。

几乎相同的论点也适用于继承。您可以轻松地将公共代码填充到公共祖先类中,但如果您开始定期使用继承作为代码重用工具,您的设计可能会陷入痛苦的世界。继承意味着一段代码中的代码可以影响其他代码段中的行为,在您意识到之前,您将拥有一个相互链接的代码球,几乎不可能在不破坏的情况下进行更改。

当您可以从这三个函数中提取或抽象出代码中一些有意义的公共部分时,通常是最好的。一些有意义的东西,比如高级模式,而不是一些没有连贯性的通用线。一个可能对您有帮助的简单规则是命名提取的代码:是否有一种明显、自然的方式来命名块?它显然适合你的一门课吗?如果确实如此,这可能是一个很好的解决方案。如果你很难给它命名,而且它几乎可以放在任何地方,你可能需要多考虑一下。

There is no solution that would work in all cases, show us the code.

The problem is that when you put the code into one function and switch a little part of the behaviour somewhere inside, you raise the code complexity, and sometimes it’s better to keep some duplicated code than that.

Almost the same argument works for inheritance. You can easily stuff the common code into a common ancestor class, but if you start routinely use inheritance as a code-reuse tool, your design may slip into a world of pain. Inheritance means that code in one piece of code can affect behaviour in other pieces of code and before you know it, you will have an interlinked ball of code that’s almost impossible to change without breaking.

It’s usually best when you can extract or abstract some meaningful common part of the code from those three functions. Something that makes sense, like a high-level pattern, instead of just a few common lines that do no coherent work. A simple rule that may help you is naming the extracted code: Is there an obvious, natural way to name the chunk? Does it obviously fit into one of your classes? If it does, it might be a good solution. If you have hard time naming it and it could go pretty much anywhere, you might want to think a bit more.

栖迟 2024-10-12 14:51:35

您可以尝试通过使其成为高阶函数或泛型函数来概括该方法。我想到的其他方法是设计模式,例如模板方法,它允许您定义算法的骨架,并让子类重新定义某些步骤。

You can try to generalize the method by making it a higher-order or a generic function. Other approaches that comes to mind are design patterns like Template method which lets you define the skeleton of the algorithm, and let subclasses redefine certain steps.

可是我不能没有你 2024-10-12 14:51:35
public MyCustomObject MethodBase(MyCustomObject myObj) 
{ 
    myObj.Name="FixedName";
    myObj.Surname="FixedSurname";
    myObj.Type = Types.Human;
    return myObj;
} 


public MyCustomObject SetOld(MyCustomObject  myObj) 
{ 
    MethodBase(); 
    myObj.IsOld = True;
    return myObj;
} 

public MyCustomObject SetYoung(MyCustomObject myObj) 
{ 
    MethodBase(); 
    myObj.IsOld = False;
    return myObj;
} 

public MyCustomObject SetIsDead(MyCustomObject myObj) 
{ 
    MethodBase(); 
    myObj.IsDead = True;
    return myObj;
} 
public void MainMethod(enum OperationType)
{
    MyCustomObject myObj = new MyCustomObject();
    switch(OperationType)
    {
        case OperationTypes.Old:
            myObj = SetOld(myObj);
            break;
        case OperationTypes.Young:
            myObj = SetYoung(myObj);
            break;
        case OperationTypes.Dead:
            myObj = SetDead(myObj);
            break;
    }
}
public MyCustomObject MethodBase(MyCustomObject myObj) 
{ 
    myObj.Name="FixedName";
    myObj.Surname="FixedSurname";
    myObj.Type = Types.Human;
    return myObj;
} 


public MyCustomObject SetOld(MyCustomObject  myObj) 
{ 
    MethodBase(); 
    myObj.IsOld = True;
    return myObj;
} 

public MyCustomObject SetYoung(MyCustomObject myObj) 
{ 
    MethodBase(); 
    myObj.IsOld = False;
    return myObj;
} 

public MyCustomObject SetIsDead(MyCustomObject myObj) 
{ 
    MethodBase(); 
    myObj.IsDead = True;
    return myObj;
} 
public void MainMethod(enum OperationType)
{
    MyCustomObject myObj = new MyCustomObject();
    switch(OperationType)
    {
        case OperationTypes.Old:
            myObj = SetOld(myObj);
            break;
        case OperationTypes.Young:
            myObj = SetYoung(myObj);
            break;
        case OperationTypes.Dead:
            myObj = SetDead(myObj);
            break;
    }
}
不羁少年 2024-10-12 14:51:35

没有人提到 lambda 函数,它们是 .NET 3.5 开发人员必须了解的:

public MyCustomObject SetYoung(MyCustomObject myObj) 
{ 
    GeneralMethod(myObj => myObj.IsOld = False);
    return myObj;
} 

public void GeneralMethod(Func<TSourceObjectType,TResultObjectType> func)
{
    MyCustomObject myObj = new MyCustomObject(); // MyCustomObject implements 'TSourceObjectType'
    TResultObjectType res = func(myObj);
}

Nobody mentioned lambda-functions, they are must to know for .NET 3.5 developers:

public MyCustomObject SetYoung(MyCustomObject myObj) 
{ 
    GeneralMethod(myObj => myObj.IsOld = False);
    return myObj;
} 

public void GeneralMethod(Func<TSourceObjectType,TResultObjectType> func)
{
    MyCustomObject myObj = new MyCustomObject(); // MyCustomObject implements 'TSourceObjectType'
    TResultObjectType res = func(myObj);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文