3 ms·
I'd argue against using abstract classes in general (just use interfaces) and stuffing logic in domain classes. Domain classes should be simple, not contain any
by jillesvangurp 8y ago
I'd argue against using abstract classes in general (just use interfaces) and stuffing logic in domain classes. Domain classes should be simple, not contain any algorithms or logic, and preferably be immutable. If you are putting ifs in domain classes you are doing it wrong. If you are moving logic from service classes to domain classes, you are no longer separating concerns.
If you have sixteen polymorphic methods in one service class (which is of course possible), maybe using a switch statement would actually be a bit shorter and easier on the eyes. It depends. I think about this in terms of unit tests and code paths. More ifs means more paths. Units with lots of code paths are complex and hard to test. On the other hand having code paths cross many classes and methods just moves the problem. It's a tradeoff. A few other tricks you can apply here is using enums with e.g. lambdas and other feature flags. That's a nice way to tie functionality to types or associate some default functionality with domain classes without littering them with logic.
Not using abstract classes is somewhat controversial for some but I have disliked them for quite long and find I don't need them and can trivially refactor them away whenever I encounter them in an codebase. Preferring delegation over inheritance is a good thing IMHO and using inheritance generally is something I end up regretting. I find framework code (Spring, cough) that uses abstract classes to be mostly unreadable and convoluted. You have a Thingy that is also an AbstractThingy that inherits an EvenMoreAbstractThingy that implements a gazillion interfaces that are also implemented by other thingies and yet more AbstractClasses, etc. If you have to control click through six classes to actually get to a place that actually has logic, something is deeply wrong. Deep inheritance hierarchies are a good sign your type system is struggling with your abstractions and sets you up for maintenance problems when the cohesiveness of your classes drops and coupling increases as you are forced to add stuff in places where it really shouldn't be for API compatibility reasons.