<p>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?</p>

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

<p>Java:</p>

<pre><code>String property = this.property;
</code></pre>

<p>PHP:</p>

<pre><code>$property = $this-&gt;property;
</code></pre>

<p>or would you do:</p>

<p>Java:</p>

<pre><code>String property = this.getProperty();
</code></pre>

<p>PHP:</p>

<pre><code>$property = $this-&gt;getProperty();
</code></pre>

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

<p><strong>EDIT:</strong></p>

<p>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...</p>

[{'answer_id': 127, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 7, 'selected': True, 'text': "<p>This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that <em>needs</em> to run every time that property is set, and the property is being set internally w/o that setter being called).</p>\n"}, {'answer_id': 128, 'author': 'Shawn', 'author_id': 26, 'author_profile': 'https://Stackoverflow.com/users/26', 'pm_score': 4, 'selected': False, 'text': "<p>It depends on how the property is used. For example, say you have a student object that has a name property. You could use your Get method to pull the name from the database, if it hasn't been retrieved already. This way you are reducing unnecessary calls to the database.</p>\n\n<p>Now let's say you have a private integer counter in your object that counts the number of times the name has been called. You may want to not use the Get method from inside the object because it would produce an invalid count.</p>\n"}, {'answer_id': 139, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 4, 'selected': False, 'text': '<blockquote>\n  <p>Am I just going overboard here?</p>\n</blockquote>\n\n<p>Perhaps ;)</p>\n\n<p>Another approach would be to utilize a private/protected method to actually do the getting (caching/db/etc), and a public wrapper for it that increments the count:</p>\n\n<p>PHP:</p>\n\n<pre><code>public function getName() {\n    $this-&gt;incrementNameCalled();\n    return $this-&gt;_getName();\n}\n\nprotected function _getName() {\n    return $this-&gt;name;\n}\n</code></pre>\n\n<p>and then from within the object itself:</p>\n\n<p>PHP:</p>\n\n<pre><code>$name = $this-&gt;_getName();\n</code></pre>\n\n<p>This way you can still use that first argument for something else (like sending a flag for whether or not to used cached data here perhaps).</p>\n'}, {'answer_id': 142, 'author': 'Coincoin', 'author_id': 42, 'author_profile': 'https://Stackoverflow.com/users/42', 'pm_score': 3, 'selected': False, 'text': "<p>Well, it seems with C# 3.0 properties' default implementation, the decision is taken for you; you HAVE to set the property using the (possibly private) property setter.</p>\n\n<p>I personally only use the private member-behind when not doing so would cause the object to fall in an less than desirable state, such as when initializing or when caching/lazy loading is involved.</p>\n"}, {'answer_id': 143, 'author': 'svrist', 'author_id': 86, 'author_profile': 'https://Stackoverflow.com/users/86', 'pm_score': 3, 'selected': False, 'text': "<p>As stated in some of the comments: Sometimes you should, sometimes you shouldn't. The great part about private variables is that you are able to see all the places they are used when you change something. If your getter/setter does something you need, use it. If it doesn't matter you decide.</p>\n\n<p>The opposite case could be made that if you use the getter/setter and somebody changes the getter/setter they have to analyze all the places the getter and setter is used internally to see if it messes something up.</p>\n"}, {'answer_id': 169, 'author': 'MojoFilter', 'author_id': 93, 'author_profile': 'https://Stackoverflow.com/users/93', 'pm_score': 5, 'selected': False, 'text': "<p>Personally, I feel like it's important to remain consistent.  If you have getters and setters, use them.  The only time I would access a field directly is when the accessor has a lot of overhead.  It may feel like you're bloating your code unnecessarily, but it can certainly save a whole lot of headache in the future.  The classic example:</p>\n\n<p>Later on, you may desire to change the way that field works.  Maybe it should be calculated on-the-fly or maybe you would like to use a different type for the backing store.  If you are accessing properties directly, a change like that can break an awful lot of code in one swell foop.</p>\n"}, {'answer_id': 3485, 'author': 'Telcontar', 'author_id': 518, 'author_profile': 'https://Stackoverflow.com/users/518', 'pm_score': 3, 'selected': False, 'text': "<p>I can be wrong because I'm autodidact, but I NEVER user public properties in my Java classes, they are always private or protected, so that outside code must access by getters/setters. It's better for maintenance / modification purposes. And for inside class code... If getter method is trivial I use the property directly, but I always use the setter methods because I could easily add code to fire events if I wish.</p>\n"}, {'answer_id': 14968, 'author': 'Brendon-Van-Heyzen', 'author_id': 1425, 'author_profile': 'https://Stackoverflow.com/users/1425', 'pm_score': 3, 'selected': False, 'text': "<p>i've found using setters/getters made my code easier to read. I also like the control it gives when other classes use the methods and if i change the data the property will store.</p>\n"}, {'answer_id': 14980, 'author': 'Mel', 'author_id': 1763, 'author_profile': 'https://Stackoverflow.com/users/1763', 'pm_score': 3, 'selected': False, 'text': "<p>Private fields with public or protected properties.  Access to the values should go through the properties, and be copied to a local variable if they will be used more than once in a method.  If and ONLY if you have the rest of your application so totally tweaked, rocked out, and otherwise optimized to where accessing values by going through their assosciated properties has become a bottleneck (And that will never EVER happen, I guarantee) should you even begin to consider letting anything other than the properties touch their backing variables directly.</p>\n\n<p>.NET developers can use automatic properties to enforce this since you can't even see the backing variables at design time.</p>\n"}, {'answer_id': 22083, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 3, 'selected': False, 'text': '<p>If you mean &quot;most encapsulation&quot; by &quot;purist&quot;, then I typically declare all my fields as private and then use &quot;this.field&quot; from within the class itself. For other classes, including subclasses, I access instance state using the getters.</p>\n'}, {'answer_id': 22111, 'author': 'Ross', 'author_id': 2025, 'author_profile': 'https://Stackoverflow.com/users/2025', 'pm_score': 3, 'selected': False, 'text': "<p>If I don't edit the property, I'll use a public method <code>get_property()</code> unless it's a special occasion such as a MySQLi object inside another object in which case I'll just make the property public and refer to it as <code>$obj-&gt;object_property</code>.</p>\n<p>Inside the object it's always $this-&gt;property for me.</p>\n"}, {'answer_id': 62045, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I like the answer by <a href="https://stackoverflow.com/questions/126/how-would-you-access-object-properties-from-within-an-object-method#132">cmcculloh</a>, but it seems like the most correct one is the answer by <a href="https://stackoverflow.com/questions/126/how-would-you-access-object-properties-from-within-an-object-method#127">Greg Hurlman</a>. Use getter/setter all the time if you started using them from the get-go and/or you are used to working with them.</p>\n<p>As an aside, I personally find that using getter/setter makes the code easier to read and to debug later on.</p>\n'}, {'answer_id': 98244, 'author': 'moffdub', 'author_id': 10759, 'author_profile': 'https://Stackoverflow.com/users/10759', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m fairly surprised at how unanimous the sentiment is that <code>getters</code> and setters are fine and good. I suggest the incendiary article by Allen Holub "<a href="http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html" rel="noreferrer">Getters And Setters Are Evil</a>". Granted, the title is for shock value, but the author makes valid points.</p>\n\n<p>Essentially, if you have <code>getters</code> and <code>setters</code> for each and every private field, you are making those fields as good as public. You\'d be very hard-pressed to change the type of a private field without ripple effects to every class that calls that <code>getter</code>.</p>\n\n<p>Moreover, from a strictly OO point of view, objects should be responding to messages (methods) that correspond to their (hopefully) single responsibility. The vast majority of <code>getters</code> and <code>setters</code> don\'t make sense for their constituent objects;<code>Pen.dispenseInkOnto(Surface)</code> makes more sense to me than <code>Pen.getColor()</code>.</p>\n\n<p>Getters and setters also encourage users of the class to ask the object for some data, perform a calculation, and then set some other value in the object, better known as procedural programming. You\'d be better served to simply tell the object to do what you were going to in the first place; also known as the <a href="http://en.wikipedia.org/wiki/GRASP_%28object-oriented_design%29#Information_Expert" rel="noreferrer">Information Expert</a> idiom.</p>\n\n<p>Getters and setters, however, are necessary evils at the boundary of layers -- UI, persistence, and so forth. Restricted access to a class\'s internals, such as C++\'s friend keyword, Java\'s package protected access, .NET\'s internal access, and the <a href="http://moffdub.wordpress.com/2008/09/17/friend-classes-in-java-and-c-sharp/" rel="noreferrer">Friend Class Pattern</a> can help you reduce the visibility of <code>getters</code> and setters to only those who need them.</p>\n'}, {'answer_id': 128396, 'author': 'Martin Spamer', 'author_id': 15527, 'author_profile': 'https://Stackoverflow.com/users/15527', 'pm_score': 3, 'selected': False, 'text': '<p>The question doesn\'t require an opinion based answer. It is a subject well covered by computing science for decades from the principle of high <a href="https://en.wikipedia.org/wiki/Cohesion_(computer_science)" rel="nofollow noreferrer">cohesion</a>, low <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)" rel="nofollow noreferrer">coupling</a> and the <a href="https://en.wikipedia.org/wiki/SOLID" rel="nofollow noreferrer">SOLID principles</a>.</p>\n<p>The <em>purist</em>, read correct, OO way is to minimise coupling and maximise cohesions. Therefore both should be avoided and the <a href="https://en.wikipedia.org/wiki/Law_of_Demeter" rel="nofollow noreferrer">Law of Demeter</a> followed by using the <a href="http://c2.com/cgi/wiki?TellDontAsk" rel="nofollow noreferrer">Tell Don\'t Ask</a> approach.</p>\n<p>Instead of getting the value of the object\'s property, which <a href="https://stackoverflow.com/questions/2832017/what-is-the-difference-between-loose-coupling-and-tight-coupling-in-object-orien">tightly couples</a> the two class, use the object as a parameter e.g.</p>\n<pre><code>  doSomethingWithProperty() {\n     doSomethingWith( this.property ) ;\n  }\n</code></pre>\n<p>Where the property was a native type, e.g. int, use an access method, name it for problem domain not the programming domain.</p>\n<pre><code>  doSomethingWithProperty( this.daysPerWeek() ) ;\n</code></pre>\n<p>These will allow you to maintain encapsulation and any post-conditions or dependent invariants. You can also use the setter method to maintain any pre-conditions or dependent invariants, however don\'t fall into the trap of naming them setters, go back to the Hollywood Principle for naming when using the idiom.</p>\n'}, {'answer_id': 128488, 'author': 'Unlabeled Meat', 'author_id': 20291, 'author_profile': 'https://Stackoverflow.com/users/20291', 'pm_score': 4, 'selected': False, 'text': "<p>PHP offers a myriad of ways to handle this, including magic methods <code>__get</code> and <code>__set</code>, but I prefer explicit getters and setters. Here's why:</p>\n\n<ol>\n<li>Validation can be placed in setters (and getters for that matter)</li>\n<li>Intellisense works with explicit methods</li>\n<li>No question whether a property is read only, write only or read-write</li>\n<li>Retrieving virtual properties (ie, calculated values) looks the same as regular properties </li>\n<li>You can easily set an object property that is never actually defined anywhere, which then goes undocumented </li>\n</ol>\n"}, {'answer_id': 157081, 'author': 'Steve McLeod', 'author_id': 2959, 'author_profile': 'https://Stackoverflow.com/users/2959', 'pm_score': 3, 'selected': False, 'text': "<p>It depends. It's more a style issue than anything else, and there is no hard rule.</p>\n"}, {'answer_id': 2099971, 'author': 'Aadith Ramia', 'author_id': 122466, 'author_profile': 'https://Stackoverflow.com/users/122466', 'pm_score': 3, 'selected': False, 'text': '<p>It is better to use the accessor methods, even within the object. Here are the points that come to my mind immediately:</p>\n<ol>\n<li><p>It should be done in the interest of maintaining consistency with accesses made from outside the object.</p>\n</li>\n<li><p>In some cases, these accessor methods could be doing more than just accessing the field; they could be doing some additional processing (this is rare though). If this is the case, accessing the field directly would mean that you are missing that additional processing, and your program could go awry if this processing is always to be done during those accesses.</p>\n</li>\n</ol>\n'}, {'answer_id': 6237699, 'author': 'Egg Vans', 'author_id': 783844, 'author_profile': 'https://Stackoverflow.com/users/783844', 'pm_score': 4, 'selected': False, 'text': "<p>I must be missing the point here, why would you use a getter inside an object to access a property of that object?</p>\n\n<p>Taking this to its conclusion the getter should call a getter, which should call a getter.</p>\n\n<p>So I'd say inside an object method access a property directly, especially seeing as calling another method in that object (which will just access the property directly anyway then return it) is just a pointless, wasteful exercise (or have I misunderstood the question).</p>\n"}]
['https://Stackoverflow.com/questions/126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58/']