Thursday, July 3, 2008

Bad polymorphism - Me, my wife and my PC


interface WithOpenPC {
}

class ForWork implements WithOpenPC {
}

class ForHobby implements WithOpenPC {
}

class Me {
public WithOpenPC whatAreYouDoingWithPC(){
if(isIDEOpen() || isBrowserOpen()){
return new ForHobby();
}else{
return new ForWork();
}
}
...
}

class MyWife {
public void checkOn(Me husband){
// This is supposed to cause compilation error!
// at least, ClassCastException!
PlayingWithPC whateverItIs =
(PlayingWithPC)husband.whatAreYouDoingWithPC();
complainTo(husband);
}
...
}

No comments: