Encapsulation – encapsulate what varies !!


Encapsulation is breaking your application into different logical parts and then keeping those parts separate.

Anytime you have behavior in an application that you think is likely to change, you want to move that behavior away from other parts of application that probably wont change very frequently. In other words, we should always try to encapsulate what varies.

By encapsulating the things, you make your application flexible and easier to change. Lets take an example :

Suppose we have a class ‘Guitar’ as below :

Guitar Class

As we can see from the above fig, serialNumber and Price as unique to each guitar. These two attributes will always be there for each guitar. But the other group of attributes like type,model,builder etc. may change in the future. So there may be some new attribute like manufacture will get added into this group. So what we can do is separate this group from the main Guitar class into new class as ‘GuitarSpecs’ as shown below.

While doing so we will add GuitarSpec type into the main Guitar class, as shown in the fig below.

GuitarSpecs Class

So in future if there is any changes/additions in the Guitar specs, its very easy to change the GuitarSpec class without affecting anything in the main Guitar class.

Hope this helps.


Author: Bhimraj Ghadge

Passionate about everything related Microsoft technologies, particularly ASP.net and SQL server..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s