Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes Design Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Design Question" Watch "Design Question" New topic

Design Question

jay vas
Ranch Hand

Joined: Aug 30, 2005
Posts: 407
Hi guys :

A Co-worker had an interesting oo question for me today .

We have wrappers to a legacy application, and the wrappers have to (typically) generate a single file with a bunch of points in it.

x y
1 10
2 20
3 36
3 36
4 45

But then, the particular app has to generate (in certain scenarios) a file with an extra column, where each "point" (call it Pi) has an additional number (n_Pi) next to it.

1 10 1
2 20 1
3 36 2
3 36 2
4 45 1

Where n = #of repeats of Pi in the whole file ...

So we have an class which behaves in two different ways, the second behavior, as you might imagine, is a corner case which we hope will dissapear someday ...

Now of course, the OO Purist would use a perfect hierarchy / interface strategy to cleanly implement this, but we want an API that is uncluttered and maximally useful (that is , we don't want a new object type for every corner case).

So we were shooting some ideas around, for example :

- Hide both file export objects behind a common factory for creating the file exporter, so that the API only exposes two, simply named methods.
- Have an enum arg in the constructor, so that any use of the object for exporting has to explicitly decide which of the two file export types are desired.
- Add a method to the class which was something like (appendPointReplicaCountToLastColumn()) <- this is a bad, statefull solution which i think should be avoided.
- etc etc etc

Any thoughts on this ? In general, any thoughts on the best way to model and object which has two very similar behaviors ? Im wondering wether dependency injection based solutions might come into play here ?
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4629

The first solution seems pretty good. You wouldn't necessarily need two methods though. You could also have just one method, and let it return an instance of either of the two classes (which both implement the same interface; the second case can easily extend the first one).

If the situation is simple enough, you can even just make this a single factory method in the base export class (which could then return an instance of a subclass, if needed).

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: Design Question
It's not a secret anymore!