I was reading an article on how optional arguments break when versioning changes.
To paraphrase here.
Let’s look at a quick example of these two concepts at work. Suppose we have a class with one method having the following signature.
// v1
public static void Redirect(string url, string protocol = "http");
This hypothetical library contains a single method that takes in two parameters, a required string url and an optional string protocol.
The following shows the six possible ways this method can be called.
HttpHelpers.Redirect("https://haacked.com/");
HttpHelpers.Redirect(url: "https://haacked.com/");
HttpHelpers.Redirect("https://haacked.com/", "https");
HttpHelpers.Redirect("https://haacked.com/", protocol: "https");
HttpHelpers.Redirect(url: "https://haacked.com/", protocol: https");
HttpHelpers.Redirect(protocol: "https", url: https://haacked.com/");
Notice that whether or not a parameter is optional, you can choose to refer to the parameter by name or not. In the last case, notice that the parameters are specified out of order. In this case, using named parameters is required.
The Next Version
One apparent benefit of using optional parameters is that you can reduce the number of overloads your API has. However, relying on optional parameters does have its quirks you need to be aware of when it comes to versioning.
Let’s suppose we’re ready to make version two of our awesome HttpHelpers library and we add an optional parameter to the existing method.
// v2
public static void Redirect(string url, string protocol = "http", bool permanent = false);
What happens when we try to execute the client without recompiling the client application?
We get the following exception message.
Unhandled Exception: System.MissingMethodException: Method not found: 'Void HttpLib.HttpHelpers.Redirect(System.String,
System.String)'....
I'm confused as to why this change will break deployed not recompiled changes.
After changing the method signature which includes an optional parameter it should still work isn't? even if we do not recompile the client application since this is an optional parameter.
Your code needs to be recompiled so that the compiler can generate a call to a new method that takes three arguments. Optional methods are just syntactic sugars, when you don't provide an optional argument the compiler passes the default value for you. But it can't happen if you don't recompile your code and you will attempt to call method with two arguments while three was expected.