0

I think that the title says it all. Maybe I should ask: Is it ever bad to not use a method to return the variable, or its value? An example would be a 2-d point class with an x and a y variable.

Is there anything wrong with using myPoint.x to get the x variable of myPoint as opposed to myPoint.xValue(), which simply returns mypoint.x?

Stuart M
  • 11,458
  • 6
  • 45
  • 59
  • Containment and readabilityitiveness would dictate the functional form, so I'd stick with that. –  Apr 18 '13 at 07:43

6 Answers6

5

Keep internals private, and provide access methods.

The outside world doesn't need to know the internals, and if you later change the internals, you can keep the API the same, and change what you want internally,so no external impact.

Much better to retrieve through a method.

Cliffordlife
  • 488
  • 5
  • 13
1

You should make your code, encapsulated, use setters and getters.

Set and Get Methods in java?

Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245
1

That entirely depends:

If you are creating a Point class that conforms to a JavaBeans Specification, then your variables will have to be private with relevant getters/setters method.

Also, if you are creating an API, then myPoint.x is not appropriate as you will like to create a application-by-contract, i.e. an interface with Point.getX(). That way, using the API, a developer knows that there is a Point that returns a x coordinate from a getX() method.

Ultimately it's up to your design. I prefer keeping encapsulate my variables to restrict access to my internals (such as variables).

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
0

Encapsulation is one of the feature in java.

Avoid accessing variables directly by making them private and provide proper accessors and mutators to update or retrieve those values.

So use methods to access those variable values and declare those variables as private.

Deepak
  • 327
  • 1
  • 7
0

Accessing with getter makes more safe. Many programmers protects their class variable with private keyword. I recommend to use getter and setter public methods.

Ugur Artun
  • 1,744
  • 2
  • 23
  • 41
0

good approch is follow encapsulation rule in Java.

providing private variables and public setters and getters.

for reference link

NPKR
  • 5,368
  • 4
  • 31
  • 48