How to change a method’s signature without breaking your application

facebooktwittergoogle_pluspinterestlinkedinmailfacebooktwittergoogle_pluspinterestlinkedinmail

Suppose you have a method that con­cat­en­ates strings, like the method in code snip­pet 1 below. One day, you come to a point where this method does not suf­fice any­more. You need an addi­tional para­meter, to allow the user to place a char­ac­ter between each con­cat­en­ated string. That’s easy, right? You just alter the method, and its sig­na­ture, as in code snip­pet 2.

Works like a charm. We can just wrap this up and leave work early, can’t we?

No, we can’t. What about all the other code in your pro­ject (or in other people’s pro­jects) that uses the method you have just altered? That code now doesn’t work any­more. It doesn’t even com­pile any­more, because you changed the method’s sig­na­ture. Is there a way to pre­vent this from happening?

Fortunately, there is. There are three things we need to look into to make this happen. 

  1. We have to make sure that a method with the ori­ginal sig­na­ture still exists after we’re fin­ished, so that the rest of the code will still com­pile after our change. But hav­ing it com­pile is not enough.
  2. We have to make sure that the ori­ginal method gives the same res­ults as it did before we altered it. Ideally, you have some unit tests in place to ensure this.
  3. Finally, we want to do all this without copy­ing and past­ing any code.

The easi­est way to do this, is to find out a way in which the altered method offers exactly the same res­ults as the ori­ginal method. In our case, this would be hav­ing an empty string for the sep­ar­ator between all con­cat­en­ated strings. We can call our altered method with an empty string para­meter to have the same results.

Have a look at our final code below. There is still a method with the ori­ginal sig­na­ture, that does the same as the ori­ginal method, and we made all this hap­pen without copy­ing and past­ing code. Nice! Now we can go home.

Deprecation

If your new method makes the ori­ginal method obsol­ete, you can deprec­ate this method, by adding the @Deprecated annota­tion. When someone uses this deprec­ated method, the com­piler will give a warn­ing. The per­son using the method then has the oppor­tun­ity to use another method. In time, you can remove the deprec­ated method.

facebooktwittergoogle_pluspinterestlinkedinmailfacebooktwittergoogle_pluspinterestlinkedinmail