Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Categories or Partial Classes: Pattern to Resolve "God Object" Code Smell?

A class is too large and becomes unwieldy to work with. In Objective-C I'd be tempted to use Categories to break the class up, but then: wouldn't categories just be dividing a house full of too much junk into rooms? The same question applies to partial classes in C#, I suppose.

Under what conditions can categories be used to solve a "class too large" code smell? When is it not correct and the class really needs to "be restructured or broken into smaller classes?"

like image 721
Dan Rosenstark Avatar asked Dec 27 '22 11:12

Dan Rosenstark


2 Answers

A very good principle to refer to is the SOLID principle. In particular the "S" stands for "Single responsibility"

Single responsibility principle

the notion that an object should have only a single responsibility.

When classes get too big, it is likely they have too many responsibilities. Can you define two or more responsibilities within the boundaries of what the class is doing? If so, separate it into two, or more, classes. You can then aggregate them back using a façade or composite pattern.

In other words:

  • the code you have in the class should be split in different classes according to the Single Responsibility principle
  • the original God class becomes a composite or façade: it uses all the new classes, exposes the same methods to the rest of the system, but does not implement any functionality in itself, besides "converting" the old-style god-class calls in the new-style SOLID calls.

This means that regions do exactly nothing to solve your problem, from an object-oriented point of view. In fact, they are actually counterproductive as they contribute to hiding the problem.

See also this Jeff Atwood article:

http://www.codinghorror.com/blog/2008/07/the-problem-with-code-folding.html

CodingHorror-regions

like image 162
Sklivvz Avatar answered Feb 20 '23 07:02

Sklivvz


I must admit I never used Objective-C, but of course, I used C#.

Said this, partial classes are the same thing that classes, splitting a class into multiple files doesn't make the class smaller, only splitted in file. The usage of the class will be the same.

So I don't agree partial classes will solve that problem, they were invented mostly for other things, like, windows forms, wpf, autogenerated code. They are useful also in other situations where classes cannot be logically splitted, but usually, should be avoided.

I think you should divide your class in several classes, a class starts to smell after 1k LOC (lines of code), also if the class is splitted in multiple files.

Use inheritance or split the class in several classes connected by fields and properties. In the example provided by chemicalNova i would split that in several classes, not in several files.

like image 39
Salvatore Previti Avatar answered Feb 20 '23 08:02

Salvatore Previti