Reputation:
In my Generic Interface, I have a function that has optional parameters. I wrote it this way in an attempt to follow DRY (Don't Repeat Yourself). While the function works and I have logic within the function to take care of as many what-ifs as I can anticipate, I feel the job is incomplete unless I can enforce proper use of the method.
What I would like to do is enforce a rule so that either the first two parameters are used as a pair or the third parameter is used -- never both. I set it up to make the one function applicable to as many situations a possible. While I could write different overloads of this function to make sure it's used correctly, I wanted to make sure there wasn't anything in the function definition that could ensure that the parameter usage is enforced without actually having to write two variants of the same function.
I went back to basics and looked at the C# Programming Guide and while I found some useful refreshers, I did not see anything there that relates to this question.
Is there a way to enforce this rule inline, or is the creation of separate overloads the only way to enforce this rule?
IQueryable<TEntity> GetByFilter(
string byWhereColumn=null, string byWhereValue = null,
string byWhereString = null,
string byOrder = null,
string byDir = null
);
Upvotes: 2
Views: 134
Reputation: 15722
To indicate parameter useage as pair, you could use a Tuple, or, even better, a specific class to enforce having a pair. This applies to the already acceppted answer as well:
Example with a Tuple:
public IQueryable<TEntity> GetByFilter(
Tuple<String, String> byWhereValueAndColumn = null,
string byWhereString = null,
string byOrder = null,
string byDir = null
);
Example with class:
public IQueryable<TEntity> GetByFilter(
ColumnAndValue byWhere = null,
string byWhereString = null,
string byOrder = null,
string byDir = null
);
public class ColumnAndValue {
public String Column { get; private set; }
public String Value { get; private set; }
public ColumnAndValue(string column, string value) {
Column = column;
Value = value;
}
}
Of course, the API user could still set any of the pair's parameters to null, but this way you at least indicate very strongly how your API should be used.
Upvotes: 2
Reputation:
As per my comment, I think you need to use separate overloads, I understand you not wanting to repeat code, but you can only simplify it so far, and overloading methods, constructors, etc is not repetitious if it is necessary.
MyMethod (param1, param2){...
MyMethod (param3){...
Upvotes: 5