C++ Contracts: The Long Road to Design by Contract and Its Controversial Implementation

BigGo Editorial Team
C++ Contracts: The Long Road to Design by Contract and Its Controversial Implementation

The C++ community is currently engaged in a heated discussion about the proposed Contracts facility for C++, highlighting both the long history of contract programming and the challenges of implementing it effectively in a modern context.

Historical Context and Revival

Contract programming in C++ isn't new - it dates back to the 1990s with implementations like Digital Mars' contract programming system. However, the current proposal represents a fresh attempt to standardize contracts in the language, with proposals dating back to at least 2004. This latest iteration aims to provide a minimum viable product approach to adding contract assertions to C++, focusing on three key types: precondition assertions, postcondition assertions, and assertion statements.

Three types of contract assertions in the proposal:

  • Precondition assertions
  • Postcondition assertions
  • Assertion statements

Runtime semantics options:

  • Ignoring
  • Observing
  • Enforcing truth of predicates

Safety Concerns and Implementation Challenges

The implementation of contracts in C++ has sparked significant debate within the community, particularly regarding safety and performance implications. A major concern revolves around undefined behavior and potential time travel defects, though recent revisions of the proposal have addressed some of these issues.

Contracts are generally useless: programmers won't write them, or will write them incorrectly. Moreover, the runtime enforcement dominates all but the most-expensive functions, and contracts become an antipattern for helper functions due to their enforcement cost.

Practical Considerations and Future Outlook

The community discussion reveals a complex balance between theoretical benefits and practical limitations. While Design by Contract (DbC) principles remain valuable for software engineering, the implementation costs and potential performance impacts make their practical application challenging. Some developers suggest that contracts are most useful when associated with formal proof systems, rather than runtime enforcement.

The controversy surrounding this proposal highlights a broader challenge in language design: balancing safety features with performance and usability. As the C++ committee works towards potential inclusion in C++26, the debate continues over whether this implementation will enhance code safety or introduce new complexities for developers to navigate.

Source Citations: Contracts for C++