Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In almost every case, when you think you have to create setter AND getter (that is, both at the same time), your design is wrong.</p> <p>Think instead what purpose has <code>num_chests</code>? You can't go anywhere without knowing what it is.</p> <p>By your code I'm guessing it contains the number of chests on the level. In that case you don't want to provide setter for this value for everyone. You want the value to be equal to the number of chests in the game, and by providing setter here everyone can invalidate that invariant.</p> <p>Instead, you can provide ONLY getter, and you can control it's value in your class.</p> <pre><code>class Chest : public GameObject { public: Chest() { ++num_chests_; } ~Chest() { --num_chests_; } static int num_chests() { return num_chests_; } private: static int num_chests_; }; int Chest::num_chests_ = 0; </code></pre> <p>More explanation about why getters and setters are wrong decision in my opinion. If you provide setter and getter, you only have illusion of control over variable. Consider <code>std::complex</code>. Why is </p> <pre><code>std::complex&lt;double&gt; my_complex(1.0, 5.0); my_complex.real(my_complex.real()+1); </code></pre> <p>better over</p> <pre><code>std::complex&lt;double&gt; my_complex(1.0, 5.0); my_complex.real()++; </code></pre> <p>The answer: when <code>std::complex</code> was designed, there were no references in C++. Also, Java doesn't have C++-style references, so they have to write boilerplate code everywhere. Now, GCC returns non-const references here as an extension, and C++11 allows</p> <pre><code>reinterpret_cast&lt;double (&amp;)[2]&gt;(non_const_non_volatile_complex_variable)[0] </code></pre> <p>and</p> <pre><code>reinterpret_cast&lt;double (&amp;)[2]&gt;(non_const_non_volatile_complex_variable)[1] </code></pre> <p>as a valid way to access real and imaginary parts of <code>std::complex&lt;value&gt;</code>.</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