<<

Concepts of Object-Oriented Programming

Peter Müller Chair of Programming Methodology

Autumn Semester 2016 5. Information Hiding and Encapsulation 2 5. Information Hiding and Encapsulation

5.1 Information Hiding 5.2 Encapsulation

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 3 Information Hiding

▪ Definition Information hiding is a technique for reducing the dependencies between modules: - The intended client is provided with all the information needed to use the module correctly, and with nothing more - The client uses only the (publicly) available information

▪ Information hiding deals with programs, that is, with static aspects ▪ Contracts are part of the exported interfaces

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 4 Objectives

▪ Establish strict interfaces class Set { … ▪ Hide implementation // contract or documentation details public void insert( Object o ) { … } ▪ Reduce dependencies } between modules class BoundedSet { - Classes can be studied and Set rep; understood in isolation int maxSize; - Classes interact only in public void insert( Object o ) { simple, well-defined ways if ( rep.size( ) < maxSize ) rep.insert( o ); } }

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 5 The Client of a Class

▪ Class name class SymbolTable extends Dictionary ▪ Type parameters implements Map { and their bounds public int size; ▪ Super-interfaces public void add( String keykey,, String value ) ▪ Signatures of { put( key, value ); } exported methods public String lookup( String key ) and fields throws IllegalArgumentException { return atKey( key ); ▪ Client interface of } direct superclass }

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 6 What about Inheritance?

▪ Is the name of the class SymbolTable { superclass part of the Dictionary rep; client interface or an public SymbolTable( ) implementation detail? { … } public void add( String key, String value ) { … } ▪ In Java, inheritance is public String lookup( String key ) done by subclassing { … } ▪ Subtype information } must be part of the client Dictionary d; interface d = new SymbolTable(); d.put( “var”, “5” );

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 7 The Client Interface of a Class

▪ Class name class SymbolTable extends Dictionary ▪ Type parameters implements Map { and their bounds public int size; ▪ Super-class public void add( String key, String value ) ▪ Super-interfaces { put( key, value ); } ▪ Signatures of public String lookup( String key ) exported methods throws IllegalArgumentException { return atKey( key ); and fields } ▪ Client interface of } direct superclass

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 8 Other Interfaces

▪ Subclass interface package coop.util; public class DList { - Efficient access to protected Node first, last; superclass fields private int modCount; - Access to auxiliary protected void modified( ) superclass methods { modCount++; } … ▪ Friend interface } - Mutual access to implementations of package coop.util; cooperating classes /* default */ class Node { /* default */ Object elem; - Hiding auxiliary classes /* default */ Node next, prev; ▪ And others … }

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 9 Expressing Information Hiding

▪ Java: Access modifiers - public client interface - protected subclass + friend interface - Default access friend interface - private implementation

▪ Eiffel: Clients clause in feature declarations - feature { ANY } client interface - feature { T } friend interface for class T - feature { NONE } implementation (only “this”-object) - All exports include subclasses

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 10 Safe Changes

▪ Consistent renaming of package coop.util; hidden elements public class DList { ▪ Modification of hidden implementation as long protected Node first, last; as exported functionality is preserved private int modCountversion; ; protected void incrModCount(modified( ) ) ▪ Access modifiers and { modCountversion++;++; } } clients clauses specify … what classes might be } affected by a change

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 11 Exchanging Implementations

▪ Observable behavior class Coordinate { must be preserved private double x,y; … ▪ Exported fields limit public double distOrigin( ) modifications severely { return Math.sqrt( x*x + y*y ); } - Use getter and setter } methods instead - Uniform access in Eiffel class Coordinate { ▪ Modifications are critical private double radius, angle; … - Fragile baseclass problem public double distOrigin( ) - Object structures { return radius; } }

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 12 Method Selection in Java (JLS1)

class T { ▪ At compile time: public void m( ) { ... } 1. Determine static declaration } 2. Check accessibility 3. Determine invocation mode class S extends T { (virtual / nonvirtual) public void m( ) { ... } }

▪ At run time: class U extends S { } 4. Compute receiver reference 5. Locate method to invoke (based on dynamic type of receiver T v = new U( ); object) v.m( );

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 13 Rules for Overriding: Access

▪ Access Rule: class Super { … The access modifier of an protected void m( ) { … } overriding method must } provide at least as much access as the overridden class Sub extends Super { method public void m( ) { … } } Default access

In class Super or Sub: protected public void test( Super v ) { v.m( ); public }

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 14 Rules for Overriding: Hiding

▪ Override Rule: class Super { … A method Sub.m private void m( ) overrides the superclass { System.out.println(“Super”); } method Super.m only if public void test( Super v ) Super.m is accessible { v.m( ); } from Sub } ▪ If Super.m is not class Sub extends Super { accessible from Sub, it is public void m( ) { System.out.println(“Sub”); } hidden by Sub.m } ▪ Private methods cannot be overridden Super v = new Sub( ); v.test( v );

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 15 Problems with Default Access Methods ▪ S.m does not override package PT; T.m (T.m is not public class T { void m( ) { ... } accessible in S) } ▪ T.m and S.m are different methods with package PS; same signature public class S extends PT.T { public void m( ) { ... } ▪ Static declaration for } invocation is T.m ▪ At run time, S.m is In package PT: selected and invoked T v = new PS.S( ); v.m( );

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 16 Corrected Method Selection (JLS2)

▪ Dynamically selected method must override statically determined method

▪ At compile time: ▪ At run time: 1. Determine static 4. Compute receiver declaration reference 2. Check accessibility 5. Locate method to invoke 3. Determine invocation that overrides statically mode (virtual / determined method nonvirtual)

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 17 Problems with Protected Methods ▪ S.m overrides T.m package PT; public class T { ▪ Static declaration is protected void m( ) { ... } T.m, which is } accessible for C package PS; ▪ At run time, S.m is public class S extends PT.T { selected, which is not protected void m( ) { ... } } accessible for C public would package PT; be safe ▪ protected does not public class C { always “provide at public void foo( ) { least as much access” T v = new PS.S( ); v.m( ); } as protected }

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 18 Another Fragile Baseclass Problem

class C { Develop int x; Superclass public void inc1( ) { this.inc2( ); } private void inc2( ) { x++; } Implement } Subclass class CS extends C { public void inc2( ) { inc1( ); } }

Modify CS cs = new CS( 5 ); Superclass cs.inc2( ); System.out.println( cs.x );

Peter Müller – Concepts of Object-Oriented Programming 5.1 Information Hiding and Encapsulation – Information Hiding 19 Another Fragile Baseclass Problem

class C { Develop int x; Superclass public void inc1( ) { this.inc2( ); } protected void inc2( ) { x++; } Implement } Subclass class CS extends C { public void inc2( ) { inc1( ); } }

Modify CS cs = new CS( 5 ); Superclass cs.inc2( ); System.out.println( cs.x );

Peter Müller – Concepts of Object-Oriented Programming 5. Information Hiding and Encapsulation 20 5. Information Hiding and Encapsulation

5.1 Information Hiding 5.2 Encapsulation

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 21 Objective

▪ A well-behaved module class Coordinate { operates according to its public double radius, angle; specification in any // invariant 0 <= radius && context, in which it can be // 0 <= angle && angle < 360 reused … // ensures 0 <= result ▪ Implementations rely on public double distOrigin( ) consistency of internal { return radius; } representations }

▪ Reuse contexts should be Coordinate c = new Coordinate( ); prevented from violating c.radius = -10; consistency Math.sqrt( c.distOrigin( ) );

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 22 Encapsulation

▪ Definition Encapsulation is a technique for structuring the state space of executed programs. Its objective is to guarantee data and structural consistency by establishing capsules with clearly defined interfaces.

▪ Encapsulation deals mainly with dynamic aspects ▪ Information hiding and encapsulation are often used synonymously in the literature; here, encapsulation is a more specific concept

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 23 Levels of Encapsulation

▪ Capsules can be - Individual objects - Object structures - A class (with all of its objects) - All classes of a subtype hierarchy - A package (with all of its classes and their objects)

▪ Encapsulation requires a definition of the boundary of a capsule and the interfaces at the boundary

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 24 Consistency of Objects

▪ Objects have (external) obj1 interfaces and an (internal) a1: representation a2: ▪ Consistency can include ha1: ha2: - Properties of one execution state ha3: - Relations between execution m(p1,p2) {..} states m1( ) {..} ▪ The internal representation of m2(p) {..} an object is encapsulated if it h1(p,q) {..} h2(r) {..} can be manipulated only by h3( ) {..} using the object’s interfaces

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 25 Example: Breaking Consistency (1) Use private class Coordinate { ▪ Problem: public double radius, angle; Exported fields allow // invariant 0 <= radius && // 0 <= angle && angle < 360 objects to manipulate the … state of other objects // ensures 0 <= result public double distOrigin( ) ▪ Solution: { return radius; } } Apply proper information hiding Coordinate c = new Coordinate( ); c.radius = -10; Math.sqrt( c.distOrigin( ) );

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 26 Example: Breaking Consistency (2)

▪ Problem: class Coordinate { Subclasses can protected double radius, angle; // invariant 0 <= radius && introduce (new or // 0 <= angle && angle < 360 overriding) methods that … break consistency public double getAngle( ) ▪ Solution: { return angle; } } Behavioral subtyping

class BadCoordinate BadCoordinate c = extends Coordinate { new BadCoordinate( ); public void violate( ) c.violate( ); { angle = -1; } Math.sqrt( c.getAngle( ) ); }

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 27 Achieving Consistency of Objects

1. Apply information hiding: Hide internal representation wherever possible 2. Make consistency criteria explicit: Use contracts or informal documentation to express consistency criteria (e.g., invariants) 3. Check interfaces: Make sure that all exported operations of an object – including subclass methods – preserve all documented consistency criteria

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 28 Invariants

▪ Invariants express class Redundant { consistency properties private int a, b; // invariant a == b … ▪ The invariant of object o has public void set( int v ) { to hold in: // prestate: invariant holds - Prestates of o’s methods a = v; // invariant does not hold - Poststates of o’s methods b = v; ▪ Temporary violations // poststate: invariant holds possible } }

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 29 Checks for Invariants: Textbook Solution

▪ Assume that all objects o are capsules - Only methods executed on o can modify o’s state - The invariant of object o only refers to the encapsulated fields of o

▪ For each invariant, we have to show - That all exported methods preserve the invariants of the receiver object - That all constructors establish the invariants of the new object

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 30 Object Consistency in Java

▪ Declaring all fields private class Redundant { does not guarantee private int a, b; private Redundant next; encapsulation on the level // invariant a == b of individual objects … ▪ Objects of same class can public void set( int v ) { … } break the invariant public void violate( ) { ▪ Eiffel supports // all invariants hold encapsulation on the next.a = next.b + 1; object level // invariant of next does not hold - feature { NONE } } }

Peter Müller – Concepts of Object-Oriented Programming 5.2 Information Hiding and Encapsulation – Encapsulation 31 Invariants for Java (Simple Solution)

▪ Assumption: The invariants of object o may only refer to private fields of o

▪ For each invariant, we have to show - That all exported methods and constructors of class T preserve the invariants of all objects of T - That all constructors in addition establish the invariants of the new object

Peter Müller – Concepts of Object-Oriented Programming 5. Information Hiding and Encapsulation 32 References

▪ James Gosling, Bill Joy, Guy Steele, Gilad Bracha, and Alex Buckley: The Java Language Specification. 2013 http://docs.oracle.com/javase/specs/

▪ Peter Müller and Arnd Poetzsch-Heffter: Kapselung und Methodenbindung: Javas Designprobleme und ihre Korrektur. Java-Informations-Tage, 1998 (in German)

Peter Müller – Concepts of Object-Oriented Programming