标签云

微信群

扫码加入我们

WeChat QR Code

What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?

I know that from outside of the object you should use a getter/setter, but from within would you just do:

Java:

String property = this.property;

PHP:

$property = $this->property;

or would you do:

Java:

String property = this.getProperty();

PHP:

$property = $this->getProperty();

Forgive me if my Java is a little off, it's been a year since I programmed in Java...

EDIT:

It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...


isn't doing anything else in a setter other than setting the value of the property an example of wrong usage in Java.

2018年07月19日35分35秒

euphoria83 Perhaps, but that doesn't preclude it from happening.

2018年07月19日35分35秒

If the Student object is a business/domain object, you are now mixing infrastructure details. Ideally, a business/domain objects should be concerned only with business/domain logic.

2018年07月19日35分35秒

What if you add some sort of boolean to the getter like: PHP: public function getName($outsideCall = true){ if($outsideCall){ $this->incrementNameCalled(); } return $this->name; } and then from within the Object itself, if you called get name, you could keep it from incrementing by: PHP: $name = $this->getName(false); Am I just going overboard here?

2018年07月19日35分35秒

I was driven by the same need you had to comment... Plus it was answered not closed ;)

2018年07月19日35分35秒