next up previous contents
Next: Replace Parameter with Query Up: Refactoring Example Previous: Refactoring Log

Refactoring Switch Statement

createWhere() {
...
// within an iteration over all attributes of the Kriterium object
  switch(krit.getOperatorId(i)){
  case Kriterium.NONE:
    break;
  case Kriterium.LIKE:
    where =  (where.equals("")?(" (" + spalteName):(where + " and (" + spalteName));
    if (obj==null) 
    where = where + " IS " + objOra7String+ ") ";
    else
    where = where + " like '\%" + 
        objOra7String.substring(1, objOra7String.length()-1) + "\%')";
    break;

// this is repeated 8 times to form the complete switch statement
...
now the code looks like:

createWhere() {
...
// within an iteration over all attributes of the Kriterium object

        operator=krit.getOperatorId(i);
        if (operator == Kriterium.NONE) continue;

        spalteName = createQualifiedName(dd.getDB(i,false), 
                     dd.getDBTable(i, false), dd.getAttributeName(i));

        obj = krit.getAttribute(i);
        where=andExpressions(where,
                             getExpression(spalteName,operator, obj));
...
with located in DatabaseFormat:

    public String getExpression(String field, int operator, Object obj) {
        return field + " " + getExpression(operator,obj);
    }
    public String getExpression(int operator, Object obj) {
        if (obj==null) 
            return formatWhereNull(operator);

        switch(operator){
        case Kriterium.LIKE:
          return formatLike(obj);
        case Kriterium.BEGIN:
          return formatBegin(obj);          
        default:
          return getOperatorLabel(operator) + " "+
                 formatObject(obj);
        }          
    }
...

 


next up previous contents
Next: Replace Parameter with Query Up: Refactoring Example Previous: Refactoring Log

Michael Hunger
Mit Okt 25 00:48:16 MEST 2000