Handling Collection Properties in NHibernate Classes and Objects

I was wondering what is the recommended way to open a collection inside a class, and if it is different from the way to do the same when working with NHibernate objects.

Let me explain ... I have never had any special problems with my classes displaying collection properties, such as:

IList<SomeObjType> MyProperty { get; set; }

Having setter as protected or private gives me several times more control over how I want to handle the collection. I recently came across this article by Davy Brion:

http://davybrion.com/blog/2009/10/stop-exposing-collections-already/

Davy explicitly recommends having collections as IEnumerables, rather than allowing lists to be used to prevent users from being able to directly manipulate the contents of these collections. I can understand his point of view, but I'm not completely convinced, and, reading the comments on his post, I am not the only one.

When it comes to NHibernate entities, it makes sense to hide collections as it suggests, especially when cascades are in place. I want to have full control over the entity that is in the session and its collections, and also identifying AddXxx and RemoveXxx for collection properties makes much more sense to me.

The problem is how to do this?

IEnumerables, / , , ToList(), , , - .

, (add.remove elements) , , , .

.

+3
3

...

private IList<string> _mappedProperty;

public IEnumerable<string> ExposedProperty
{
    get { return _mappedProperty.AsEnumerable<string>(); }
}

public void Add(string value)
{
    // Apply business rules, raise events, queue message, etc.
    _mappedProperty.Add(value);
}

, NHibernate , . _mappedProperty. .

, . , , , ORM.

+7

ReadOnlyCollection?

IList<SomeObjType> _mappedProperty;

return new ReadOnlyCollection<SomeObjType> ExposedProperty
{
  get
  {
    return new ReadOnlyCollection(_mappedProperty);
  }
}
0

NHibernate, ISet .

ISet<SomeObjType> MyProperty { get; protected set; }

AddXxx RemoveXxx , . . , , .

Basically, I saw if I follow the principle of "Report, don't ask" in my client code without worrying too much about forcibly restricting access to my domain object properties, then I always get a good design.

0
source

Source: https://habr.com/ru/post/1723906/


All Articles