aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes A refactoring question. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "A refactoring question." Watch "A refactoring question." New topic
Author

A refactoring question.

Qunfeng Wang
Ranch Hand

Joined: Jan 28, 2005
Posts: 433
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.


To be or not to be. It's a question.
Peer Reynders
Bartender

Joined: Aug 19, 2005
Posts: 2922
    
    5
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

Joined: Jul 27, 2006
Posts: 131
You could use composition instead of inheritance.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Peer Reynders
Bartender

Joined: Aug 19, 2005
Posts: 2922
    
    5
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A refactoring question.