Code units

Code units #

A unit test is meant to test to a small unit of code. This is only possible if the program contains small units of code.

Therefore unit testing is closely related to decomposing complex problems into smaller ones (and creating methods that solve these smaller problems).

Benefits #

Possible benefits of decomposing complex methods into smaller ones are:

  • readability,
  • easier debugging,
  • opportunities to factorize code (the same small methods can be called in several places),
  • easier collaboration (two person modifying the same method in parallel is less likely if the method is small),

Some good indicators that auxiliary methods may be helpful are:

  • multiple levels of nested blocks (“curly braces” in Java),
  • a loop that contains an important amount of code.

Simplify (and factorize) the following pseudocode using auxiliary methods:

if(<condition1>){
    while(<condition2>){
        if(<condition3>){
            <block1>
        } else {
            <block2>
        }
        <block3>
    }
    <block4>
} else {
    if(<condition3>){
        <block1>
    } else {
        <block2>
    }
    <block5>
}
<block6>
method1()
<block6>

method1(){
    if(<condition1>){
        method2()
        <block4>
    } else {
        method3()
        <block5>
    }
}

method2(){
    while(<condition2>){
        method3()
        <block3>
    }
}

method3(){
    if(<condition3>){
        <block1>
    } else {
        <block2>
    }
}