90 likes | 269 Views
Guidelines for class design. From Scott Meyers Effective C++. Item 20: Avoid data members in the public interface. Consistency : If everything in the public interface is a function, clients of your class won't have to remember whether to use parentheses or not
E N D
Guidelines for class design From Scott Meyers Effective C++
Item 20: Avoid data members in the public interface • Consistency: If everything in the public interface is a function, clients of your class won't have to remember whether to use parentheses or not class foo {public: float temperature; float averageTempterature(); }
Control: functions give precise control over accessibility class AccessLevels { public: int getReadOnly(); void setReadWrite(int value); int getReadWrite() const; setWriteOnly(int value); private: int noAccess; // no access to this int int readOnly; // read-only access to int readWrite; // read-write access to int writeOnly; // write-only access to
AccessLevels implementation int AccessLevels::getReadOnly() const { return readOnly; } void AccessLevels::setReadWrite(int value) { readWrite = value; } int AccessLevels::getReadWrite() const { return readWrite; } void AccessLevels::setWriteOnly(int value) { writeOnly = value; }
Still not convinced??? • functional abstraction: If you implement access to a data member through a function, you can later replace the data member with a computation, and nobody using your class will be any the wiser.
Functional Abstraction You are writing an application inwhich some automated equipment ismonitoring the speed of passing cars. As each car passes, its speed is computed, and the value is added to a collection of all the speed data collected so far class SpeedDataCollection {public: void addValue(int speed); // add new data value double averageSoFar() const; // return ave speed };
How to implement averageSoFar • One way to implement it is to have a data member in the class that is a running average of all the speed data so far collected. Whenever averageSoFar() is called, it just returns the value of that data member. • A different approach is to have averageSoFar()compute its value anew each time it's called, something it could do by examining each data value in the collection.
Which is best? • Tradeoff of time vs. space • The important point is that by accessing the average through a member function, you can use either implementation, a valuable source of flexibility that you wouldn't have if you made a decision to include the running average data member in the public interface
Item 20: Avoid data members in the public interface Benefits of following Item 20: • Consistency • Control • Functional abstraction