jeudi 17 septembre 2015

Readonly nested object properties

I'm having a problem defining these 2 classes:

public class Article
{
    public Article(long ID, string Name, ArticleFamily Family)
    {
        //...Initializer...
    }
    public ArticleFamily Family { get; set; }
    //Other props...
}

public class ArticleFamily
{
    public ArticleFamily(int ID, string Description)
    {
        //...Initializer...
    }
    public int ID { get; private set; }
    public string Description { get; set; }
}

I have a collection of Article and each one belongs to a family.
Now, given that I have a certain ArticleFamily object I should be able to change its Description and it gets eventually persisted to a DataBase. (I left out that part for simplicity)
But I should not be able to do this:

Article art = SomeMethodReturningArticle();
art.Family.Description = "SomeOtherValue";

I should be able to change the Family of an Article entirely, replacing it with a new ArticleFamily object, but I shouldn't be able to change just the description.
Should I create a copy of the ArticleFamily class with readonly properties like this:

public class ArticleFamilyReadonly
{
    ArticleFamily _family;
    public ArticleFamilyReadonly(ArticleFamily Family)
    {
        _family = Family;
    }
    public int ID { get { return _family.ID; } }
    //etc...
}

How can I do this in a clean way?

Aucun commentaire:

Enregistrer un commentaire