Method Overloading
There are a lot of techniques for working with methods.
One technique is called method overloading.
Method overloading allows us to define methods with the same name and purpose, but different signatures.
The first PlaceOrder method defines two parameters, one for the product to order and one for the quantity of that product.
This overload adds a delivery by date, and another overload adds delivery instructions.
This overload adds a delivery by date, and another overload adds delivery instructions.
For method overloading, the name must be the same, and the number and/or type of parameters must be different.
The return type is excluded when comparing signature for overloading, so even though this method has the name, it is not a valid overload, because the only difference is the return type.
Overloading lets us provide a simple signature for the simple scenarios and more full-featured signatures for more advanced scenarios, making it easier for other code to use our methods.
One technique is called method overloading.
Method overloading allows us to define methods with the same name and purpose, but different signatures.
The first PlaceOrder method defines two parameters, one for the product to order and one for the quantity of that product.
This overload adds a delivery by date, and another overload adds delivery instructions.
This overload adds a delivery by date, and another overload adds delivery instructions.
For method overloading, the name must be the same, and the number and/or type of parameters must be different.
The return type is excluded when comparing signature for overloading, so even though this method has the name, it is not a valid overload, because the only difference is the return type.
Overloading lets us provide a simple signature for the simple scenarios and more full-featured signatures for more advanced scenarios, making it easier for other code to use our methods.
- Do keep the number of parameter to a minimum. If there are a large number of parameter, consider grouping them into an object.
- Do keep the order of the parameter consistent. Notice that for each overload, we added the new parameter to the end.
- Do define an XML document comment for each overload with a description of each parameter.
- Consider using optional parameters instead of method overloads when feasible.
- Avoid confusing overloads. for example, one overload that takes a boolean and a string and another overload that takes a string and a boolean.
- Avoid overloads that differ in purpose. for example, an OrderItems method could have one overload that gets the ordered items, and second overload that orders a set of items. these methods don't have the same purpose and should not be named the same.
- Avoid duplicating code.
Comments
Post a Comment