Constraints for input values

You recognised some flaws in the entity implementation in the previous section. There are quite a few of them at the moment, but let's look at the most obvious one. What is surely missing here, is the owner id. It is hard to believe we can allow having ads without anyone owning them. How in this case will be understood, who can modify the content of such ads? Plus, we already have the _ownerId field in this class. So, let's add one more parameter to the constructor to enforce this constraint.

From this moment on, we will not list the whole class, but just a part of it that is being changed.
public ClassifiedAd(Guid id, Guid ownerId)
{
if (id == default)
throw new ArgumentException(
"Identity must be specified", nameof(id));

if (ownerId == default)
throw new ArgumentException(
"Owner id must be specified", nameof(ownerId));

Id = id;
_ownerId = ownerId;
}

We have not only added one more parameter but also added one more check. So now our entity is guaranteed to be valid after it is created since the client must supply both the ad id and the owner id.

The code that creates a classified ad entity would look like this:

public void CreateClassifiedAd(Guid id, Guid ownerId)
{
var classifiedAd = new ClassifiedAd(id, ownerId);

// store the entity somehow
}

Notice that we are adding more parameters to the entity constructor and the constructor itself grows since we add more checks for these parameters. In the end, it is not very easy to understand what is going on because many rules are mixed in one large chunk of code. Also, it is quite evident that we are not checking core complex rules, which involve multiple properties of the entity. In our case, all we control is that each parameter has a value. This approach is not wrong but is also not ideal. Instead, we can check the validity of such values even before reaching the entity constructor, using value objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.130.199