0

I have a huge class (>1000 lines), in which all methods depend on a small set of attributes in that class. I can think of 2 quick ways of refactoring.

  1. I keep it as a huge object, but split related methods into separate classes from which I inherit (but I don't instantiate those separate classes, only the last one in the inheritance-chain). This probably has the disadvantage that conceptually, my object is still a huge monolith.

  2. I make the common attributes, with a few helper functions, into a separate class. All other code that depends on this common state then are in their own class, but contain the common state through composition. Disadvantage is I end up with a lot of nested lookup calls similar to self.commonState.foo, instead of just self.foo.

The latter is getting a bit reminiscent of the MVC pattern of course. Is there a clear answer to which method is preferred?

p.s.w.g
  • 4,135
  • 4
  • 28
  • 40
funklute
  • 201
  • 2
  • 4
  • ...see also: [When is it suitable to use inheritance](http://programmers.stackexchange.com/q/234881/31260) and questions linked to it – gnat Jan 24 '15 at 13:43
  • I have to say that I would ***burn the [Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter)***. *(Read the disadvantages to see why.)* – rwong Jan 24 '15 at 14:21

1 Answers1

0

It is difficult to tell without having more conetxt information on what the class does, but I faced the same problem once and I took the composition approach to refactoring.

The first approach looks like the decorator pattern to me. Depending of what the nature of your class is, it could be a good solution but without knowing much more I can't tell.

Back again to what I did: In my case I had a very big "Report" class that read from a database and formatted the data in a tab separated fashion, applying formats to dates and numbers. I refactored uit sing composition, by separating all format information and operations into a separate class exactly like you propose and injected that "Format" class into the "Report" class. I managed to reduce the size of the original class dramatically but with a lot of what you call "nested lookup calls".

Being pragmatic, and since the composition approach worked for me, I can tell you it's a safe way to go. But I also suggest you read about the decorator pattern to see if it suits you conceptually.

Tulains Córdova
  • 39,201
  • 12
  • 97
  • 154