Skip to content
IRC-CodingIRC-Coding
JSON SchemaOCLDesign by ContractInvariantPreconditionPostcondition

Data Structures with JSON Schema, OCL & Design by Contract

Specify data and program structures using ER diagrams, JSON Schema, OCL invariants, and Design by Contract pre/post conditions.

S

schutzgeist

9 min read
Data Structures with JSON Schema, OCL & Design by Contract

Specifying Data and Program Structures

This article explains data and program structure specification — covering exam questions, core components, and patterns.

In a Nutshell

Data structures are formally described using models, types, invariants, and schemas. Program structures are specified through interfaces, pre/postconditions, states, and control flow. The goal is clear, testable, and maintainable software.

Core Concepts

Data Specification

  • Models: Entity-Relationship diagram or UML class diagram
  • Cardinalities, keys, normalization (up to 3NF)
  • Rules as invariants
  • Machine-readable interface data: JSON Schema (or DDL/XML Schema)

Program Specification

  • Modules/APIs with signatures
  • Error contracts
  • Design by Contract: precondition, postcondition, invariant
  • Behavior: state machines, activity/sequence diagrams
  • Formalization: OCL (Object Constraint Language)

Specifications serve as the foundation for automated validation, stub generation, and contract testing.

Exam-Relevant Checkpoints

  • Cardinalities and keys must be correct: Data models need unique keys and proper relationships between entities. Incorrect cardinalities lead to inconsistent data or broken queries.
  • JSON Schema for input validation: JSON Schema describes valid structures and value ranges for JSON data. You can validate inputs before processing and reject invalid data automatically.
  • Pre/postconditions and error cases: Design by Contract states obligations for callers and callees. Preconditions must hold before the call; postconditions must hold afterward. Error cases are explicitly defined as exceptions.
  • State models for allowed transitions: State diagrams show which states an object can enter and which transitions are permitted. This prevents invalid state changes—for example, a cancelled order being shipped again.
  • Deriving test cases (equivalence classes and boundary values): Specifications guide test design. Invariants and conditions suggest equivalence classes; keys and boundaries suggest concrete test data.
  • Versioning, migration, and deprecation: Schemas and interfaces change over time. Semantic versioning, deprecation notices, and migration paths help you introduce changes in a controlled manner.
  • Security: validation, permissions, and audit fields: Specifications must cover security aspects. This includes input validation, access control, and logging who changed what data and when.

Core Components

  1. Abstract data type and value domain — An abstract data type defines the possible values and operations of a data structure. The value domain specifies which inputs are valid—for example, positive numbers or strings matching a particular pattern.
  2. Structural model (ER/class) — An ER diagram or UML class diagram describes entities, their attributes, and relationships. The structural model is the foundation for databases and object models.
  3. Cardinalities and normal forms — Cardinalities indicate how many entities are connected. Normal forms eliminate redundancy and prevent anomalies during insertion, updating, and deletion.
  4. Data schema (JSON Schema) — JSON Schema is a machine-readable description of JSON data. It specifies types, required fields, value ranges, and patterns, enabling automated validation.
  5. API contract and error codes — An API contract describes interfaces, parameters, return values, and error cases. Error codes and messages help callers identify and handle problems correctly.
  6. Design by Contract — Design by Contract defines preconditions, postconditions, and invariants. It ensures that callers and callees honor their agreements, making debugging easier.
  7. State and process models — State models show allowed states and transitions. Process models such as activity diagrams describe workflows and decisions within program logic.
  8. Quality rules (NFR) — Non-functional requirements like performance, security, or availability are captured as quality rules. They complement functional specifications with measurable criteria.
  9. Test derivation (contract and property-based) — Test cases can be derived from specifications. Contract tests verify interface agreements; property-based tests verify general properties like invariants.
  10. Versioning and migration strategy — Changes to schemas or APIs must be versioned. A migration strategy describes how existing data and clients transition to new versions.

Practical Example (Order)

JSON Schema (Text excerpt)

type: object
required: id, kundeId, positionen, gesamt
properties:
  id: string (pattern ^ORD-[0-9]{6}$)
  gesamt: number (minimum 0)
  positionen: array (minItems 1)

OCL Invariants (conceptual)

context Bestellung inv SummeStimmt:
  gesamt = sum(positionen.preis * positionen.menge)

context Bestellung inv PositiveMengen:
  forAll(positionen, menge > 0)

Service Contract (pseudocode)

interface BestellService
  legeBestellungAn(warenkorb)

precondition:
  warenkorb.positionen not empty and warenkorb.gesamt > 0
postcondition:
  result.status = ANGELEGT and result.gesamt = warenkorb.gesamt
error cases:
  UngültigeDaten, ZahlungAbgelehnt

Strengths and Weaknesses

Strengths

  • Unambiguous communication
  • Automatable validation
  • Better testability and fewer integration defects

Weaknesses

  • Initial overhead
  • Managing versions and migrations
  • Risk of over-formalization

Typical Exam Questions (with brief answers)

  1. ER diagram vs. class diagram? ER for data and persistence; class diagram for types and operations.
  2. Why invariants? Rules that must always hold true.
  3. How do tests emerge from specifications? Preconditions and invariants → equivalence classes and boundary values.
  4. How do you safely version schemas? Semver: breaking changes = major version, deprecation plus migration path.

Learning Strategy

  1. Building understanding: Model a small domain like a library or online shop as a class diagram. Derive a JSON Schema and some invariants from it.
  2. Going deeper: Write preconditions, postconditions, and error cases for an existing function. Develop test cases using equivalence classes and boundary values.
  3. Exam-focused practice: Master distinguishing ER diagrams from class diagrams, and practice proper notation for invariants and state transitions.
  4. Avoiding pitfalls: Keep specifications up to date. When the system changes, the model, schema, and contracts must change too, or technical debt accumulates.

Practice Example 1: JSON Schema for an order

An order has an ID formatted as ORD- plus six digits, a customer ID, at least one line item, and a total amount greater than or equal to zero. JSON Schema formalizes these rules and can automatically validate input.

Exercise Example 2: OCL Invariants for an Order

An order has the invariant that the total amount must equal the sum of all line items. Another invariant states that each quantity must be positive. Such invariants can be converted into tests.

Exercise Example 3: Design by Contract for an Order Service

The placeOrder function requires a non-empty shopping cart with a positive total amount as a precondition. The postcondition is that the order has status CREATED and the total amount is correct. Error cases such as invalid data or rejected payment are explicitly named.

Exercise 1: Choose a Model Type

You want to document the data structure for a relational database. Which model is more appropriate: an ER model or a class diagram?

Solution: The ER model is more appropriate because it represents entities, attributes, and relationships for database design. A class diagram focuses more on types, operations, and inheritance.

Exercise 2: Derive an Invariant

An order line item has the attributes price and quantity. Formulate a meaningful invariant.

Solution: A meaningful invariant is quantity > 0 and price >= 0. Both must always hold for the line item to be valid.

Exercise 3: Explain a State Model

An order can have the states CREATED, PAID, SHIPPED, and CANCELLED. Which transitions are sensible and which are not?

Solution: Sensible transitions are CREATED → PAID, PAID → SHIPPED, and CREATED → CANCELLED. Transitions like SHIPPED → CREATED or CANCELLED → SHIPPED would be nonsensical because they violate the business workflow.

Topic Analysis

  • Technical Core: Formal description of data and behavior. Specifications define which data is permitted and how the system must behave. Models, schemas, and contracts are the central instruments.
  • Implementation Challenges: Balancing precision with practicality. Overly formal specifications are expensive to maintain, while imprecise ones lead to misunderstandings. The right level of detail depends on the project.
  • Security Implications: Validation and access control as part of the specification. Input validation, access control, and audit trails must be considered in the specification so they are not overlooked during implementation.
  • Documentation Requirements: Models, schemas, and contracts as project documentation. Specifications are binding parts of project documentation. They help align requirements between business, development, and testing teams.
  • Economic Assessment: Cost of specification versus savings from fewer defects. A good specification takes time upfront but avoids expensive bugs and rework in later phases. Automatable validation and test derivation increase its value.

Key Resources

  1. https://json-schema.org
  2. https://www.omg.org/spec/UML

FAQ: Specification of Data and Program Structures

1. What is a specification in software development?

A specification describes precisely which data and behavior a system must have. It includes models, schemas, contracts, and rules that serve as the basis for implementation, validation, and testing.

2. What is an ER model?

An ER model describes data using entities, attributes, and relationships. It is used primarily for designing relational databases.

3. What is a class diagram?

A class diagram is a UML structural diagram that represents classes with attributes, operations, and relationships. It is suitable for object-oriented software modeling.

4. What is JSON Schema?

JSON Schema is a standard for describing JSON data. It specifies types, required fields, value ranges, patterns, and structures, and enables automatic validation.

5. What is an invariant?

An invariant is a condition that must hold at all times. For example, the total amount of an order must always equal the sum of its line items.

6. What is a precondition?

A precondition is a condition that must be satisfied before calling a function or operation. The caller must ensure that the precondition holds.

7. What is a postcondition?

A postcondition is a condition that must hold after a function executes. It guarantees that the result or state has certain properties.

8. What is Design by Contract?

Design by Contract is an approach in which interfaces are formalized through preconditions, postconditions, and invariants. Callers and callees must adhere to the contract.

9. What is OCL?

OCL stands for Object Constraint Language. It is a formal language used to describe invariants, preconditions, and postconditions for UML models precisely.

10. What is a state diagram?

A state diagram shows the states an object can assume and the allowed transitions between those states. It prevents invalid state changes.

11. What are equivalence classes?

Equivalence classes are ranges of inputs that the system treats identically. At least one test case is selected from each equivalence class to reduce the total number of tests.

12. What are boundary values?

Boundary values are the edges of equivalence classes, such as 0, 1, or the maximum allowed value. Defects often occur at boundaries, so they are tested deliberately.

13. What is a normal form?

A normal form is a rule for structuring relational databases that reduces redundancy and anomalies. Third normal form (3NF) is a common goal in practice.

14. What is a primary key?

A primary key is an attribute or combination of attributes that uniquely identifies each record in a table. It cannot be null and must remain unique.

15. What is an API contract?

An API contract describes the interface of a programming interface. It includes parameters, return values, error codes, and expected behavior on success and failure.

16. What is a fault contract?

A fault contract describes which errors can occur and how they are reported. It supplements the API contract with exceptions, error codes, and their meanings.

17. What is a version number under Semantic Versioning?

Semantic Versioning uses versions in the format MAJOR.MINOR.PATCH. A breaking change increments MAJOR, new backward-compatible features increment MINOR, and bug fixes increment PATCH.

18. What is deprecation?

Deprecation means a function or schema is still available but outdated. Users are informed that it may be removed in a later version.

19. What is a migration script?

A migration script transforms existing data or schemas to a new version. It is used to evolve databases or APIs in a controlled manner.

20. What is a contract test?

A contract test verifies that an interface adheres to the agreed contract. It is often used between consumer and provider to ensure compatibility.

21. What is an audit field?

An audit field logs who changed what data and when. Typical fields are createdAt, updatedAt, createdBy, and updatedBy. They support traceability and compliance.

22. What is machine-readable validation?

Machine-readable validation means that rules from a schema or model can be checked directly by a computer. JSON Schema, XML Schema, and DDL are examples of such machine-readable rules.

23. What is the difference between data and program specification?

Data specification describes data structures, relationships, and rules. Program specification describes interfaces, behavior, states, and workflows of a program.

24. Why do specifications lead to fewer integration errors?

Clear specifications define interfaces and behavior early. All stakeholders work against the same contract, reducing misunderstandings during integration.

25. What is a non-functional requirement?

A non-functional requirement describes quality attributes such as performance, security, availability, or scalability. It complements functional requirements and is often defined as Quality of Service.
Back to Blog
Share:

Related Posts