Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A refactoring question.

 
Qunfeng Wang
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ManagedObject is a class provided by a framework. Our own classes all inherit from this class. The framework also provides some API to retreive ManagedObject from database. We have kinds of childrens of ManagedObject. But we only get their parent reference via the framework's API. We add a group attribute to all the children classes. When we want to get this attribute, the code like this:

We do the downcast only to get the group attribute! We haven't the privilege to modify the ManagedObject to add this attribute. How to eliminate these if-else in this situation?

Thanks.
 
Peer Reynders
Bartender
Posts: 2968
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the creational context automatically implies a certain descendent, segregate the creational methods (automatically downcasting) and then only use the segregated versions.

Be as general as you can but no more general than useful.
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use composition instead of inheritance.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Introduce an interface



Let both ChildA and ChildB implement that interface. That way, you can simply cast the ManagedObject to the Grouped interface - no need for the instanceof test.
 
Peer Reynders
Bartender
Posts: 2968
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
Introduce an interface


The Interface Segregation Principle (ISP) in action ...
Clients Should Not Be Forced To Depend Upon Interfaces That They Do Not Use

Neither ChildA or ChildB added anything of value other than the methods they had in common - so that interface needed to be extracted.
Good catch.
[ May 28, 2007: Message edited by: Peer Reynders ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic