Search code examples
coding-stylerefactoring

Programming style: write new functions or extend existing ones



lets say, that I have a form with Image field and function ```getImageWidth()```, that checks Image width. After some time, I am adding a new Mobile Image field to my form and I am wondering, what is the best practice for writing a function to check Mobile Image width - extend the old one function ```getImageWidth()``` (by adding parameter isMobileImage) or writing a new ```getMobileImageWidth()``` function? The code for this new function is almost similar to the old one.

What are your opinions? Thank you,


Solution

  • I think, that getMobileImageWidth() will be better option. For example there is topic Remove Flag Argument in Martin Fowler's blog. And in his book Refactoring: Improving the Design of Existing Code he wrote the next statement:

    I dislike flag arguments because they complicate the process of understanding what function calls are available and how to call them. My first route into an API is usually the list of available functions, and flag arguments hide the differences in the function calls that are available. Once I select a function, I have to figure out what values are available for the flag arguments. Boolean flags are even worse since they don’t convey their meaning to the reader—in a function call, I can’t figure out what true means. It’s clearer to provide an explicit function for the task I want to do.

    I think it is exactly what you need.