- Java 11 and 12:New Features
- Mala Gupta
- 354字
- 2021-07-02 12:27:01
Limiting the scope of failed assumptions
As you know, the use of var types is limited to local variables in Java. They are not allowed in the public API, as method parameters or as the return type of methods. Some languages support type inference for all types of variables. Java may allow us to do so in the future, but we don't know when.
However, there are strong reasons for limiting the scope of the inferred variables, to spot the errors due to mismatch of assumptions and the actual, early on. The contracts of the public APIs should be explicit. Type inference with public APIs would allow for these errors to be caught and corrected much later.
The following is a practical example of how a mismatch between an assumption and the actual case can lead to errors.
Recently, my daughter was traveling overseas with her school for a student exchange program. The school asked me to send back a set of photographs for her visa application. I called a photographer, requesting that he print photos for the visa (and specifying the country). Two days later, the school asked me to resubmit the photos because they didn't match the rules.
What went wrong? Neither the school nor myself were explicit with the specifications of the photograph. The school assumed that I would know the specifications; I assumed that the photographer would know the specifications (because he had been doing it for years). In this case, at least one person assumed that the result conformed to a specific output, without explicitly specifying the output. Without an explicit contract, there is always the chance of mismatching the expectation with the actual case.
Despite the confusion, the mistake was spotted and corrected before the applications were submitted to the embassy.
The following is a fun image, included showing why the use of type inference is limited to local variables. The local instances and static variables are competing in a race, and only the local variables can make it to the finish line:

- Machine Learning with R Cookbook(Second Edition)
- PowerCLI Cookbook
- 程序員修煉之道:通向務實的最高境界(第2版)
- C#程序設計
- Spring Boot進階:原理、實戰與面試題分析
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(1)
- Android項目實戰:手機安全衛士開發案例解析
- ServiceNow:Building Powerful Workflows
- 移動互聯網軟件開發實驗指導
- Python 3 數據分析與機器學習實戰
- 并行編程方法與優化實踐
- ASP.NET Web API Security Essentials
- Learning Grunt
- Mastering Unity 2017 Game Development with C#(Second Edition)
- 軟件自動化測試實戰解析:基于Python3編程語言