It is so common that we need to add new parameter to the method during the system development or maintenance. Adding new parameter will become unavoidable when the business requirements changed.
For example, you have a method call Process which takes 2 integer parameters as shown below:
public int Process(int a, int b) { int result = a + b; return result; }
Now, what if you have to add a new integer parameter to this method? Normally, we will just simply add a parameter as we used to do. So, the new method will be look like this:
public int Process(int a, int b, int c) { int result = a + b + c; return result; }
Again, you have to add a new parameter (i.e., fourth parameter) due to the business process changed. OK. I think we need an efficient way to do this.
To avoid adding new parameter to the method (i.e., changing the method signature), we have to pass a struct or a object to the method. To do this,
1. Declare a class call MyParam:
public class MyParam { public int a { get; set; } public int b { get; set; } public int c { get; set; } }
2. Change the Process method to take in the MyParam class instead of the 3 parameters:
public int Process(MyParam p) { int result = p.a + p.b + p.c; return result; }
3. If you want to the fourth parameter, you have to add a new property instead of parameter. Also, the caller will no longer require to be modify because the method signature does not change.
The new MyParam class will be look like this:
public class MyParam { public int a { get; set; } public int b { get; set; } public int c { get; set; } public int d { get; set; } //<== new parameter. }
Of course, the implementation within the Process method must be modify and the caller must assign the value to property 'd' before passing it to the Process method.
No comments:
Post a Comment