Blog Home

Obsessed With Primitives?

2017-11-14

Code that relies too heavily on primitive types instead of custom abstractions can be hard to understand and maintain.

Bad

std::vector<std::pair<int, int>> polygon = {
    std::make_pair(0, 0), std::make_pair(0, 4), std::make_pair(4, 0)};
std::pair<std::pair<int, int>, std::pair<int, int>> bounding_box =
    GetBoundingBox(polygon);
int area = (bounding_box.second.first - bounding_box.first.first) *
           (bounding_box.second.second - bounding_box.first.second);

Make higher-level abstractions.

Good

Polygon polygon = RightTriangle(4, 4);
int area = polygon.GetBoundingBox().GetArea();

This advice doesn't just apply to primitives and The STL. It's possible for any type to be too primitive for the job.

Good

Polygon polygon = IsoscelesRightTriangle(4);
int area = polygon.GetBoundingBox().GetArea();