Monday, March 3, 2008

How to design good interfaces

Bjarne Stroustrup

KISS principle

Don’t use f(pointer, count)

Interface principles
1. Simple
2. Stable
3. Evolvable (extensible)
4. Explicit
5. Catch errors
6. Consistent
7. Efficient

Simple/concrete then abstract/generalize. If in doubt, don’t put it in.

Not all interfaces are the same, nor should they be.

Design parameters (checklist)
1. Type safety
2. Mutability
3. Customization
4. Error handling
5. Performance
6. Concurrency
7. Resource management
8. Lifetime
9. Copying

(See slides on developing a project’s design parameters)

Aims of design
· Represent ideas directly in code
o Data structures
o Algorithms
· Represent ideas independently in code
· Represent relationships among ideas directly in code
o Hierarchy
o Parameterization
· Combine ideas freely

Class vs. Plain Old Data (struct) design

Use struct if you can’t define an invariant

Define an invariant for ever class (that’s not a struct) and provide ways of checking and enforcing invariants.

Be explicit about mutability! (const correctness)

Classic Bjarne rule: RIIA “resource acquisition is initialization”
· Keys to exception safety and performance
· Capture resources (i.e. memory, file, socket, thread handle) with constructors
· Release resources with destructors

No comments: