A Neat Coding Trick: Add a Property Instead of a Parameter

If you’ve ever had to work on a legacy application with a HUGE code base, you might get faced with this situation:

Manager: “Hey journeyman can you fix this address on this page so that it knows to take a system configuration?”

Journeyman:  “Sure, give me a second for an estimate.”

You find the code:

public class AddressService {

      public String getFormattedAddress(Datasource ds, int yourFormat) {
           if (yourFormat == 1) { /* do this format */ }
           else { /* do this format */ }
           return addressString;
         }
 }

Now go in and track down the code to change .   Hmm interesting function called getFormattedAddress().  Let’s see, before I touch it do a code search in Eclipse : used in 147 places!!!!!  Ugh . . .

You shan’t dare change the function call in ALL those places, nightmare, just for one of the calls.

So here’s one way to do avoid this messy situation:

  1. Add a new property, yourConfig, with getters and setters.
  2. Override the function getFormattedAddress so that it takes your new parameter
  3. Set that parameter in the overriding function.
  4. Modify the original function to check the parameter, using a default if the value is empty.
  5. Call the original function form the overriding function
  6. Don’t forget to reset the default value!

Something like this:

public class AddressService {
      private String yourConfig = "";

      public String getFormattedAddress(Datasource ds, int yourFormat) {
           String localConfig = 
                   (getYourConfig == "") ? "default" : getYourConfig();
           setYourConfig("");   
           if (yourFormat == 1) { /* do this format +localConfig */ }
           else { /* do this format + localConfig */ }
           return addressString;
         }
     public String getFormattedAddress(Datasource ds, int yourFormat, String inYourConfig) {
           setYourConfig(inYourConfig);
           return getFormattedAddress(ds,yourFormat);
     }

    public String setYourConfig(String inStr) {this.yourConfig = inStr;}
    public void getYourConfig() {return this.yourConfig;}

}
Now you can call the function from either its original state, or, pass in a config.

Comments are closed.