Search code examples
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:

    • If you later introduce some logic when accessing/setting the variable, you can do it just in one place without the need to affect all the classes using the variable - you can easily add features as additional logging, lazy loading, security, validation, ...

    • You can later change the underlying representation of the field (eg return subtype in some cases)

    • You can later introduce lifecycle management of the returned object - eg. Return pooled/cached/singleton/.. object
    • You can later decide to return Proxy/decorated object instead without affecting callers

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