Search code examples
c++oopvectorlaw-of-demeter

Law of demeter or return the whole vector


Which one is better:

public:
  const vector<int> & GetPointsVector();
private:
  vector<int> PointsVector;

Or:

public:
  int GetCurrentPoint();
  void MoveToFirstPoint();
  void MoveToNextPoint();
  bool IsAtLastPoint();
  size_t GetNumberOfPoints();
private:
  vector<int> PointsVector;

Solution

  • There is no right answer. The answer will vary with context, of which, at present we have very little.

    It depends on the clients of your class. In most situations you would not want a casual inspector to change the object's state, so it is better to a certain degree to return a reference to a const object. However, in such a case, I'd also make the function a const i.e.

     /* a design const - this accessor does not change the state */
     const vector<int> & GetPointsVector() const;
    

    This is also efficient since you are not passing around heavy objects as return values (it is a different question that most compilers do a RVO these days).

    If, your client needs to use the vector in algorithms, yes, you'd better provide iterators. But two pairs i.e.

    typedef vector<int>::iterator _MyItr;
    _MyItr begin() const;
    _MyItr begin();
    
    _MyItr end() const;
    _MyItr end();
    

    This would be in keeping with the way the STL is designed. But, be careful in specifying what sort of iterator the client can expect (for example: if the class specification says that the iterators returned are RandomIterators, it sets a certain amount of expectation on your implementation).