Design decision conflict for methods in a class
Ok I will try to explain this as much as possible. I have a class, say MyLib, the methods of which will be used by another class, say Consumer class. There is a public method called Navigate() in MyLib, which will be used by Consumer. This method sort of provides a level of abstraction for Consumer, as it can provide different types of navigation using just this method. The following code snippet provides the needed code map.
// this method will be exposed to the consumer class.
public bool Navigate (NavigationType type)
{
// this method will decide which private _navigateToXyz() method will be called.
switch (type)
{
case x: return _navigateToX();
case y: return _navigateToY();
case z: return _navigateToZ(arg1, arg2);
case a: return _navigateToA(arg3);
}
}
private bool _navigateToX() { }
private bool _navigateToY() { }
// two or three additional _navigateTo_() without any parameters
private bool _navigateToZ (arg1, arg2) { }
private bool _navigateToA (arg3) { }
As shown above, all but two private methods requires some arguments to be passed. So if I follow this approach, then I essentially have to pass those arguments in Navigate() as well - those arguments that none of the other methods have to do anything with.
I am doing this way right now. But I want to know if there is a better approach possible in this situation?
UPDATE : After some more brainstorming, I think that Navigate() method is not that required, since it pretty much just calls an appropriate method based on the passed navigationType. Now, the navigationType being known by the caller of Navigate(), he could himself call the very method required, if those methods are exposed as public. I hope I am clear. So do optional param开发者_JS百科eters matter at all now? Method overloading makes more sense?
Have multiple public versions of the method. That will make way more sense to consumers looking at this through intellisense.
Use optional paramters introduced in .NET 4.0
You can provide an overload, or more overloads, but be aware that overloads decrease API descoverability. Every time the consumer of the API needs to "navigate" it has first to decide which overload to call. This can be ok if the overloads make a lot of sense and if the consumer is already familiar with the API.
Another way is to use a class to pass the parameter. In your case NavigationType could be a class that encapsulates all the possible parameter combinations. This class can also have a few constants so that it can be used almost as an enum. Also the class could have overloaded consutrctors or a fluent builder interface to facilitate usage. Also the class could contain some navigation logic or navigation selection logic if appropriate.
精彩评论