82. Avoid using var if the called names don't contain enough type information for humans

Well, var is not a silver bullet, and this problem will highlight this once again. The following snippet of code can be written using explicit types or var without losing information:

// using explicit types
MemoryCacheImageInputStream is =
new MemoryCacheImageInputStream(...);
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = compiler.getStandardFileManager(...);

So, migrating the preceding snippet of code to var will result in the following code (the variables names have been chosen by visually inspecting the called names from the right-hand side):

// using var
var inputStream = new MemoryCacheImageInputStream(...);
var compiler = ToolProvider.getSystemJavaCompiler();
var fileManager = compiler.getStandardFileManager(...);

The same will happen at the border of over-naming:

// using var
var inputStreamOfCachedImages = new MemoryCacheImageInputStream(...);
var javaCompiler = ToolProvider.getSystemJavaCompiler();
var standardFileManager = compiler.getStandardFileManager(...);

So, the preceding code doesn't raise any issues in choosing the variable's names and readability. The called names contain enough information for humans to feel comfortable with var.

But let's consider the following snippet of code:

// Avoid
public File fetchBinContent() {
return new File(...);
}

// called from another place
// notice the variable name, bin
var bin = fetchBinContent();

For humans, it is pretty difficult to infer the type that's returned by the called name without inspecting the returned type of this name, fetchBinContent(). As a rule of thumb, in such cases, the solution should avoid var and rely on explicit types since there is not enough information on the right-hand side for us to choose a proper name for the variable and obtain highly readable code:

// called from another place
// now the left-hand side contains enough information
File bin = fetchBinContent();

So, if var in combination with the called names causes loss of clarity, then it is better to avoid the usage of var. Ignoring this statement may lead to confusion and will increase the time needed to understand and/or extend the code.

Consider another example based on the java.nio.channels.Selector class. This class exposes a static method named open() that returns a newly opened Selector. But if we capture this return in a variable declared with var, it's tempting to think that this method may return a boolean representing the success of opening the current selector. Using var without considering the possible loss of clarity can produce exactly these kinds of problems. Just a few issues like this one and the code will become a real pain.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset