Best practice - when to overload?
When designing a class is it best to force the implementer to pass in all required parameters by making it part of the method signature or开发者_JAVA百科 to create an overload and allow the user to set properties, then check that they are set properly?
For example, let's say we have a class Emailer
with a method Send
. Send requires
public bool Send(string ToAddress, string FromAddress, string subject, string body, string Attachment = null)
I also have public properties
public string To { get; set; }
public string From { get; set; }
/// <summary>
/// Full filepath to attachment
/// </summary>
public string Attachment { get; set; }
public string Subject {get;set;}
public string Body {get;set;}
Now, should I create an overload for Send
?
public void Send()
And then write checks for unpopulated properties. Or, leave out the overload and possibly remove the properties?
I feel that your Emailer
has too much resposibility by holding those properties. Perhaps you should look into separating that into a Message
class, then you can pass that.
Have a look at the way the .NET mail classes do it.
I'd require anything needed as a parameter to make it harder to mess up... it's too easy to miss a required field if you leave it as a property. Plus, requiring certain fields as parameters makes it very explicit that you need those fields.
@Daniel A. White has already suggested using a Message class to separate your concerns (mailer vs message). I'd take in a Message object, which in turn requires the required data in the constructor (minimum of To and From).
This, of course, is assuming that you only used email as an example. In real life you'd use the built in classes :)
精彩评论