Define two methods with the same type of parameter

Today I came across a scenario where I need to create a method that has the same name, params count and params types with an existing one, something like this:

 public static Department GetDepartment(string departmentName) { //LOGIC } public static Department GetDepartment(string employeeID) { //LOGIC } 

at first glance I just said why not call him by another name and do nothing, but I couldn’t! I want to keep the readability of my code I'm working on, I want it to be overloaded first,
so I said, why not add a fake parameter to get around this problem from a compiler point of view.

  public static Department GetDepartment(string employeeID, object fakePassWtEver) { //LOGIC } 

What is the best practice for this case? I see that all the ways allow my code to work, but none of them satisfied me.

+7
source share
4 answers

Maintaining readability is exactly why you should rename it:

 Department GetDepartmentByName(...) Department GetDepartmentByEmployeeID(...) 

Now when you call the method, it is absolutely obvious which you mean. This is not the case if you overload this method.

I refuse to overload more and more over time - there are quite a few subtle issues , and readability is often reduced.

+28
source

You can update the signatures of your method and make your code more readable at the same time by following these steps.

 public static GetDepartmentByName( string departmentName ) public static GetDepartmentByEmployeeId( string employeeId ) 

Personally, I feel that adding verbosity to the code helps others who come later to understand what is going on. It also helps make your methods more readable.

+5
source

Define 2 methods:

  • public static Department GetDepartmentByDepartmentName(string departmentName)
  • public static Department GetDepartmentByEmployeeID(string employeeID)
+4
source

Another option would be to delegate other methods if you can somehow distinguish between the employee ID and the department name by examining the argument.

 public static Department GetDepartment(string employeeIdOrDepartmentName) { if (LooksLikeEmployeeID(employeeIdOrDepartmentName)) return GetDepartmentByEmployeeID(employeeIdOrDepartmentName); else return GetDepartmentByDepartmentName(employeeIdOrDepartmentName); } private static Department GetDepartmentByEmployeeID(string employeeId) { /* ... */ } private static Department GetDepartmentByDepartmentName(string departmentName) { /* ... */ } 

You should only do this if you absolutely cannot add another method for clarity - the remaining answers are 100%.

0
source

All Articles