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.
-
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.
-
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 justself.foo
.
The latter is getting a bit reminiscent of the MVC pattern of course. Is there a clear answer to which method is preferred?
2
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.