tags:

views:

54

answers:

2

I have a list of nullable integer and it look like a 1 to many relation

 id1 can have an id2 and id3
 id2 can have id4

if the value of id1 change, id2 and id3 must be set to null and it mean id4 must be set to null

In that example, I only use 4 variables so that easy to manage.

I got, for now, at least 15 variables to manage.

The way I'm thinking of doing it for now is within the "set" property checking if the value change and if it's the case, setting the child value to null. This is going to be a nightmare later on if the relation change and a nightmare for maintenance.

Is there an easier/better way than what I just said?

A: 

Here's what I think you have now:

public class Ids
{
    public int? Id1
    {
        get { return _id1; }
        set
        {
            if (_id1 != value)
            {
                _id1 = value;
                Id2 = null;
                Id3 = null;
            }
        }
    }

    public int? Id2
    {
        get { return _id2; }
        set
        {
            if (_id2 != value)
            {
                _id2 = value;
                Id4 = null;
            }
        }
    }

    public int? Id3 { get; set; }
    public int? Id4 { get; set; }

    private int? _id1;
    private int? _id2;
}

And here's one alternative:

public class Id
{
    public Id(int? value)
    {
        _value = value;
    }

    public void AddChild(Id child)
    {
        _children.Add(child);
    }

    public IEnumerable<Id> Children
    {
        get { return _children; }
    }

    public int? Value
    {
        get { return _value; }
        set
        {
            if (_value != value)
            {
                _value = value;

                foreach (Id id in Children)
                {
                    id.Value = null;
                }
            }
        }
    }

    public override string ToString()
    {
        return Value.ToString();
    }

    private readonly List<Id> _children = new List<Id>();
    private int? _value;
}

Used as follows:

var id1 = new Id(1);
var id2 = new Id(2);
var id3 = new Id(3);
var id4 = new Id(4);

id1.AddChild(id2);
id1.AddChild(id3);

id2.AddChild(id4);

Note that you can add these to a generic List<Id>.

I did only basic testing on this, and there are many alternatives (as well as ways to provide syntactic sugar for easier initialization). Perhaps others will suggest better designs; hopefully this describes your problem accurately.

EDIT: This is an attempt to answer the question as asked; however, it would help to have more context on the problem you are trying to solve. For instance, what do the nullable IDs represent, and why is one ID a child of another? Is there a database involved?

TrueWill
+1  A: 

You might consider using INotifyPropertyChanged and add handlers for when values change. That way, you can put all of your logic in one place.

Brian Genisio