Answer the question
In order to leave comments, you need to log in
Does an object always have to be valid?
Hi guys.
Let's say I have a Document entity object in my code that has a RegNumber property, i.e. registration number. The rule is this - the registration number must be of a certain format and be unique for each document. The number can be generated automatically or assigned manually. Consider the case when the user enters a document number into the form and the View passes this number to the Presenter. If the number is malformed or not unique, can the Presenter assign a value to the RegNumber property of the Document object?
I always thought that NO, because the domain object must always be in a valid state, i.e. observe all invariants. If the Document object has some operation, then after its execution, the object must observe invariants, and if it is not valid before the operation is performed, then. and after that too...
More than once I have seen code where objects have the IsValid property, and the GetBrokenMessages() method, which returns messages about broken business rules. It turns out they admit that the object may be in an incorrect state, but how then should operations be performed on the object when it is incorrect?
And how do you read whether an object of the subject area can be in a non-valid state during its life cycle, i.e. breaking invariants?
Answer the question
In order to leave comments, you need to log in
Yes, the question is about Entity and ValueObjects.
I'm writing C# code, but that's not the point... I've already tried to express the registration number in the code through a ValueObject that would validate the input string, and always created a valid one. At first, everything seemed simpler to me, I checked the input string with a regular expression, but this was not enough.
The input string that represented the registration number consists of three parts, the first part is the business line, the second part is the document type and the third part is the serial number, i.e. it is also necessary to check whether the business direction and document type exist, and even the global uniqueness of the number itself. I doubt that ValueObject should deal with all this. a call to the Repository is required.
It can do this: move the Document class into a separate Domain assembly, set the RegNumber property to the internal access modifier so that client code, for example Presenter, cannot directly set values. Introduce the DocumentService domain service and implement the registration number assignment logic in it, here it will just be parsing the string and checking all parts of the number in the database, which will be accessed through the repository?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question