Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unless you perform some kind of validation when setting the values (i.e. balance is not negative), use <code>public</code> if possible. </p> <p>Creating both a getter and a setter for an attribute that merely return or assign a value, without additional logic actually exposes your attribute as <code>public</code> and provide unnecessary clutter to the code (in terms of readability). Using public attributes directly makes the code cleaner.</p> <p><strong>Example 1:</strong></p> <p>*You want to allow an account to only have positive balance. You will have to perform a check to see if you are assigning it a negative value EVERY time you assign it a value. </p> <p>The best place to do this would be in a setter method. This gets you rid of the trouble of having to put a lot of <code>if(newBalance &lt; 0)</code> checks all over the place. </p> <p>To enforce the fact that you want only positive balance values, you make the attribute <code>private</code>. This restricts the programmers who might want to assign a negative value to a <code>balance</code> attribute(*). In order to make the value held within the balance attribute accessible again, you would need to add a getter for the private value. </p> <p>You now have "some kind" of a <code>public</code> attribute on which you enforce restrictions (not being able to be set as negative).</p> <p><strong>Example 2:</strong></p> <p>You want to take notes on every account. You will have a <code>String notes;</code> attribute in your class. </p> <p>If there are not restrictions you want to enforce, the best here is to use <code>public</code> modifier for it.</p> <p>Consider which of the following pieces of code is cleaner:</p> <pre><code>accountA.setNotes(accountB.getNotes()); </code></pre> <p>or</p> <pre><code>accountA.notes = accountB.notes; </code></pre> <p>They both copy <code>notes</code> from one account to the other, but the latter is easier to read.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload