Hacker News new | ask | show | jobs
by vbezhenar 2228 days ago
With Java I've seen coding standards that you can use `var` only when type is obvious from declaration. For example:

    var person = new Person();
    var car = selectCarById(carId); // Car
if type is not obvious, it should be explicitly declared.
3 comments

I'd avoid the second example since you'd need to know the return type of selectCarById to know what the actual type that will be returned is (the name doesn't help, it might return something like, say, a "ref<Car>" or something like that - e.g. in a game engine i worked on a couple of years ago all resource pointers were passed around encapsulated in a special template that handled automatic resource management - methods would still be called something like "GetMesh" but what you'd get wouldn't be a "Mesh" but a "TResRef<Mesh>", however since in other places in the engine you'd work with "raw" Mesh types, unless you knew what GetMesh returned - which could be the case for, e.g., some programmer that normally worked with at a completely different subsystem with its own rules - you'd might expect a "auto mesh = foo->GetMesh()" to be a "Mesh" but instead it is "TResRef<Mesh>").
This is also common in the C++ community. Clang-tidy has an auto fix for this that can be applied to code bases.
I sometimes see people stating exactly this, but then writing:

`doSomethingToACar(selectCarById(carId));`

Kind of weakens the argument. I'm not sure what's the best approach, but I'm usually ok with autos even when the type is not explicitly known - when reading code, I do not really need to know what exact type a variable has ("it's a car, goddamnit, it says so in the name!"), just how it's used (and then meaningful function names become very important).