SORU
24 EYLÜL 2008, ÇARŞAMBA


Kod yollar anahtarı ortadan kaldırmak için

Yollarından kod anahtarı kullanımını ortadan kaldırmak için nelerdir?

CEVAP
24 EYLÜL 2008, ÇARŞAMBA


Switch Statements Smell:

Tipik olarak, benzer switch deyimleri bir program boyunca dağılmış. Eğer siz veya bir koşul eklemek anahtarını kaldırırsanız, sık sık bulmak ve diğerleri de tamir etmek zorunda.

Refactoring Refactoring to Patterns hem de bu sorunu çözmek için yaklaşımlar var.

Eğer (pseudo) kod gibi görünüyor:

class RequestHandler {

    public void handleRequest(int action) {
        switch(action) {
            case LOGIN:
                doLogin();
                break;
            case LOGOUT:
                doLogout();
                break;
            case QUERY:
               doQuery();
               break;
        }
    }
}

Bu kod Open Closed Principle ihlal ve birlikte eylem kodu her yeni tür için kırılgandır. Bir tanıtabilirsin bu sorunu çözmek için 'Komut' nesne:

interface Command {
    public void execute();
}

class LoginCommand implements Command {
    public void execute() {
        // do what doLogin() used to do
    }
}

class RequestHandler {
    private Map<Integer, Command> commandMap; // injected in, or obtained from a factory
    public void handleRequest(int action) {
        Command command = commandMap.get(action);
        command.execute();
    }
}

Eğer (pseudo) kod gibi görünüyor:

class House {
    private int state;

    public void enter() {
        switch (state) {
            case INSIDE:
                throw new Exception("Cannot enter. Already inside");
            case OUTSIDE:
                 state = INSIDE;
                 ...
                 break;
         }
    }
    public void exit() {
        switch (state) {
            case INSIDE:
                state = OUTSIDE;
                ...
                break;
            case OUTSIDE:
                throw new Exception("Cannot leave. Already outside");
        }
    }

O zaman anlarız 'Devletin' nesnesi.

abstract class HouseState {
    public HouseState enter() {
        throw new Exception("Cannot enter");
    }
    public HouseState leave() {
        throw new Exception("Cannot leave");
    }
}
class Inside extends HouseState {
    public HouseState leave() {
        return new Outside();
    }
}
class Outside extends HouseState {
    public HouseState enter() {
        return new Inside();
    }
}

class House {
    private HouseState state;
    public void enter() {
        this.state = this.state.enter();
    }
    public void leave() {
        this.state = this.state.leave();
    }
}

Bu yardımcı olur umarım.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Dopelives

    Dopelives

    30 Temmuz 2009
  • Jared Busch

    Jared Busch

    25 Mayıs 2011
  • Julian Smith

    Julian Smith

    31 EKİM 2006