Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is no specific correct answer. The design should always be in context of your problem domain and business context. So here are various options</p> <p><strong>Option 1</strong> Person class has a vailidate() method that you can call to perform all he validations on its current state.</p> <p>Pros</p> <ul> <li>better encapsulation</li> <li>changes are localized to 1 single class</li> <li>validation is performed after setting all the properties</li> </ul> <p>Cons</p> <ul> <li>Person might be in invalid state before the validate() method is called hence no fail fast</li> <li>Can't have different validation rules for different context</li> </ul> <p><strong>Option 2</strong> Each property has its own validateXXX() method in the Person class. Each setXXX() method is going to call corresponding validateXXX() method.</p> <p>Pros</p> <ul> <li>better encapsulation</li> <li>changes are localized to 1 single class</li> <li>Fail fast behavior i.e. Person object will never be an invalid state</li> </ul> <p>Cons</p> <ul> <li>might be overkill based on the context</li> <li>Can't have different validation rules for different context</li> </ul> <p><strong>Option 3</strong> You could have a PersonBuilder that contains these validation checks. The builder will perfrom these validations before it builds the Person object. This way once the Person object is built, it satisfies all the validations and invariants.</p> <p>Pros</p> <ul> <li>You have externalized the validations to a builder class hence you can have different validation rules for different contexts</li> <li>Construnction logic is separated from the domain object</li> <li>Person class can be made immutable once constructed</li> </ul> <p>Cons</p> <ul> <li>Might be a overkill in some scenarios</li> </ul> <hr> <p>Your option 2 is not correct because ValidatePersonAge IS NOT same as ValidatePerson. You are not validating the person entirely but only validating his age. So they are semantically different. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload