What OO Design to use ( is there a Design Pattern )?

Posted by Blundell on Programmers See other posts from Programmers or by Blundell
Published on 2012-07-05T21:31:22Z Indexed on 2012/07/06 3:23 UTC
Read the original article Hit count: 166

I have two objects that represent a 'Bar/Club' ( a place where you drink/socialise).

In one scenario I need the bar name, address, distance, slogon

In another scenario I need the bar name, address, website url, logo

So I've got two objects representing the same thing but with different fields.

I like to use immutable objects, so all the fields are set from the constructor.

One option is to have two constructors and null the other fields i.e:

class Bar {
     private final String name;
     private final Distance distance;
     private final Url url;

     public Bar(String name, Distance distance){
          this.name = name;
          this.distance = distance;
          this.url = null;
     }

     public Bar(String name, Url url){
          this.name = name;
          this.distance = null;
          this.url = url;
     }

     // getters
}

I don't like this as you would have to null check when you use the getters

In my real example the first scenario has 3 fields and the second scenario has about 10, so it would be a real pain having two constructors, the amount of fields I would have to declare null and then when the object are in use you wouldn't know which Bar you where using and so what fields would be null and what wouldn't.

What other options do I have?

Two classes called BarPreview and Bar?

Some type of inheritance / interface?

Something else that is awesome?

© Programmers or respective owner

Related posts about java

Related posts about design-patterns