Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking up a large, cohesive class

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();
    }
}
like image 475
user204588 Avatar asked Feb 28 '11 14:02

user204588


People also ask

What is high cohesion and how is it helpful?

High cohesion is when you have a class that does a well-defined job. Low cohesion is when a class does a lot of jobs that don't have much in common. High cohesion gives us better-maintaining facility and Low cohesion results in monolithic classes that are difficult to maintain, understand and reduce re-usability.

What is a cohesive method?

Method cohesion focuses on the methods you write inside the class. A method should clearly state the intention of why it is written. Otherwise, it is weakly cohesive. More tasks you accumulate within a method, more likely, you do wrong programming.


1 Answers

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...

like image 90
Martin Hennings Avatar answered Sep 19 '22 04:09

Martin Hennings