Tuesday, July 8, 2008

Parent Control for small kids and big kids



class ParentControl {
public void checkViewer(Person viewer, Program tv)
throws ForbiddenViewerAndProgramException {
if(viewer.getAge() < 13 && tv.isViolent()){
throw new ViolentProgramException();
}
if(viewer.getAge() < 13 && tv.isSexual()){
throw new ThisIsTooEarlyForYouException();
}
if(viewer.getAge() >= 30 && tv.isCartoon(){
throw new GoOutAndFindDatesException();
}
viewer.watch(tv);
}
}

Saturday, July 5, 2008

The ClassCastException costs $40 (if refund is not accepted...)


class Me {
public Data salvageDataFromBrokenPC(PC brokenPC){
HDD hdd = brokenPC.getHDD();
HDDEnclosure enclosure = buy(HDDEnclosure.class);
enclosure.setHDD(hdd);
return enclosure.getData();
}
}


Exception in thread "main" java.lang.Exception:
Can't set IDE HDD to eSATA HDD Enclosure
...
Caused by: java.lang.ClassCastException: IDEHardDiskDrive
...
at Me.salvageDataFromBrokenPC(Me.java:5)

Friday, July 4, 2008

Exception is not a good way to report problems...



class Manager {
public Report report(){
Developer member = callMember();
try{
member.report();
}catch(NotEnoughTimeException e){
}catch(NotEnoughResourceException e){
}catch(NotEnoughMemoryOnPCException e){
}catch(INeedYouToCompleteYourReviewException e)
member.workHarder();
return new Report("Everything is all right");
}
}

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);
}
...
}

Inheritance... it's a dream


public class Granpa {
Property company = new Property();
Property money = new Property();
}

class Dad extends Granpa {
Property car = new Property();
Property house = new Property();
}

class Me extends Dad {
public Me(){
consume();
}
private void consume(){
super.company = null;
super.money = null;
super.car = null;
super.house = null;
}
}

Tuesday, July 1, 2008

Start blogging !!! ... but it may not last so long


public class Blogging extends Thread {

public void run() {
Blog today = new Blog();
today.post();
}

...

private static Blogging singleton = new Blogging();

protected Blogging(){}

public static Blogging getInstance(){
return singleton;
}
}