Computer Science 209 - PowerPoint PPT Presentation

1 / 8
About This Presentation
Title:

Computer Science 209

Description:

The state of an object the values of its instance variables ... Avoid returning references to mutable objects. List Something A = new ArrayList Something ... – PowerPoint PPT presentation

Number of Views:43
Avg rating:3.0/5.0
Slides: 9
Provided by: KenLa2
Category:

less

Transcript and Presenter's Notes

Title: Computer Science 209


1
Computer Science 209
  • Encapsulation

2
What Is Encapsulation?
  • The state of an object the values of its
    instance variables can be modified only by
    running that objects methods
  • We get encapsulation by declaring a variable as
    private

3
Why Encapsulate?
  • Security avoid side effects
  • Modularity and simplicity reduce the number of
    interactions
  • Responsibility enforce ownership and division
    of labor in a system

4
Enforcement private Visibility
public class MyClass private String name
public ListltBookgt books
All instance variables should have private
visibility Dont make an instance variable
public because you think it will make it easier
for clients to access
5
Enforcement Immutability
public class MyClass private String name
public void setName(String name)
Avoid supplying mutator methods unless they are
absolutely necessary Classes like String are
immutable
6
Enforcement Immutability
public class MyClass private ListltBookgt
books public ListltBookgt getBooks()
return books
Avoid returning references to mutable objects
7
Enforcement Immutability
ListltSomethinggt A new ArrayListltSomethinggt() L
istltSomethinggt B new ArrayListltSomethinggt() A.
addAll(B) // A is implicit, B is explicit
// A is modified, B is not public void
modifyList(ListltSomethinggt x) x.clear()
Avoid mutations on explicit parameters
8
The Law of Demeter
  • A method should use only
  • Instance fields of its class
  • Parameters
  • Objects that it constructs with new
  • Dont operate on global objects or on objects
    that are part of the internal state of another
    object
Write a Comment
User Comments (0)
About PowerShow.com