SlideShare una empresa de Scribd logo
1 de 22
+
Encapsulation
Systems Analysis and Design
Michael 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 Function
End 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.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (10)

Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Driven to Tests
Driven to TestsDriven to Tests
Driven to Tests
 
Clean Code
Clean CodeClean Code
Clean Code
 
Oops presentation java
Oops presentation javaOops presentation java
Oops presentation java
 
Object Oriented Relationships
Object Oriented RelationshipsObject Oriented Relationships
Object Oriented Relationships
 
Total oop in c# dot net
Total oop in c# dot netTotal oop in c# dot net
Total oop in c# dot net
 
SOLID principles
SOLID principlesSOLID principles
SOLID principles
 
13. interfaces
13. interfaces13. interfaces
13. interfaces
 
Abstract method
Abstract methodAbstract method
Abstract method
 
Design patterns
Design patternsDesign patterns
Design patterns
 

Destacado

Destacado (9)

Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Chapter 03 enscapsulation
Chapter 03 enscapsulationChapter 03 enscapsulation
Chapter 03 enscapsulation
 
Microencapsulation
MicroencapsulationMicroencapsulation
Microencapsulation
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)
 
encapsulation
encapsulationencapsulation
encapsulation
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
polymorphism
polymorphism polymorphism
polymorphism
 

Similar a SAD05 - Encapsulation

Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desaijinaldesailive
 
CPP14 - Encapsulation
CPP14 - EncapsulationCPP14 - Encapsulation
CPP14 - EncapsulationMichael Heron
 
Clean Code .Net Cheetsheets
Clean Code .Net CheetsheetsClean Code .Net Cheetsheets
Clean Code .Net CheetsheetsNikitaGoncharuk1
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.Questpond
 
Top 30 Technical interview questions
Top 30 Technical interview questionsTop 30 Technical interview questions
Top 30 Technical interview questionsSohailSaifi15
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxArifaMehreen1
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Luis Valencia
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cfloraaluoch3
 
A Tale of Two Patterns
A Tale of Two PatternsA Tale of Two Patterns
A Tale of Two PatternsKevlin Henney
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and oodthan sare
 
CHAPTER 3.pptx
CHAPTER 3.pptxCHAPTER 3.pptx
CHAPTER 3.pptxSRKkkr1
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternsbonej010
 

Similar a SAD05 - Encapsulation (20)

Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desai
 
CPP14 - Encapsulation
CPP14 - EncapsulationCPP14 - Encapsulation
CPP14 - Encapsulation
 
Clean Code .Net Cheetsheets
Clean Code .Net CheetsheetsClean Code .Net Cheetsheets
Clean Code .Net Cheetsheets
 
Clean code-v2.2
Clean code-v2.2Clean code-v2.2
Clean code-v2.2
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 
Bad Smells in Code
Bad Smells in CodeBad Smells in Code
Bad Smells in Code
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
Top 30 Technical interview questions
Top 30 Technical interview questionsTop 30 Technical interview questions
Top 30 Technical interview questions
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptx
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in c
 
A Tale of Two Patterns
A Tale of Two PatternsA Tale of Two Patterns
A Tale of Two Patterns
 
Oops concepts
Oops conceptsOops concepts
Oops concepts
 
Review oop and ood
Review oop and oodReview oop and ood
Review oop and ood
 
Mca 504 dotnet_unit3
Mca 504 dotnet_unit3Mca 504 dotnet_unit3
Mca 504 dotnet_unit3
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
CHAPTER 3.pptx
CHAPTER 3.pptxCHAPTER 3.pptx
CHAPTER 3.pptx
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
Writing Quality Code
Writing Quality CodeWriting Quality Code
Writing Quality Code
 

Más de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 

Más de Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Último (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

SAD05 - Encapsulation

  • 2. + 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
  • 3. + 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.
  • 4. + 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.
  • 5. + 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
  • 6. + 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 Function End Class
  • 7. + 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.
  • 8. + 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.
  • 9. + 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.
  • 10. + 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.
  • 11. + 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.
  • 12. + 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.
  • 13. + 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.
  • 14. + 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.
  • 15. + 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.
  • 16. + 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.
  • 17. + 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.
  • 18. + 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.
  • 19. + 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.
  • 20. + 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.
  • 21. + 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.
  • 22. + 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.