It’s tricky trying to come up with a meaningful question title for this. I’ll explain exactly what I’m trying to do.
I have created an Android graphics library that builds a potentially large list of Path objects. I now have a need to attach some additional data to each Path. To do this, I have simply subclassed Path (call it PathSubclass) to provide the additional extended data fields. In general use cases, only very few of those Path objects will actually have extra data set on them. For example, there could be an ArrayList of several thousand Paths, but only a handful have additional data. As I develop the library, it is possible that the amount of extra data I want to attach to each Path will grow considerably. I appreciate this may be premature optimisation, but I am concerned that it is not efficient to subclass an object to contain some additional data when that additional data is very rarely populated and considerably large collections of that object are used.
What I thought of doing was perhaps having an ExtendedPathData class, separate from my Path subclass. Therefore each Path subclass is only bloated a little by the need for a mExtendedData member, which in many cases will be null, except for those very few Path objects that require the additional data. I suppose this is similar to how one would usually attach additional data to a View, using the setTag() method.
Is there any other approach I should consider, that is better for any reason?
You could use composition instead of inheritance.
Idea 1
A
PathDataclass might contain a reference to aPathand aExtendedPathData:This enables you to set the
datamember tonull. EachPathDatainstance has a size of constantly two references. When the number of members inExtendedPathDatagrows, the actual memory consumption grows only forPathDatainstances that have a non-nulldata.Idea 2
You could shave off one more reference by using an interface with two implementations:
It’s up to you to decide whether having two implementations is really worth the code, as you need a factory method here to decide what implementation to use. It’s one 4-byte-reference per instance…
Further stuff
If
ExtendedPathDatais immutable and many equal instances may exist, you could also pool them by exposing a static factory method that uses an instance pool instead of a public constructor.In case you’ve got Effective Java by Joshua Bloch, here are further references explaining the tips in detail (in a more general context):