Guys I have a "best practice question" For example I have this classes:
class Person
{
public int age {get; set;}
}
class Computer
{
public void checkAge(Person p) // Which one is recommended THIS
{
// Do smthg with the AGE
}
public void checkAge(int p) // OR THIS
{
//Do smthg with the age.
}
}
What is recommended to pass? Just what I need (int-value type) or the whole object (reference type)
Im asking this because Im using LINQ on an app that I am making and I have created many entities where I should pass the IDs (foreing keys), but Im passing objects.
What is the best approach?
Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.
The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.
An object variable is always a reference-type. Classes and string are reference type. Struct and enum are kind of value types.
Pass by reference means that you have to pass the function(reference) to a variable which refers that the variable already exists in memory. Here, the variable( the bucket) is passed into the function directly. The variable acts as a Package that comes with its contents(the objects).
The function checkAge
should only take in the minimum amount of information needed to perform it's job. Adding anything else just creates an artificial dependency. If only an int
is needed then that is the solution I should take.
I would argue that in this case, the answer is probably neither. Either "Age" would be factored out into its own class, or if the operation is context-specific with Person, it would be found inside the Person class itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With