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

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?

Change CustomerList to CustomerSet, then it's obvious.
add(CustomerSet set, Customer customer);

AddIfNotPresent

bool TryAdd(CustomerList list, Customer customer)

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 );
}
}
}

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).

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.

Make it two methods. IsCustomerPresent() AddCustomer(). Then if you want you could make a AddCustomerIfNotAlreadyPresent() method that just calls your loosely coupled logic.

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.

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(..).

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.

Related

Overloading a method with a difference of list/array of type . Is that a good practice?

I have a method in businessservice as follows,
public void ProcessModelId(int modelId){
//method logic for a modelid....
}
Now the requirement is to send list of ids, so should i modify existing method or can i overload another method wit list of ids? like below?
public void ProcessModelIds(List<int> modelIds){
foreach(var i in modelIds){//method logic for each modelid....}
}
which one is a good practice in design perspective?
or that doesn't matter at all?
Depending on the requirement, if you no longer have to pass single integer modelId to the function, then it is advisable to modify the existing function as there is no reason to overload it and have redundant code that is never used.
On the other hand, if you want to have the choice of passing an int or a List<int>, overloading would be the way to go. Although, personally, I'd just modify the existing function, as even if you want to pass just a single integer, you can still pass it as a list with just one element.

Should I check whether a method is executed inside or outside of the method itself?

I have a method which should be executed if a boolean is true.
The normal way to achieve this would be:
private void OneMethod() {
if (ShouldExecute)
OtherMethod();
}
private void OtherMethod() {
Do Stuff...
}
Note that the varibale "ShouldExecute" is a global variable of the class.
But a colleague of mine recently started to put the if into the method itself.
So now it looks like this:
private void OneMethod() {
OtherMethod(ShouldExecute);
}
private void OtherMethod(bool shouldExecute) {
if (shouldExecute) {
Do Stuff...
}
}
He argues that the decision, whether the method should be executed, is a function of the method itself and thus should be a part of the method.
While i can see where he is coming from i still don't like his way. I think it just seems wrong and confusing.
If I see something like this:
var list = FilterList(list, otherParameter, yetAnotherParameter, shouldExecute);
I wouldn't read all of the parameters if they don't particually interest me. I would assume, that the list is somehow filtered by some parameters. Always.
But my argument "it feels wrong" is a pretty bad argument.
His way may clash with "Seperation of concerns" or the "Single responsibility principle" as well, which would be a stronger argument, but I'm not sure if that is the case.
But i really couldn't find any strong evidence for either of the two standpoints. And i don't really know what to search for, either...
So maybe someone here knows which way is more in line with the object-oriented programming paradigm.
And my goal is not to proof my colleague wrong, although i would be happy if were right, of course. :)
My goal is to find a good base on which we can create a policy for this case in our company's programming standards.
Thank you for your help.
I'll answer your concern describing a real-world case.
You go to your workplace and a policeman stops you. And you tell him:
hey agent, do I surpassed the maximum speed on this road?
That policeman would think that you're laughable, because if you were aware of your infraction, why you did it? And, anyway, he would fine your anyway!
Usually rules are defined by who's not the target of the whole rule (excepting when we talk about laws which should be fulfilled by any person in your country).
For me, a method isn't responsible of knowing if it should be executed, but it's a responsibility of the caller, because the same method should be callable by other methods and those may have other conditions to decide if some method should be called or not.
This way (the one your colleague proposes) you add a function to the call stack that basically does nothing if boolean value is false. The method should be called only if it has to be really executed to avoid a memory abuse.
About "separation of concerns" is your colleague to be in fault, as the called function shouldn't know "why" it has been called
I don't think it's sensible to have a parameter to determine whether the logic of a method is executed or not. As much as possible, a method should be considered a piece of logic that always carries out the same task (for different parameters). As suggested in Clean Code, if you have boolean parameters that significantly change the behaviour of a method, maybe it should be a different method.
As a rule of thumb, I would say that if the documentation ends up being something like "This method does X, unless parameter P takes value V, in which case it does Y" (maybe excepting null or empty values in some cases) it probably means that there should be different methods and the caller should be more explicit about what needs to be done.
From the following code it seems that OtherMethod is already following Single Responsibility Principle, i.e it is doing things for which it is meant for. But use of ShouldExecute inside OneMethod is hiding some thing from the one who calls OneMethod.
private void OneMethod()
{
if (ShouldExecute)
OtherMethod();
}
private void OtherMethod()
{
Do Stuff...
}
When a method expects some parameter the caller of that function knows that the parameter has some relevance in working of that function. So following code is more descriptive. But again if all the stuff OtherMethod is going execute only depends upon its parameter shouldExecute then why call the method itself. In such case previous code is better.
private void OneMethod()
{
OtherMethod(ShouldExecute);
}
private void OtherMethod(bool shouldExecute)
{
if (shouldExecute)
{
//Do Stuff...
}
}
Finally, this will be better, maintaining SRP as well as not hiding anything from the caller of OneMethod:
private void OneMethod(bool _bShouldExecute)
{
if (_bShouldExecute)
OtherMethod();
}
private void OtherMethod()
{
Do Stuff...
}

NHibernate: How to check if an entity is persistent

I find myself writing code like the following quite a lot:
if (myEntity.Id == default(Guid))
Session.Save(myEntity);
What is the best way to check if an entity is already persistent (and therefore doesnt need to be saved)?
Am I doing something wrong writing code like this?
That's what I do except I usually use an IsNew() or IsTransient() method in a base class or extension that performs this check. Then the code becomes:
public Boolean IsTransient(){
return this.Id == default(Guid);
}
Don't forget that the Session.SaveOrUpdate(entity) method will cause an update of a persisted entity (as opposed to an insert) so you could use this method and ignore the check. I prefer to do the check though.

How to name a method that has an out parameter?

What is the common preference to name a method that has an out parameter inside?
Usually I use Get as a prefix to mention that the method returns a value (like GetMyBusiness).
But what if there is an out parameter that will be set after the method call?
Should the method name mention this and focus only the return value?
thanks!
There is no standard in nomenclature. However, if your method is going to be acting on compound types, consider adopting a convention of using Get...And...() to indicate that there are two things going on. For example:
int GetPopulationAndMeanAge(out double meanAge)
{
// ...
meanAge = CalculateMeanAge();
return totalPopulation;
}
I think the better approach is to return a compound type instead. In a garbage collected language, there is really no excuse NOT to do this, except in cases where such a method is called, say, millions of times and instrumentation reveals that the GC isn't properly handling the load. In non-GC languages, it presents a minor issue in terms of making sure that it's clear who is responsible for cleaning up the memory when you're done.
Refactoring the previous into a compound type (C#):
public class PopulationStatistics {
int Population { get; set; }
double MeanAge { get; set; }
}
PopulationStatistics GetPopulationStatistics()
{
// ...
return new PopulationStatistics { Population = totalPopulation, MeanAge = CalculateMeanAge };
}
The method name should describe the function of the method (self-documenting code). If the method signature will indicate that it uses an out parameter, the signature should be sufficient to alert developers that a value will be returned in the variable. I would consider it to be redundant, therefore, to include this in the method name. Even self-documenting code should be clear and concise. If your language doesn't make this clear then I would either document it in the name, if it can be done clearly and concisely, or using inline comments.
Why not return that parameter instead?
Anyway, you could use "modify" or "handle" prefix.
I'd say in this case it's more important to keep your naming consistent rather than what your naming scheme actually is. It makes things easier for those who code behind you, since they will know what to expect from your methods based on how they're named.
Having said that, Get should be just fine.
That depends on the language.
In C#, for example, there's no need to add it to the name of the function, it's already in the signature: you cannot call the function without specifying out again, so there's no risk of missing the side effect:
Int32.TryParse("123", out number);

how do you call this anti-pattern?

In the database you have a table with a bit field, let call that field Active
In the application you have a variable boolean, let call it NotActive
Everytime you get the field from the table, in the application you have switch the meaning of the variable.
NotActive = !mytable.active;
Another example would be a bit field in the database named Enable__yes__no and in the code you do
control.enabled = !mytable.Enable_yes_no
best practice would be to keep the same name and the same meaning, but the pattern above, how to you call that?
I wouldn't name boolean variables with a negative prefix.
Name the variable IsActive or Active, naming it NotActive is double negation.
Edit/Clarification:
If you need to check if the thing is active, you need a double negation:
If (!NotActive) { DoSomething() }
Positive boolean Variable names are much easier to understand:
If (isActive) { DoSomething() }
Obfuscation by design?
Backward compatibility with existing databases?
It's widely known as the "not-not-negative spaghetti confusion pattern" and was first mentioned 1972. ;-) SCNR
I think the problem here is in the architecture, not in the specific naming of the data. For instance, if you used an entity framework, then your entity for this table could declare a property called InActive, and it could use the Active column as the datastore. As far as the outside world is concerned, the translation back and forth is transparent.