Consider the following code:
public class Car {
public string name;
public string owner;
public string id;
public Car(string name, string owner) {
this.name = name;
this.owner = owner;
id = GenerateId(name);
}
private static string GenerateId(string name) {
//do some fancy computation to derive the ID from the name, such as hash it or anything else.
return result;
}
}
The important bit is that GenerateId is a static function here that explicitly takes an argument.
Now, let us consider the following, where GenerateId is made into an instance function that takes no arguments explicitly, instead just references the instance field it needed.
public class Car {
public string name;
public string owner;
public string id;
public Car(string name, string owner) {
this.name = name;
this.owner = owner;
GenerateId(name);
}
private void GenerateId() {
//do some fancy computation to derive the ID from the name, such as hash it or anything else.
string computation_result = fancy_computation(this.name);
this.id = computation_result;
}
}
Another approach would be an instance method that references the id field directly, but needs the "name" string as an argument anyway.
Which is the "more proper" approach that an experienced programmer would follow? Why?
My current thoughts are:
- If we think GenerateId is always going to be called with name as the argument (and in the future it most likely won't change), it's safe to just reference the name field instead of passing it as the string argument. However, if we expect at some point we will want to compute the ID using the owner string as the base, we can in advance design the function to take a string argument.
- I've heard multiple times that 'a function should take as few arguments as possible'.
The more I think about it, the more it seems to be a question of "how generic should we make this function?" that isn't decided by the OOP rules, but simply on a case-by-case basis: ask yourself whether you're gonna need a more generic version, or if the function both now and in the future is most likely to do only this one thing, so you're free to 'hardcode' it in, instead of writing more code to make it more generic.
GenerateIdif you do not have an instance ofCar? Yes, then make it static. No, make it non static.