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开发者_如何学JAVA 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);
精彩评论