Factorizing

Factorizing #

Duplicate code #

Duplicate code within a same project has undesirable consequences. In particular:

  1. Duplicate code means duplicate bugs.
  2. The application may be harder to extend: adding a new feature may require modifying several nearly identical copies of the same method and/or class.

Factorizing #

By code factorization, we mean eliminating duplicate statements or expressions, by analogy to the factorization of an algebraic expression (e.g. $(ab) + (ac)$ can be rewritten $a(b+c)$).

This usually comes down to simple techniques. We illustrate here a few of them.

Conditional statement #

Factorize the following program:

if(<condition 1>){
    <code block 1>
    <code block 3>
} else if(<condition 1> && <condition 2>){
    <code block 1>
    <code block 2>
    <code block 3>
} else {
    <code block 3>
}
if(<condition 1>){
    <code block 1>
}
<code block 3>

Auxiliary method #

Factorize the following Java class:

public class Extractor {

    String extractId(String text){
        Matcher matcher = Pattern.compile("^[A-Z]?\\d+").matcher(text);
        return matcher.find()?
                matcher.group(0):
                null;
    }

    String extractSSN(String text){
        Matcher matcher = Pattern.compile("SSN:(\\d+)").matcher(text);
        return matcher.find()?
                matcher.group(1):
                null;
    }
}
public class Extractor {

    String extractId(String text){
        return getFirstMatch(text, "^[A-Z]?\\d+", 0);
    }

    String extractSSN(String text){
        return getFirstMatch(text, "SSN:(\\d+)", 1);
    }

    String getFirstMatch(String text, String regex, int group){
        Matcher matcher = Pattern.compile(regex).matcher(text);
        return matcher.find()?
                matcher.group(group):
                null;
    }
}

Abstract class #

Factorize the following Java classes:

public class Unicorn extends Unit {

    public void wait(){
        <code block 1>
        <code block 2>
    }
}
public class Butterfly extends Unit {

    public void wait(){
        <code block 1>
        <code block 3>
    }
}
public class Wall extends Unit {

    public void wait(){
        <code block 4>
    }
}
public abstract class MobileUnit extends Unit {

    public abstract void wait(){
        <code block 1>
    }
}
public class Unicorn extends MobileUnit {

    @Override
    public void wait(){
        super.wait();
        <code block 2>
    }
}
public class Butterfly extends MobileUnit {

    @Override
    public void wait(){
        super.wait();
        <code block 3>
    }
}
public class Wall extends Unit {

    public void wait(){
        <code block 4>
    }
}