views:

105

answers:

1

I am trying to decide among three different implementations.

I have an IPerson interface, all people types (ie. police officer, student, lawyer) implement this. Each person type needs to have a different AddressLocation (ie. home, office, mailing). This location never changes so it can be static/readonly. People are handled generically so my save method SavePerson(IPerson person) takes anything that inherits from the IPerson interface and I have a LoadPerson(int ID) method that takes an ID.

My initial solution was to add a DefaultLocation property to IPerson and only have a getter. This way I can use generic methods to save the data. A problem arises when I try to load the data as I do not have an instance of the class yet so I can not reference the property.

On the other hand I can create a public static readonly DefaultLocation property on each of my people types. In this case I can call Student.DefaultLocation and pass that into the method loading my data.

Which way should I go and why? Both appear to have pros and cons.

A third option came to me as I was typing this question: What if I used a public static readonly proprty which could be referenced without an instantiation of the class and then used a public property without a setter which could be called from the generic methods?

Per Jon's advice I went with:

public interface IPerson
{
    LocationType DefaultLocation { get; }
}

public class PoliceOfficer : IPerson
{
    public static readonly LocationType _DefaultLocationType = LocationType.Office;
    public LocationType { get { return _DefaultLocationType; } }
}
+1  A: 

The last option sounds like the best one to me - at least if you want each type's location to be available to the rest of the code. If you don't, I'd just use a private readonly static field in each type, and return that value from the instance property. (I'm assuming locations are immutable.)

Basically you're using polymorphism here in a slightly unusual way in that it doesn't depend on the state of the particular object or any particular behaviour, but the state in terms of the type. Note that by using a property in the interface rather than having an abstract base class with a field set in the constructor, you avoid having one field per instance with basically redundant data.

Jon Skeet