views:

175

answers:

4

I have a class EqualCondition which implements my own interface ICondition, which has only one method: SatisfiedBy(Something).

public class EqualCondition : ICondition {
    private Something m_Something;

    public HelloCondition(Something something) {
        m_Something = something;
    }

    // Magic!!!
    public bool SatisfiedBy(Something something) {
        return something == m_Something;
    }
}

So ICondition is very simple to implement. Now I'm trying to create a CombinationCondition which also implements it. The idea is that CombinationCondition which will contain a list of IConditions which will determine whether SatisfiedBy will be successful or not.

My first thought was to make CombinationCondition implement IList<Something> but I quickly realized that I was only duplicating List<Something>. So why not just subclass it?

That idea sounded fine until I started thinking again about how to implement SatisfiedBy if I just subclassed List<Something>. I need to do:

return innerList.All(x => x.SatisfiedBy(something))

But how do I access the inner list?

+5  A: 

Personally, for the use case you're showing, I would just make this implement IEnumerable<Condition>. You could then just implement the GetEnumerator by calling the (internal, encapsulated) List<Condition>'s method.

Potentially, ICollection<Condition> may make more sense (so you can add conditions at runtime), but only if you need that capability. Implementing IList<T> seems like overkill in this situation, for the use cases I'd see with this.

Reed Copsey
A: 

I'm not sure I 100% understand what you are trying to do, but would this solve your need?

public interface ICondition<T>
{
   bool SatisfiedBy(T something);
}

That way, you can just implement it for any generic type you need

Joel Martinez
he already has that
RCIX
no he doesn't ... at least not based on the information provided in the question ;-)
Joel Martinez
A: 

One possibility would be a property of type IList<ICondition> called maybe "Conditions".

You don't need to access the inner list - you could access your class "itself".

However, prefer sublassing from ICollection<T>.

winSharp93
+1  A: 

From what you have posted, I would just have CombinationCondition contain (encapsulate) a List<Something>. No need for the outside world to know it is a list unless absolutely necessary.

Edit 1:

public class CombinationCondition : ICondition {
private List<ICondition> list;

public CombinationCondition(List<ICondition> list) {
    this.list = list;
}

// if you need it
public void AddCondition( ICondition condition ){
    list.Add( condition );
}

// Still Magic!!!
public bool SatisfiedBy(Something something) {
    return list.Any( x => x.SatisfiedBy( something ) );
}

}

Edit 2:
You might also consider renaming CombinationCondition to CompoundCondition...makes more sense, at least to me :)

BioBuckyBall