Code Clarity with Class Constants

I enjoy refactoring legacy code, especially when I can add clarity to ambiguous business rules by using class constants. Consider the following line of code:

<?php
if ($Customer.AccountStatus == 1 
    && $Customer.BillingStatus == 100) { 
    
    // Do something....
}
?>

Now we are left with only a handfull of ways to know the true meaning of ’1′ and ’100′:

  • Hope the previous developer wrote detailed code comments
  • Hope there is existing documentation
  • Hope the original developer is still working there

Once we know the meaning of ’1′ and ’100′, we can refactor this code to ensure the next developer to come along will know exactly what this line of code is trying to accomplish. First we’ll create constants in the Account and Billing classes to represent the various status codes:

<?php
class Account {
    const Status_Open = 1;
    const Status_Closed = 2;
    const Status_Terminated = 3;
}

class Billing
{
    const Status_Current = 100;
    const Status_Pastdue_30 = 101;
    const Status_Pastdue_60 = 102;
    const Status_Pastdue_90 = 103;
}
?>

Now we can rewrite our conditional statement to utilize our class constants:

<?php
if ($Customer.AccountStatus == Account::Status_Open 
    && $Customer.BillingStatus == Billing::Status_Current) { 
    
    // Do something....
}
?>

With our refactored code we have provided current and future developers with an easy to understand conditional statement. Even our business stake holders could decipher this line of code. And remember, you don’t have to wait until you refactor legacy code to implement class constants!

Leave a Reply