Saturday, June 16, 2007

Make interfaces easy to use correctly and hard to use incorrectly

Type system is your primary ally in preventing undesirable code from compiling

Try that either it wont compile, or if it compiles it wont execute properly.

For e.g.
Date( int day , int month . Int year)

Date ( 3 , 40 , 2001);
Date( 30 , 3 , 2001);

Use type system:

Struct day { explicit(day) } ; struct month { explicit(month);} ; struct year(expli….}

Date ( day(23) , nmonth…..)

Be judicious it has become somewhat harder to write now.

To make sure you cant do Month(13)…we can

Have month as an enum type limited to 12, or
Class month{
Static month(jan()) { return month(1);

..
Private month(int m);
};

Another way to contrain things is as shown in item 4…make them const

Unless there is a good reason your types should behave consistently with built in types

Std::tr1_shared_ptr<investment> pinv( 0 , getridofinvestment) --wont compile because tr1 needs a explicit ptr, hence
Std::tr1_shared_ptr<investment> pinv (static_cast<investment*>(0), getridofinvestment() );

Tr1 avoids the cross dll problem ( what is cross dll problem ?) since by default it uses the version of delete defined in its dll

Things to remember:
Good interfaces are easy to use correctly and hard to use incorrectly. You should strive for these characteristics in all your interfaces

Ways to facilitate correctness use include consistenc in interfaces and behavioral compatiblity with built in types
Ways to prevent errors include creating new types , restricting oeprations on types, constraining object values and eliminating client resource management responsiblities

Tr1::shared_ptr supports custom deleters. This prevenets the cross dll problem , can be used  to automatically unlock mutexes etc.



--
Regards,
Umesh Kumar

http://worthyarticles.blogspot.com/
http://learnbooks.blogspot.com/
http://cplusplusnotes.blogspot.com/

No comments: