Saturday 22 June 2013

Self Encapsulation

What is Self Encapsulation?

Martin Fowler mentioned this in his bliki :

"Self Encapsulation is designing your classes so that all access to data, even from within the same class, goes through accessor methods."

This is also called Self Delegation. Take this simple Email example:

public final class Email implements Serializable { private static final long serialVersionUID = 1L; private String emailAddress; public Email(String anEmailAddress) { super(); this.setEmailAddress(anEmailAddress); } public Email(Email anEmail) { this(anEmail.getEmailAddress()); } public String getEmailAddress() { return this.emailAddress; } private void setEmailAddress(String anEmailAddress) { if(anEmailAddress == null) { throw new IllegalArgumentException ("Email address must not be null."); } if(anEmailAddress.length() == 0) { throw new IllegalArgumentException ("Email address is required."); } if(!java.util.regex.Pattern.matches( "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", anEmailAddress)){ throw new IllegalArgumentException ("Email address format is invalid."); this.emailAddress = anEmailAddress; } }

In above example, constructor is delegating instance variable, emailAddress assignment to its own internal property setter. Here the setter method is not only setting the email address, but also performing an important assertion. It is providing a guard against invalid data. The self-encapsulation enables the setter method to determine the appropriate contractual condition for setting the email address. This is the advantage of using Self Encapsulation.



References
1. http://martinfowler.com/bliki/SelfEncapsulation.html
2. Implementing Domain-Driven Design - Vaughn Vernon

No comments:

Post a Comment