SAD05 - Encapsulation
-
Upload
michael-heron -
Category
Software
-
view
80 -
download
2
description
Transcript of SAD05 - Encapsulation
+
Encapsulation
Systems Analysis and DesignMichael Heron
+Introduction
One of the things that distinguishes object orientation from other kinds of programming is the tight coupling between functions and data. This is a principle known as encapsulation.
In this lecture we are going to talk about why this is such an important technique. And the problems it was designed to resolve.
This is the second of the Great Pillars of OO Inheritance Encapsulation Polymorphism
+Scope
Cast your minds back to a few weeks ago when we talked briefly about scope. I mentioned this was an easy way to cause problems in
large programs. Hard to identify potential side effects Hard to guarantee fidelity of access.
By storing data along with the methods that act on that data (in a class), it is possible to have access to data without global scope. Variables inside a class have class-wide scope. They are available provided someone has access to that
class.
+Encapsulation
Encapsulation is the principle of keeping data and functions together in one unit. The class
By doing this, we have a highly portable unit of data we can manipulate. But only through the functions that we set.
We can set an interface on an object that permits us fine-grained control over access.
We don’t have to ferret around for methods to manipulate data. The methods come along with the data in a single capsule.
+Encapsulation in VB .NET
Class BankAccount private balance as Integer property Balance() as Integer Get return balance End Get Set (ByValue Value as Integer) balance = Value End Set End Property
public Function doubleBalance() balance = balance * 2; end Function
End Class
+Encapsulation in Java
Class ExtendedBankAccount inherits BankAccount
private overdraft as Integer
Function adjustBalance (byVal val as Integer) as Boolean if Me.Balance – val < 0 – overdraft then return false end if
Me.Balance = (getBalance() - val); return true; End FunctionEnd Class
+Private and Public
We set sections of the code to be either private or public. private for variables public for functions
These are known as visibility modifiers. They change how visible these things are to other pieces of
code.
There exists a third called protected. Of more niche benefit.
We need to carefully manage our visibility modifiers. They will in a large part define to what extent your code is
easily maintainable in large multi-developer environments.
+Private
Private visibility means that variables (or functions) are available only to the class in which they are defined. We can access balance and overdraft as variables within
the methods of our object. We cannot access them outside of that object.
Including within ExtendedAccount. We have to do that through our property.
We do this to make sure that people cannot simply set the value on our data. They have to go through methods or properties we provide. That way we can ensure that they don’t get set to crazy
values.
+Public
Public means anything has access. It’s the highest level of visibility. If you can get access to an object, you have access to its
public bits.
We reserve this visibility for methods that we don’t mind everyone being able to use. These methods make up our interface to the object.
This is why we use properties around variables in VB .NET The raw variable is made private so that other objects cannot
change it. We provide an ‘official interface’ through the property.
+Protected
Protected means that the class in which the item is defined and any children of that class can get access. It’s not available to external objects. Any child that is specialised from, at some point, the class
in which the item is defined has access.
Limits the impact of change to the defining class and specialisations only. Refactoring can be limited to these classes.
Protected offers an opportunity to provide fine grained control over inherited methods. Rarely advisable to do with variables.
+Impact of Change
It’s very common when writing a program to have to change the way things work. Alas, this comes with major side-effects for many
situations. Maintenance is an ongoing ‘manage the impact of
change’ scenario.
When working with other developers especially, you need to be wary. The interface to the objects you write is a kind of informal
contract with your colleagues. It’s important to be respectful when developing.
You cannot unilaterally make adjustments to shared code if you want to make it home alive at the end of a day.
+Impact of Change
Impact of Change defines how much code is likely to need changed if you make an adjustment to your code. The higher the impact, the more code will need modified.
Some things are almost always safe to do. Extension is usually safe:
Add in variables. Add in methods
Usually. Overloading and overriding are an issue.
Some things are almost never safe to do. Change what a method does.
+Impact of Change
In large object oriented programs, there may be thousands of classes. All interrelated in complex ways.
It is not possible to know which objects may be using public methods and variables in your code. You have to assume if it can be accessed, it will be accessed.
You’d be surprised how freely people will use exposed methods.
Can’t change code indiscriminately. That’s not respectful. Code unto others as you would have them code unto you.
+Impact of Change
Instead, what we do is restrict visibility. To private, ideally. We do this when we write the code.
We expose as public only those methods we are happy to support. The ones that we are exposing as our public interface.
This limits the impact of change. We only need to change things in our own class if we modify
things.
Important to be able to make adjustments in your code. Private access permits this.
+What is the benefit?
Simplify documentation. External documentation can focus on only relevant
functions.
Can ensure fidelity of access. If the only access to data is through methods you provide,
you can ensure consistency of access.
Hides the implementation details from other objects. In large projects, a developer should not have to be aware
of how a class is structures.
Simplifies code All access to the object through predefined interfaces.
+Problems with Encapsulation
They are conventions that have been adopted in some languages.. You can’t guarantee they are being adhered to in Java and
C++. These are handled by accessor methods.
Can lead to duplication of effort or over-engineering of code solutions.
Can lead to security leaks as people attempt to work around restrictions. Especially a problem when working with pointers and object
references in languages that provide explicit access.
+Designing A Class
A properly encapsulated class has the following traits. All data that belongs to the class is stored in the class.
Or at least, represented directly in the class.
All attributes are private. There’s almost never a good reason to make an attribute
public. Hardly ever a good reason to make an attribute protected.
Methods that all objects should have access to should be public. The rest should either be protected or private.
This allows you to internally refactor if required.
+The Class Interface
Classes have a defined interface. This is the set of public methods they expose.
A properly encapsulated class has a coherent interface. It exposes only those methods that are of interest to
external classes. It hides those methods that perform internal housekeeping
or data conversion.
A properly encapsulated class has a clean divide between its interface and its implementation. They likely won’t be handled in the same methods.
+Interfaces
The easiest way to think of an interface is with a metaphor.
Imagine your car’s engine. You don’t directly interact with the engine.
You have an interface to the engine that is controlled by: Gears Pedals Ignition
Likewise with your car wheels. Your steering wheel is the interface to your wheels.
As long as the interface remains consistent… It doesn’t matter what engine is in the care.
Change the interface and you can no longer drive the car the same way.
+Interface and Implementation
Within a properly encapsulated class, it does not matter to external developers how a class is implemented. I know what goes in. I know what comes out.
A properly encapsulated class will work as a black box.
The interface to a class can remain constant even while the entirety of the class is rewritten. Not an uncommon act in development.
As long as the interface remains constant, my code continues to function.
+Interface and Implementation
It’s important to design a clean an effective interface. It’s safe to change encapsulated implementation. It’s usually not safe to change a public interface.
You are committed to the code that you expose publicly. When new versions of .NET deprecate existing
functionality, they never just switch it off. Some old code implementations have been supported for
ten years. Deprecation (marking code as obsolete) is a very slow
process and you’ll have to go through it if you’re careless.
+Conclusion
Encapsulation is a tool for creating maintainable systems. And you will come to appreciate it when you start building your
own multi-person projects. Hint hint.
It allows you to package together attributes and the methods for acting on those methods in a safe way. By defining a public interface and restricting access to things
that shouldn’t be manipulated by others.
Good class design employs two main rules: All attributes should be private. Only those methods that are part of the interface should be
public.