Errors and Assertions

Defensive Programming with Assertions

How can I use assertions to practice "defensive programming" and make my code more robust?

Abstract art representing computer programming

Defensive programming is a style of programming that anticipates potential errors and takes steps to prevent or mitigate them. Assertions are a key tool in defensive programming, as they allow you to express and validate assumptions about your code.

Here are some ways to use assertions for defensive programming:

Example 1: Check function preconditions:

int strlen(const char* str) {
  assert(str != nullptr);// ...
}

Example 2: Validate function postconditions:

int pop(std::stack<int>& s) {
  assert(!s.empty());
  int top = s.top();
  s.pop();
  assert(top == s.top());
  return top;
}

Example 3: Verify loop invariants:

int sum(const std::vector<int>& v) {
  int total = 0;
  for (size_t i = 0; i < v.size(); ++i) {
    total += v[i];
    assert(total >= 0);
  }
  return total;
}

Example 4: Check switch cases and if-else chains:

char to_lower(char c) {
  switch (c) {
    case 'A': return 'a';
    case 'B': return 'b';
// ...
    default:
      assert(false && "Invalid character");
  }
}

Example 5: Test user input:

void save_preferences(int pref) {
  assert(pref >= 0 && pref < 10);// ...
}

Some tips for effective defensive programming with assertions:

  • Be liberal with assertions. It's better to have too many than too few.
  • Assert as close to the source of the error as possible.
  • Don't use assertions as a substitute for error handling. Assertions are for detecting bugs, not for expected error conditions.
  • Leave assertions enabled in debug builds to catch problems early.
  • Consider writing unit tests to exercise assertions and edge cases.

Remember, the goal of defensive programming is to make your code fail quickly and visibly when something goes wrong, rather than silently producing incorrect results. Assertions help you achieve this by making your assumptions explicit and verifiable.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved