Articles‎ > ‎

Compiler Warnings

posted Jan 29, 2011, 2:44 AM by Michael Schollmeyer
Compiler errors and warnings can help you accomplish your work faster and with higher quality. javac is your friend so stop ignoring her. 

It seems that things the compiler issues beside the class file is nothing but annoyances to some developers. After all, if the compiler stops emitting errors, we are set. Consequently, some developers want the compiler to shut up. 

Imagine the following implementation of a paycheck application: 

public double getSalary(Employee employee) { 
    double salary; 

    if (employee.isBoard()) { 
        salary = employee.getBaseSalary() + employee.getBonus(); 
    } 
    else { 
        salary = employee.getBaseSalary(); 
    } 

    return salary; 


The implementation changes a lot over time, so some day a developer changes the code due to some updated requirements: 

public double getSalary(Employee employee) { 
    double salary; 

    if (employee.isBoard()) { 
        salary = employee.getBaseSalary() + employee.getBonus(); 
    } 
    else { 
        if (employee.isTerminated()) { 
            salary = employee.getBaseSalary(); 
        } 
    } 

    return salary; 


Now the compiler issues an error saying that "the local variable salary might not have been initialized". Very true, we branched at employee.isTerminated() but there is no else branch. 

Eclipse suggest at this point to initialize salary and if you agree, it will change double salary to double salary = 0. This may fix the error but not the problem. What is actually missing is the else branch. Some developers suggest to initialize all local variables for some reason. 

Think twice. The compiler will analyze all your method to find out if you missed an assignment to salary. All that is required is a little support from your side.
Comments