2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
Local variable type inference - Will it compile?
1. @mirocupak
Local variable type inference
-
Will it compile?
Miro Cupak
Co-founder & VP Engineering, DNAstack
November 02, 2019
2. @mirocupak 2
Best practices
• Does not replace static typing.
• Generally good - reduces boilerplate, improves readability, and helps with
maintenance and refactoring.
• Use for local variables with initializers (especially constructors) and for
loops.
• Use for complex types when breaking chained or nested expressions with
local variables.
• Can’t use for declarations without explicit initialization, null or array
initializers, compound declarations, method signatures, class fields, catch
formals, lambdas or method references.
3. @mirocupak 3
Best practices
• Consider whether to use when the generated type is not obvious.
• Primitive types might surprise you, be careful (e.g. byte, short, long all
inferred as int).
• Code to the interface pattern does not work, but that’s kind of OK.
• Be very careful about combining with <> and generic methods (e.g. var
list = new ArrayList<>()).
• Works with non-denotable types (e.g. intersection types), but be careful!
• Capture variables are projected to supertypes that do not mention capture
variables.
• Probably not the best idea to use with anonymous classes.
4. @mirocupak 4
Best practices
• Use carefully chosen and expressive variable names.
• Don’t use var as names of variables, methods, enums (even if it works).
• Don’t use Hungarian notation.
• Don’t rely on IDEs.
• Minimize the scope of local variables.
• Declare variable when it’s first used.
• Declaration not containing an initializer (i.e. you can’t use var) often
indicates the scope is not minimal.
• Prefer for loops to while loops.
• Keep methods small and focused.