问题
What's a good name for a method that adds something to a container if it's not already there, i.e.
void AddCustomerToList(CustomerList list, Customer customer)
but that name does not properly convey that it won't be added if it's not there already. What is a better name? AddCustomerToListIfNotThereAlready? EnsureCustomerInList?
回答1:
AddIfNotPresent
回答2:
Change CustomerList to CustomerSet, then it's obvious.
add(CustomerSet set, Customer customer);
回答3:
bool TryAdd(CustomerList list, Customer customer)
回答4:
I would go with something like AddIfMissing
, though I like the idea of renaming to Set since that's really what it is.
public static class ListExtensions
{
public static void AddIfMissing<T>( this List<T> list, T item )
{
if (!list.Contains(item))
{
list.Add( item );
}
}
}
回答5:
Usually "put" would be used instead of "add" to convey this, but I agree with chase that you should just call this "add" and use "set" instead of "list". Unless of course the container supports both operations (which would be odd).
回答6:
You could do like the generic list does and create a ContinsCustomer function to check if it exists first, then use AddCustomerToList if it returns false.
回答7:
Make it two methods. IsCustomerPresent() AddCustomer(). Then if you want you could make a AddCustomerIfNotAlreadyPresent() method that just calls your loosely coupled logic.
回答8:
in my opinion you are asking this question since you design OO is sub-optimal:
void AddCustomerToList(CustomerList list, Customer customer)
the responsability to ensure if a customer must be present must be assigned to
CustomerList
.
In that case you name your method:
Add
in the case you specify in the documentation that the customer will be added only if not presentAddIfNotPresent
orPutIfNotPresent
otherwise.
I prefer the latter since it is more autodocumented.
回答9:
Maybe just name it AddCustomerToList, and don't make it check to see if its already there, instead at the end, call another method, RemoveMultipleOccurences(..).
回答10:
You didn't say what you do if it isn't there. Assuming the answer is "nothing", I'd go with.
bool InsertIfNew (CustomerList list, Customer customer)
The method returns true if it was "inserted", and false if it was already there. That the caller can perform alternate logic if the entry was already there. You might not want to do that, but someone might and you already have the knowledge inside the routine.
来源:https://stackoverflow.com/questions/1228758/good-name-for-a-method-that-adds-to-a-container-if-not-aleady-there