Type Safety
Team LiB
Previous Section Next Section

Type Safety

90. Avoid type switching; prefer polymorphism.

Switch off: Avoid switching on the type of an object to customize behavior. Use templates and virtual functions to let types (not their calling code) decide their behavior.

91. Rely on types, not on representations.

Don't try to X-ray objects (see Item 96): Don't make assumptions about how objects are exactly represented in memory. Instead, let types decide how their objects are written to and read from memory.

92. Avoid using reinterpret_cast.

Lies have short legs (German and Romanian proverb): Don't try to use reinterpret_cast to force the compiler to reinterpret the bits of an object of one type as being the bits of an object of a different type. That's the opposite of maintaining type safety, and reinterpret_cast isn't even guaranteed to do that oranything else in particular.

93. Avoid using static_cast on pointers.

Pointers to dynamic objects don't static_cast: Safe alternatives range from using dynamic_cast to refactoring to redesigning.

94. Avoid casting away const.

Some fibs are punishable: Casting away const sometimes results in undefined behavior, and it is a staple of poor programming style even when legal.

95. Don't use C-style casts.

Age doesn't always imply wisdom: C-style casts have different (and often dangerous) semantics depending on context, all disguised behind a single syntax. Replacing C-style casts with C++-style casts helps guard against unexpected errors.

96. Don't memcpy or memcmp non-PODs.

Don't try to X-ray objects (see Item 91): Don't use memcpy and memcmp to copy or compare anything more structured than raw memory.

97. Don't use unions to reinterpret representation.

A deceit is still a lie: Unions can be abused into obtaining a "cast without a cast" by writing one member and reading another. This is more insidious and even less predictable than reinterpret_cast (see Item 92).

98. Don't use varargs (ellipsis).

Ellipses cause collapses: The ellipsis is a dangerous carryover from C. Avoid varargs, and use higher-level C++ constructs and libraries instead.

99. Don't use invalid objects. Don't use unsafe functions.

Don't use expired medicines: Both invalid objects and historical but unsafe functions wreak havoc on your program's health.

100. Don't treat arrays polymorphically.

Arrays are ill-adjusted: Treating arrays polymorphically is a gross type error that your compiler will probably remain silent about. Don't fall into the trap.

    Team LiB
    Previous Section Next Section