View Single Post
  #8   Spotlight this post!  
Unread 03-02-2009, 10:06
galewind's Avatar
galewind galewind is offline
... more like a temperate breeze
AKA: Chris Gregory
FRC #1089 (Team Mercury)
Team Role: Teacher
 
Join Date: Jan 2003
Rookie Year: 2003
Location: Hightstown, NJ
Posts: 410
galewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond reputegalewind has a reputation beyond repute
Send a message via AIM to galewind
Re: why encapsulation is required?

Here's an example of why encapsulation is important.

Let us, for a moment, assume that you have variables within an object that are directly related to other variables within that same object. Thus, changing one requires that you adjust others in order to compensate for the change. The object itself should ultimately be responsible for updating itself to make sure that the data correlates accordingly.

Simple example: Assume we made a Rectangle class that contained four variables - length, width, area, perimeter. Please note that area and perimeter are derived from length and width (normally I wouldn't make variables for them), so that changing length would change both area and perimeter.

If you did not use proper information hiding (encapsulation), then another program utilizing that Rectangle class could alter the length without altering the area, and you would have an inconsistent Rectangle. Without encapsulation, it would be possible to create a Rectangle with a length of 1 and a width of 3, and have an area of 32345.

Using encapsulation, we can create a function that, if a program wanted to change the length of the rectangle, that the object would appropriately update its area and perimeter without being inconsistent.

Encapsulation eliminates the possibilities for inconsistency, and shifts the responsibility of staying consistent onto the object itself rather than a program utilizing it.
__________________
Chris G
Advisor, Team Mercury (1089), Hightstown High School

Last edited by galewind : 03-02-2009 at 10:10. Reason: clarifications