-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEncapsulateDowncast.java
43 lines (37 loc) · 1.06 KB
/
EncapsulateDowncast.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package ch10;
/*
* A method returns an object that needs to be downcasted by its callers
*
* Move the downcast to within the method
*
* - Rather than force client to do the downcasting, you should always provide
* them with the most specific type you can
*
* - The downcasting case often appear with methods that return a collection or iterator
*
* - Altering a method to return a subclass alters the signature of the method but does
* not break existing code because the compiler knows it can substitue a subclass for
* the superclass
*/
class EncapsulateDowncast {
Object lastReading() {
return readings.lastElement();
}
public void client() {
Reading lastReading = (Reading) theSite.readings().lastElement();
}
}
class Site {}
class EncapsulateDowncastRefactored {
Reading lastReading() {
return (Reading) readings.lastElement();
}
public void client() {
Reading lastReading = theSite.getLastReading();
}
}
class SiteRefactored {
public Reading getLastReading() {
return (Reading) readings.lastElement();
}
}