2

Possible Duplicate:
Private vs. Public members in practice (how important is encapsulation?)

Recently I've been coming across a situation where I declare a class variable as public, because it will be used in another class. Someone told me recently that I should make such variables private and write a public method returning the value of the variable. I was told this was good practice. I searched through my Java book and couldnt find any reference to this. My question is, is it good practice to declare as many as possible class variables as private?

Community
  • 1
  • 1
  • 1
    Sure, I always start by declaring *all of them* private. Most of the time they stay so. This means more writing, but your IDE helps you. Threre's also "project lombok", which generates the accessors for you when you annotate the field or the class. – maaartinus Jan 23 '11 at 15:04

1 Answers1

4

Yes. Generally, all variables should be private (not protected, private), and there should be methods to get their values (and possibly set them) if (and only if) you want to allow that by outsiders. The variables you use are an implementation detail, and usually contain data that has to be a certain way. Getters and setters allow you to take responsibility for that data, validate it, synchronize it, etc, instead of letting some jackass store random stuff in it and potentially make your object unusable.

The sole exception might be classes whose only purpose is storage of data so you can ship it around as one object, kinda like a C/C++ struct. But then, you're making a decision that no, you don't want to validate, synchonize, encapsulate that data in any way...and changing your mind later breaks binary compatibility (meaning any code that touched that class will need to be recompiled). Not a big deal in a little private project; huge deal in a public framework/API.

cHao
  • 84,970
  • 20
  • 145
  • 172