eShopOnWeb Architecture (6/16) – uses private setters and non default constructors to support encapsulation which helps keep the model valid

eShopOnWeb has some really nice examples of encapsulation.
The particular example below is the CatalogItem class.

Click on the image for a larger view in a new window…
We can see above that there is an explicit constructor and since C# will only create a default parameterless constructor when no other constructors exist, in this case there is no default constructor. This means instances of CatalogItem cannot be created without passing in all the required parameters such as catalogTypeId, catalogBrandId, description etc. This helps eShopOnWeb ensure that invalid CatalogItems are never created.

We can also see that all the property setters are private meaning consumers of the class can’t update them directly. For consumers to update properties of the CatalogItem class they have to go through methods such as UpdateDetails and UpdateBrand which can contain rules and validations to ensure the domain model is always valid.

Is encapsulation possible when using Entity Framework with the Database first approach?

eShopOnWeb uses the Entity Framework Code First approach which has really good support for encapsulation but FYI… encapsulation with the DB First approach is possible too. To support this we need to customise the generated models to have private properties and constructors and use partial classes to expose public constructors and public update methods.

One thought on “eShopOnWeb Architecture (6/16) – uses private setters and non default constructors to support encapsulation which helps keep the model valid”

Leave a Reply

Your email address will not be published. Required fields are marked *