views:

50

answers:

2

Say you have an API that is not accessible to change:

List<LegacyObject> getImportantThingFromDatabase(Criteria c);

Imaging Legacy Object has a ton of fields and you want to extend it to make getting at certain information easier:

class ImprovedLegacyObject extends LegacyObject {
   String getSomeFieldThatUsuallyRequiresIteratorsAndAllSortsOfCrap() {
       //cool code that makes things easier goes here
   }
}

However, you can't just cast to your ImprovedLegacyObject, even though the fields are all the same and you haven't changed any of the underlying code, you've only added to it so that code that uses LegacyObject still works, but new code is easier to write.

Is it possible to have some easy way to convert LegacyObject to ImprovedLegacyObject without recreating all of the fields, or accessors? It should be a fast opperation too, I konw you could perform something by using reflections to copy all properties, but I don't think that would be fast enough when doing so to masses of LegacyObjects

EDIT: Is there anything you could do with static methods? To decorate an existing object?

+1  A: 

How about making a copy constructor for your Improved Legacy Object that takes a Legacy Object as an argument. Then just create new objects from the old ones.

Zak
the copy constructor would manually assign each property of the old object to the new one? Could you add just a tiny snippit of psuedo?
walnutmon
+1  A: 

You would have to perform the copying yourself. You can either have a constructor that does this (called a copy constructor):

public ImprovedLegacyObject(LegacyObject legacyObject) {        
  ...
  //copy stuff over

  this.someField = legacyObject.getSomeField();
  this.anotherField = legacyObject.getAnotherField();
  ...
}

or you can have a static factory method that returns an ImprovedLegacyObject

public static ImprovedLegacyObject create(LegacyObject legacyObject) {
  ...
  //copy stuff over
  ...
  return improvedLegacyObject;
}

If you're planning on extending this behavior to other legacy objects, then you should create an interface

public interface CoolNewCodeInterface {

   public String getSomeFieldThatUsuallyRequiresIteratorsAndAllSortsOfCrap() {

   }

   public String getSomeFieldInAReallyCoolWay() {

   }
}

Then your ImprovedLegacyObject would look like this:

public ImprovedLegacyObject extends LegacyObject implements CoolNewCodeInterface {

  //implement methods from interface
}
Vivin Paliath
Yeah, I figured this may be my only way to do it :o. I was trying to avoid this because of laziness... But it would be cool of Java had a way to do this without having to create extra objects and perform a write to all properties. If nobody else comes up with something better I'll accept this
walnutmon