Return to site

Java 10 local type inference guidelines (var)

· java,mashup

Choose good variable names

Before:

List<Customer> x = dbconn.executeQuery(query);

After with var:

Right: var custList = dbconn.executeQuery(query);

Wrong: var x = dbconn.executeQuery(query);

Minimize local variable scope

Wrong:

var items = new HashSet<Item>(...);

// ... 100 lines of code ...

for (var item : items) ...

Right:

var items = new HashSet<Item>(...);

// ... 3 lines of code ...

for (var item : items) ...

Use good initializer information

Before:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

With var:

//Right:

var outputStream = new ByteArrayOutputStream();

//Wrong:

var reader = fetch();

Break up chained expressions in logical places

Before:(Verbose type names lead to no interim vars, and reduced readability)

return strings.stream()

.collect(groupingBy(...)

.entrySet()

.stream()

.max(...)

.map(...);

With var:

var freqMap = strings.stream()

.collect(...);

var maxEntryOpt = freqMap.entrySet()

.stream()

.max(...);

return maxEntryOpt.map(...);

Don't worry about "programming to the interface" with vars

Before:

List<String> list = new ArrayList<>();

With var:

// ArrayList<String> is inferred

var list = new ArrayList<String>();

Take care with <> or generic methods

Before:

PriorityQueue<Item> itemQueue = new PriorityQueue<>();

With var:

//Right:

// PriorityQueue<Item> is inferred

var itemQueue = new PriorityQueue<Item>();

//Wrong:

// PriorityQueue<Object> is inferred

var itemQueue = new PriorityQueue<>();

Take care with literals

Good inferring with var:

//before

boolean ready = true;

//Inferred type, with var:

boolean

//before

char ch = '\ufffd';

//Inferred type, with var:

char

//before
long sum = 0L;
//Inferred type, with var:

long

//before
String label = "wombat";
//Inferred type, with var:
String

Wrong inferring with var:

//before

byte fags=0;

//Inferred type, with var:

(int)

//before

short mask = 0x7fff;

//Inferred type, with var:

(int)

//before

long base=17;

//Inferred type, with var:

(int)

All Posts
×

Almost done…

We just sent you an email. Please click the link in the email to confirm your subscription!

OK