0

Suppose there is an entity class A like so:

class A {
    public Id { get; private set; }
}

There is also another entity class B which holds a reference to A:

class B {
    public Id { get; private set; }
    public aId { get; private set; }
}

Do guidelines on setting the visibility of ID references to other entities and aggregate roots, such as aId in the example above, exist?

Making the entity Id public with private setter seems common practice, but does it imply that making references to other Id fields public is also prefered? Does a situation exist where such an approach might cause problems?

1

Well in the case of A.Id, if something makes that value be defined only after B object exists, you won't be able to set it.

So:

  • If A object always must exist within B since the very start of B's life and won't change, you can go for a private setter.
  • If A object may be set after or change within B's life, either keep the private setter and use another method to set the value (and perform some checks eventually) or let the setter be public.

For A.Id field, it will exist since the very start of A's life if you fetch it from your database. However if you're storing in database a new A which doesn't have his Id yet (it will be set by database), you will need to refetch the A created and return it to the upper method so it can use A.Id. Or you need to be able to set A.Id.

If you really want to enforce something, that would be either Id be null or, if it's set, you can't change it anymore. For A.Id it depends on the domain's needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.