Search code examples
scalajavabeans

Is it good practice to use @BeanProperty in Scala instead of defining getter/setter functions?


Defining data members in a class that can be publicly accessed/modified

var _foo: Int = _
def foo_(foo: Int) = _foo = foo    // setter function
def foo = _foo                     // getter function

Is it a good practice to convert this using annotation @BeanProperty?

import scala.reflect.BeanProperty
@BeanProperty var foo: Int = _

and when to use this annotation and when not to?


Solution

  • There's some redundancy in your first example, since defining a var already results in the generation of getters and setters. For example, if we compile this class:

    class Foo {
      var foo: Int = _
    }
    

    Then javap -private Foo shows the following:

    public class Foo {
      private int foo;
      public int foo();
      public void foo_$eq(int);
      public Foo();
    }
    

    Unless you have custom logic that you need to fit into your getters or setters (in which case it's often a good idea to consider more descriptive method names, anyway), you shouldn't need to define them manually.

    The scala.reflect.BeanProperty annotation (or scala.beans.BeanProperty on 2.11) doesn't have any effect on the generation of the foo() and foo_$eq(int) methods—the compiler will generate these for a var foo: Int whether or not you use the annotation. The annotation simply adds getFoo and setFoo aliases for these methods. If you need these aliases, use the annotation, and if you don't, don't.

    To summarize best practices:

    1. Don't use var.
    2. If you have to use var, you can (and should) avoid defining your own getters and setters.
    3. Use the BeanProperty annotation only if you're implementing an interface with getFoo and setFoo-style method signatures, or if you're expecting your code to be called from Java (where calling methods with names like foo_$eq is inconvenient).