Declaring Final Variables Elegantly Using The Assigner Design Pattern
Join the DZone community and get the full member experience.Join For Free
a final variable is used to define a constant value and reference, and can only be defined once. in most cases, declaring a final variable is just a matter of assigning to a primitive value or an object reference directly. however, in some cases, declaring a final class/instance variable may be more involving especially it gets assigned from a method that throws an exception (eg api for database access, web access), or it may involve multiple statements.
editors note: this content was submitted by geekycoder
in such cases, the code may become cluttered with class helper methods and dummy temporary variables that help define the final variable, making the code look less elegant and harder to maintain. the following common ways of declaring a final variable in those situations might look familiar to many.
declaring final variable by instance/class method
declaring final variable by instance/class variable with static/instance initializer.
the aforementioned ways definitely get the work done but at the cost of elegancy. the helper method and variable help to define the final variable but it inevitably becomes part of class method and variable.
recommended way: assigner design pattern
a better way to declare final instance/class variable is to use generic method and interface with the advantages of
- forcing initializing method in the same statement as the final variable declaration.
- reusing as design pattern (term: assigner design pattern) and enhancing code readability
there is generic helper class whose interface and method accept a parametric type similar to the type of final variable. the advantage of using generics is that the type mismatch will be caught at compile time rather than runtime. this design pattern is termed assigner because it assigns value to a variable from initializing method.
using the design pattern, the code becomes cleaner and elegant.
the above can be downloaded - assigner.zip (1kb)
some will probably argue that assigner design pattern may not be efficient compare to the first two ways since additional bytecode classes are generated for assigner helper class and inner class. however, like other design patterns, code readability and reusability may outweigh the negligible performance loss and inefficiency.
Opinions expressed by DZone contributors are their own.