Search code examples
c#objective-cdesign-patternsgod-object

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?"


Solution

  • 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
    (source: typepad.com)