CSC 480 Software Engineering Encapsulation
Topics OOD guidelines: an overview Encapsulation Accessors and mutators Side effects Pre- and postcoditions Invariants
Elements of the Object Model Abstraction: model the essential attributes Encapsulation: hide implementation details Modularity: (think package in Java) Hierarchy: ranking/ordering of objects Typing: enforcement of the class Concurrency: distinguishes active object Persistence: transcends time and/or space
Abstraction
Encapsulation
Modularity
Hierarchy: “part-of” relationship
Hierarchy: “is-a” relationship
Typing
Concurrency
Persistence
Class Design Essential guidelines Instance variables are declared as private Public methods are provided to access and manipulate instance variables Accessors Mutators
Mutators Do not provide set methods for every instance variable Bad examples setBalance for a BankAccount class setDate, setMonth, and setYear for Date class Day deadline = new Day(2001, 1, 31); dealine.setMonth(2);//change day to 3/3 deadline.setDate(1);//final result is 3/1
Accessors Accessors may also break encapsulation giving out a reference to a mutable instance variable Solution – return a clone of the instance variable class Employee { private Date hireDate; //… public Date getHireDate() { //error //return hireDate; //the right way return (Date) hireDate.clone(); } }
What May Go Wrong? The mutable object may be modified by a client Sample code Employee bob = ...; Date d = bob.getHireDate(); d.setTime(t);
Separation of Getters & Setters It’s desirable to have Accessors will not change the state of an object nextToken for the StringTokenizer class Mutators will not return a data field removeFirst in the MessageQueue class In reality, you should consider your method design in terms of Completeness Convenience
Side Effects In a method invocation fraction1.add(fraction2); One expect the value in fraction1 be changed If the value in fraction2 changed, it is a side effect Changing a public static field is also a side effect Using System.out.println is not a good solution Define and throw specific exceptions instead
Programming by Contract Contract between client and server objects Formal definitions in terms of Precondition a condition must be fulfilled before the method may be called failure in doing so may cause program to break allow a client to check whether the condition is satisfied Postcondition A condition that holds after the method has completed Invariants A condition that is fulfilled by all objects after completion a method/constructor
Related Debugging Mechanisms Assertion A condition a programmer expects to be true Available since Java version 1.4 Program will terminate if an assertion yields false Exception The exceptions as declared in the throws clause should be deemed as a part of the contract Typical Java style, especially good for something the client have no control