0

Possible Duplicate:
Java: Are Getters and Setters evil?

I have a class called Block with a simple boolean in it called inUse. For example in an if statement elsewhere in the program is it better to use a method called inUse() that returns the inUse boolean or just reference the variable with block.inUse

e.g.

if(block.inUse == true) // do something

or should I use

if(block.inUse()) //do something

where inUse() would be a simple return method in the block class

boolean inUse() {
   return inUse }

Thanks

Community
  • 1
  • 1

3 Answers3

2

Given that Java is usually implemented with a bytecode interpreter, questions of efficiency at this level are usually meaningless, since the overhead cost imposed by the interpreter will eat you alive, without salt or barbecue sauce.

The advantage of using a method, as opposed to granting access to the instance variable, is that it allows the programmer to control modification of the instance variable.

John R. Strohm
  • 7,547
  • 2
  • 28
  • 33
0

Using the value directly is certainly more efficient execution wise. But using a method is the best option. That is what OO and Java are all about, encapsulation of variables.

len
  • 335
  • 1
  • 5
  • Actually, OO (and information-hiding long before it) is about hiding implementation details that might change without changing the interface. Read "On the Criteria To Be Used in Decomposing Systems into Modules", by Parnas, at (for one example) http://sunnyday.mit.edu/16.355/parnas-criteria.html. – John R. Strohm Mar 15 '12 at 16:23
0

Depends on your jre, and it's JIT implementation. Many JIT compilers will end up inlining simple getters and setters once they get called often enough.

I personally have never been one for referencing member variables via methods. I realize that this is a matter of personal preference, but my general feeling is that an object shouldn't need to call a method to get (or set) it's own internal variables.

Matt
  • 11,523
  • 2
  • 23
  • 33