编程风格:编写新函数或扩展现有函数
Programming style: write new functions or extend existing ones
可以说,我有一个带有图像字段和函数```getImageWidth()```的表单,用于检查图像宽度。一段时间后,我在我的表单中添加了一个新的移动图像字段,我想知道,编写检查移动图像宽度的函数的最佳实践是什么——扩展旧函数```getImageWidth()```(通过添加参数 isMobileImage) 或编写一个新的 ```getMobileImageWidth()``` 函数?这个新函数的代码与旧函数几乎相似。
你有什么看法?
谢谢,
我认为 getMobileImageWidth()
会是更好的选择。比如有话题Remove Flag Argument in Martin Fowler's blog. And in his book Refactoring: Improving the Design of Existing Code他写了下一句话:
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.
我认为这正是您所需要的。
可以说,我有一个带有图像字段和函数```getImageWidth()```的表单,用于检查图像宽度。一段时间后,我在我的表单中添加了一个新的移动图像字段,我想知道,编写检查移动图像宽度的函数的最佳实践是什么——扩展旧函数```getImageWidth()```(通过添加参数 isMobileImage) 或编写一个新的 ```getMobileImageWidth()``` 函数?这个新函数的代码与旧函数几乎相似。
你有什么看法? 谢谢,
我认为 getMobileImageWidth()
会是更好的选择。比如有话题Remove Flag Argument in Martin Fowler's blog. And in his book Refactoring: Improving the Design of Existing Code他写了下一句话:
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.
我认为这正是您所需要的。