When should a private method take the public route to access private data? For example, if I had this immutable 'multiplier' class (a bit contrived, I know):
class Multiplier {
public:
Multiplier(int a, int b) : a(a), b(b) { }
int getA() const { return a; }
int getB() const { return b; }
int getProduct() const { /* ??? */ }
private:
int a, b;
};
There are two ways I could implement getProduct
:
int getProduct() const { return a * b; }
or
int getProduct() const { return getA() * getB(); }
Because the intention here is to use the value of a
, i.e. to get a
, using getA()
to implement getProduct()
seems cleaner to me. I would prefer to avoid using a
unless I had to modify it. My concern is that I don't often see code written this way, in my experience a * b
would be a more common implementation than getA() * getB()
.
Should private methods ever use the public way when they can access something directly?
Aucun commentaire:
Enregistrer un commentaire