how explicit should I be with my overloads?
-
22-08-2019 - |
Question
I'm building a wrapper for a jquery plugin to C# and I dont like the usage of [Optional] because its not as "optional" as it says it is(meaning you still have to declare that System.Missing library) so I decided to use overloaded methods. I want to give the user alot of customization but I'm not sure how explicit I should be with my overloads. Should I break it down in terms of importance for the parameters or do an overload for every scenario.
P.S I'm calling a base class' constructor and having to use base(param1, param2, ...)
method but I would also like to use this(param1, param2, ...
) instead of having to initialize my member variables in each scenario, is there a way around this?
Solution
A confusing API is the eternal bane of library consumers. Make it easy, even trivial, for people to decide exactly what they want to do given the interface you provide. If they must pick from a lengthy list of overloaded functions, that's probably too much cognitive overhead. Also, it's worth noting that C# 4 will have support for optional and named parameters, so your System.Missing
problem will go away by itself.
Is it frowned upon in terms of OOP?
OOP favors the Single Responsibility Principle, or SRP. If you have a single class with many of these functions, each having many overloads, that suggests that it may be doing too much.
Does it decrease in efficiency?
If you have a lot of overloads for the same method, it takes longer to statically resolve each function call (i.e., "which method with this name is the right one?"). But that's not going to have a runtime impact on performance if they're nonvirtual calls -- that is, where the compiler can statically know exactly what type something is going to be. Either way, though, I don't think that should be your motivating factor here.
OTHER TIPS
If you have a lot of parameters and need to be extensible consider using a class that contains your parameters.
E.g.
public class FileOptions
{
public bool Indented { get; set; }
public string Namespace { get; set; }
public System.Text.Encoding Encoding { get; set; }
}
public void Save(string fileName, FileOptions options) { ... }
// usage:
obj.Save("a.xml", new FileOptions { Indented=true });
obj.Save("b.xml", new FileOptions { Namespace="urn:foo", Encoding=System.Text.Encoding.UTF8 });