打破一个大型,凝聚力的阶级 [英] Breaking up a large, cohesive class

查看:107
本文介绍了打破一个大型,凝聚力的阶级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班,我觉得太久了。我真的不知道太长的意思,但它是大约2500行代码。然而,所有的方法都使用至少一个或多个变量,所以我认为它是非常有凝聚力的。我正在考虑将这个类分成几个较小的类,它们将使用三个相同的变量。这是不好的设计还是代表一种模式?

  class MyClass 
{
...
MyVar1 myVar1;
MyVar2 myVar2;

public void DoStuff()
{
...
MyPart1 myPart1 = new MyPart1(this,myVar1,myVar2);
myPart1.DoStuff();

MyPart2 myPart2 = new MyPart2(this,myVar1,myVar2);
myPart2.DoStuff();
}
}


解决方案

你一般来说,2500行代码对于一个类来说太多了。



然而,你可以说一个用于10个不同动作的类是非常单一的。有些人在这里说每个班只应该有一个功能。这些人会读取10作为二进制...



现在,如果你没有看到有机会把你的班级分成两半,可能开始分开小功能部件。这样,您可以更好地了解您的课程功能的真正重要性。



从您的方法开始:如果您的课程有几种基本属于相同的范围(例如,XML-I / O或类似于播放/暂停/停止/重置功能集的功能),您可以为这些创建一个子类。

如果您的所有方法彼此相符(即与上述相反),我会说你的班级不是太大。



最重要的是,你不会失去您的代码中的方向。尝试构建您的类,并按照最合适的顺序排列您的方法。不要忘了评论这个订单,以便您再次轻松进入...


I have a class that I think is too long. I don't really know what too long means but it's about 2500 lines of code. However, all the methods use at least one or more of the variables so I think it's pretty cohesive. I'm thinking of still breaking this class up into a few smaller classes that would use three of the same variables. Is this bad design or does this represent a pattern?

class MyClass
{
    ...
    MyVar1 myVar1;
    MyVar2 myVar2;

    public void DoStuff()
    {
         ...
         MyPart1 myPart1 = new MyPart1(this,myVar1,myVar2);
         myPart1.DoStuff();

         MyPart2 myPart2 = new MyPart2(this,myVar1,myVar2);
         myPart2.DoStuff();
    }
}

解决方案

You can't generally say that 2500 lines of code is too much for one class.

You can however say that a class that gets used for 10 different actions is quite monolithic. Some people here say that each class should only have one functionality. These people would read the "10" as binary...

Now if you don't see a chance to divide your class in half, maybe start by splitting small functional parts off instead. This way you might get a better view for what's really essential to your classes' functionality.

Start with looking at your methods: If your class has several methods that basically belong to the same scope (e.g. XML-I/O or something like a Play/Pause/Stop/Reset function set) you could create a subclass for these.
If all your methods are on a par with each other (i.e. the opposite of the above), I'd say your class is not too big.

The most important thing though is that you don't lose orientation in your code. Try structuring your class and order your methods as seems best fit. And don't forget to comment this order so you'll get into it easily again...

这篇关于打破一个大型,凝聚力的阶级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆