Encapsulation - Principles of Object Oriented Design

Uploaded by AgileJStructureViews on 21.01.2010

hi, I'm Paul Wells from AgileJ
what is it
and what problems does it solve?
well, the main three problems that I can think of are...
one, without encapsulation
all of your code
has access to
all of its data
now that's fine for a small
but as things get larger
what happens is if you find that in the data
there's a value which you weren't expecting then
you've got no choice but to check
all of the code to find that which piece of code
altered the data
to the value that you weren't expecting
that's the first problem
the second problem is to do with
making alterations to the data structure
if you plan your
project very carefully
you do a thorough analysis
and you come up with a data structure
the models exactly what you want
and you carefully write the code
around that data structure
then you'll be fine
but the problem is
in the real world it doesn't tend to happen that way
one, you won't get it right
first time
and two,
the chances are that the requirements will change anyway
so when you do make alterations to your data structure
every time
you alter the data structure
you have to check
all of the code
to make sure
that code,
which was built
around the assumptions of a particular data structure
haven't been broken
by the changes to the data structure
and the third problem
is to do with reuse.
if you write code
around a data structure - around a central data structure
whenever you try to move that code
to a new program; whenever you try to reuse it
unless you're very careful
what you find is the piece of code
which you want to move
is dependent upon
particular parts of the central data structure
in other words - it's very difficult to reuse of peace of code
without it breaking because
the data structure that it was written around
is no longer there
encapsulation is when instead of having one large central
data area
surrounded by one large
piece of code
you write small pockets
of code
and each of those small pockets of code
has access to
a small area of data
only it
has access to that small
area of data
so that solves the first problem
if you find that your data's got a value in it that you weren't expecting
well now you've only got a small piece of code to check
instead of the entire program
if you find that
you want to make a change to the data structure
well you can go ahead and do that much more easily
because you only have a small amount of code
which depends upon that data structure
and thirdly
if you want to make
of part of your code well you can do that a lot more easily now
you could take one of those
pockets, one of those components
and bring it into a new program
on the data structure that it is built around
will automatically come with it
and that's encapsulation