2013-08-19 5 views
-2

Considérons un exemple de code.Comment refactoriser un code pas à pas?

  1. Est-ce un modèle que je ne connais pas?

  2. Comment nettoyer ce désordre?

    int func1val = func1(); 
    boolean val = checkIfTrue(func1val); 
    if (val) { 
        int func2val = func2(); 
        val = checkIfTrue(func2val); 
        if (val) { 
         int func3val = func3(); 
         val = checkIfTrue(func3val); 
        } 
    } 
    
    if (val) { 
    // print func1val, func2val, func3val, 
    } 
    

Répondre

0

On dirait que vous imprimez sur ces trois valeurs si et seulement si checkIfTrue renvoie true pour tous les trois. Sauf quelques détails de mise en œuvre de checkIfTrue, vous ne pourriez pas faire quelque chose comme

int func1val = 0, func2val = 0, func3val = 0; // any value here 
if (checkIfTrue(func1val = func1()) && checkIfTrue(func2val = func2()) && checkIfTrue(func3val = func3())) { 
    // print func1val, func2val, func3val 
} 

Pour être juste, quelque chose comme

int func1val = func1(); 
if (checkIfTrue(func1val)) { 
    int func2val = func2(); 
    if (checkIfTrue(func2val)) { 
     int func3val = func3(); 
     if (checkIfTrue(func3val)) { 
      // print func1val, func2val, func3val 
     } 
    } 
} 

doit faire la même chose, et peut-être plus lisible en fonction du réel situation.

0

Comment nettoyer est avec des rendements mi-méthode.

int func1val = func1(); 
boolean val = checkIfTrue(func1val); 
if (!val) return; 
int func2val = func2(); 
val = checkIfTrue(func2val); 
if (!val) return; 
int func3val = func3(); 
val = checkIfTrue(func3val); 
if (!val) return; 

// print func1val, func2val, func3val, 

Et puis vous n'avez même pas besoin de val; juste inline chaque occurrence:

int func1val = func1(); 
if (!checkIfTrue(func1val)) return; 
int func2val = func2(); 
if (!checkIfTrue(func2val)) return; 
int func3val = func3(); 
if (!checkIfTrue(func3val)) return; 

// print func1val, func2val, func3val, 
+1

Downvoters, veuillez laisser des commentaires. – GManNickG