问题
I was wondering about providing backwards compatibility by using optional parameters.
In my program I have an interface with a function that is used throughout my program as well as in a lot of unittests. For some new functionality, a boolean has to be passed into this function which will alter its behaviour if set to false
. If you pass in true
, you will get the same behaviour as before.
Now I have to pass in true
everywhere where in my current code where I have called this function before. That is why I was thinking: "Ok I just put true
as the default value of the boolean. Then I only have to pass in false
in the few new places where I need the new behaviour."
I feel however, that my motivation to make the interface this way is to have to do less coding now. Usually when that is the only motivation I can think of it is a short-cut and will probably bite me later on. I cannot think of anything that will cause problems later on though, which is why I post this question here.
Next to my situation as I described above, is it a good idea in general to make a new parameter optional for backwards compatibility (e.g. in interfaces that are used by third parties)?
Thanks in advance.
回答1:
I good reason against would be that optional parameters default values are only used at compile time (except when using the dynamic keyword).
So if your third party is trying to use the new version without recompiling their code (such as having your library marked as a dependency in nuget) it would not be compatible because the signature has an extra parameter.
来源:https://stackoverflow.com/questions/7516256/is-using-optional-parameters-for-backwards-compatibility-a-good-idea