110 likes | 220 Views
A Summary of Interface Principles. ByeongGil Jeon. Interfaces. class Csv { public: Csv(istream& fin = cin, string sep = ",") : fin(fin), fieldsep(sep) {} int getline(string& str); string getfield(int n); int getnfield() const { return nfield; } private: ... };.
E N D
A Summary of Interface Principles ByeongGil Jeon
Interfaces class Csv { public: Csv(istream& fin = cin, string sep = ",") : fin(fin), fieldsep(sep) {} int getline(string& str); string getfield(int n); int getnfield() const { return nfield; } private: ... };
A Set of Principles from the book • Hide implementation details • Choose a small orthogonal set of primitives • Don’t reach behind the user’s back • Do the same thing the same way everywhere
Hide Implementation Details(1) • Terms: Information hiding Encapsulation Abstraction Modularization
Hide Implementation Details(2) • Avoid global variables • Against publicly visible data However, Extern FILE __job[_NFILE]; #define stdin (&__job[0]) #define stdout (&__job[1]) #define stderr (&__job[2]) Two underscores for visible private names
Choose a Small Orthogonal Set of Primitives(1) • A large interface is harder to write and maintain • Example (functions that will write a single character to an output stream) char c; putc(c, fp); fputc(c, fp); fprintf(fp, “%c”, c); fwrite(&c, sizeof(char), 1, fp); Multiple ways of doing the same thing Not all are necessary
Choose a Small Orthogonal Set of Primitives(2) • Do one thing, and do it well • Don’t add to an interface just because it’s possible to do so • Don’t fix the interface when it’s the implementation that’s broken • For instance, rather than having many functions, it would be better to have one function that was best
Don’t Reach behind the user’s back • Should not write secret files and variables or change global data • The use of one interface should not demand another one just for the convenience • Should be circumspect about modifying data in its caller Example char str[] = "now # is the time for all # good men to come to the # aid of their country"; char delims[] = "#"; char *result = NULL; result = strtok( str, delims ); while( result != NULL ) { printf( "result is \"%s\"\n", result ); result = strtok( NULL, delims ); } Reference: http://www.cppreference.com/wiki/string/c/strtok Each subsequent call, with a NULL as the value of str, starts searching from the saved pointer
Do the same thing the same way everywhere • Should be easy to predict how to use an unfamiliar function • Example: • the algorithms for STL containers present a very uniform interface • The standard I/O function fread and fwrite would be easier to remember if they looked like read and write functions they are based on
A Set of Principles from the book • Hide implementation details • Choose a small orthogonal set of primitives • Don’t reach behind the user’s back • Do the same thing the same way everywhere