File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

A refactoring question.

Qunfeng Wang
Ranch Hand

Joined: Jan 28, 2005
Posts: 434
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?


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

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

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

Joined: Aug 19, 2005
Posts: 2933
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:
subject: A refactoring question.
It's not a secret anymore!