javaaccessorpackage-private

What is good practice to accessing package private variables?


What is good practice to access my package-private variables from other classes in this same package?

  1. Package-private accessor

    String getColor() {
        return color;
    }
    
  2. Just accessing as field from object.

    String color = instanceOfClass.color;
    

In my opinion:

  1. Package-private method for accessing package-private field. A lot of unnecessary code, but in my opinion provides clarity with a lot of fields (and properly named accessor methods)

  2. We don't need accessors and mutators for package-private variables in package, so maybe I shouldn't create them?

Which practice is better, consistent with the programming convention?

EDIT: Thank you for fast answers! :)


Solution

  • Having accessors/mutators is usually handy even if it is some more code:

    Generally, it is a good idea as it gives you more flexibility, preserves encapsulation and reduces coupling between objects.