good name for a method that adds to a container if not aleady there

给你一囗甜甜゛ 提交于 2019-12-08 04:57:25

问题


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 present
  • AddIfNotPresent or PutIfNotPresent 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!