Tuesday, June 19, 2007

avoid returning handles to object internals

class rectangle {
Point& upperLeft() const { return pData->ulhc; }
Point& lowerRight() const { return pData->lrhc;}

will this compile ? isnt it wrong that this compiles ?

if a const member function returns a reference to data associated with an object that is stored outside the object itself, the caller of the function can modify that data....this a fallout of the limitations of bitwise constness.

reference pointers iterators are all handles and all have the same issue,

returning handle to objects internals always runs the risk of compromising encapsulation.

private fns are also object internals.

use const point& upperleft() cosnt { return pdata->ulhc; } solves the problem above.

returning handles can also lead to dangling handles. handles that refer to parts of objects that dont exist.... e.g. ( very similar to window example in previous item)

class guiobject{>>>}
const rectangle boundingBox (const guiobject& g);

guiobject * pgo;
const point* pupperleft = &( boundingbox(*pgo).upperleft());
a temp obj is former, upper kleft taken and then it gets destroyed.

so dont return object internal data ( their are notable exceptions like operator[] )

but it shud be an exception not a rule

things to remember:
avoid returning handles ( references , pointers, iterators) to object internals, not returning handles increases encapsulation helps const member functions act const and minimizes the creation of dangling handles.

No comments: