A Kotlin Multiplatform library for Design by Contract (DbC).
Software systems require high reliability and clear behavioural specifications. Design by Contract provides formal, verifiable boundaries between callers and implementations. This library enables contracts across all Kotlin Multiplatform targets, supporting preconditions, postconditions, and class invariants.
It provides two complementary modes of operation:
-
Unconditional Checks: Critical validation rules and compiler smart-casts that always execute.
-
Excludable Checks: In-depth verifications that you can enable during development and testing, and disable in production to maximise runtime performance.
-
JVM: JVM 11+ (Toolchain 17+)
-
Android: API 21+ (
minSdk 21,compileSdk 36) -
Apple Platforms: iOS (
iosArm64,iosSimulatorArm64), macOS (macosArm64) -
Linux:
linuxX64,linuxArm64 -
JavaScript: Node.js and Web Browsers
-
WebAssembly:
wasmJs(Node.js & Browsers) andwasmWasi(Node.js)
Add the dependency to your project build file.
repositories {
mavenCentral()
}
kotlin {
sourceSets {
commonMain.dependencies {
implementation("org.infosmid:design-by-contract:1.0.0")
}
}
}repositories {
mavenCentral()
}
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'org.infosmid:design-by-contract:1.0.0'
}
}
}
}If your project uses a Gradle version catalog, declare the library in gradle/libs.versions.toml:
[versions]
design-by-contract = "1.0.0"
[libraries]
infosmid-dbc = { module = "org.infosmid:design-by-contract", version.ref = "design-by-contract" }Then reference it from your build file through the generated libs accessor:
kotlin {
sourceSets {
commonMain.dependencies {
implementation(libs.infosmid.dbc)
}
}
}For a single platform (JVM / Android) project, use the same accessor in the top-level dependencies block:
dependencies {
implementation(libs.infosmid.dbc)
}In Groovy DSL (build.gradle) the accessor is implementation libs.design.by.contract.
Contract checks are divided into two distinct groups based on their execution guarantees:
| Check Type | Signature Pattern | Behavior & Evaluation | Excludable? |
|---|---|---|---|
Eager Preconditions |
|
Evaluated immediately. Integrates with Kotlin contracts for compiler smart-casting. |
Never Excluded (Always Active) |
Lazy Preconditions |
|
Evaluated only when |
May Be Excluded |
Eager Postconditions |
|
Evaluated immediately upon function return. Integrates with Kotlin contracts. |
Never Excluded (Always Active) |
Lazy Postconditions |
|
Evaluated only when |
May Be Excluded |
Class Invariants |
|
Validates object state before and after method execution, or immediately. Controlled by |
May Be Excluded |
|
Important
|
|
Preconditions define requirements that callers must satisfy before invoking a method.
import org.infosmid.dbc.precondition
import org.infosmid.dbc.preconditionNotNull
import org.infosmid.dbc.preconditionFailed
class OrderProcessor {
fun processOrder(orderId: String?, amount: Double, items: List<String>) {
// Never Excluded: Validates nullability and smart-casts orderId to String
val validId: String = preconditionNotNull(orderId) { "Order ID must not be null" }
// Never Excluded: Direct boolean check
precondition(amount > 0.0) { "Order amount must be positive, but was $amount" }
// May Be Excluded: Lambda check for expensive validation (e.g. collection scanning)
precondition({ items.isNotEmpty() && items.all { it.isNotBlank() } }) {
"Items list must contain only non-blank identifiers"
}
// Never Excluded: Explicit failure branch
if (amount > 1_000_000.0) {
preconditionFailed("Amount exceeds single transaction limit: $amount")
}
executeTransaction(validId, amount, items)
}
private fun executeTransaction(id: String, amount: Double, items: List<String>) {
// ...
}
}Postconditions define guarantees that a method delivers upon successful execution.
import org.infosmid.dbc.postcondition
import org.infosmid.dbc.postconditionNotNull
import org.infosmid.dbc.postconditionFailed
class CalculationService {
fun computeSquareRoot(value: Double): Double {
precondition(value >= 0.0) { "Cannot compute square root of negative number: $value" }
val result = kotlin.math.sqrt(value)
// Never Excluded: Immediate boolean postcondition
postcondition(result >= 0.0) { "Square root output must be non-negative" }
// May Be Excluded: Lambda postcondition verifying mathematical consistency
postcondition({ kotlin.math.abs((result * result) - value) < 0.0001 }) {
"Square root calculation precision error for value $value"
}
return result
}
fun findUser(id: String): User {
val user: User? = databaseQuery(id)
// Never Excluded: Smart-casts return value and guarantees non-null
return postconditionNotNull(user) { "User query must return a non-null User object for id: $id" }
}
private fun databaseQuery(id: String): User? = User(id)
}
data class User(val id: String)Class invariants define state consistency rules that must remain true for the lifetime of an object.
Classes implement HasInvariant and evaluate state consistency using checkInvariant.
import org.infosmid.dbc.HasInvariant
import org.infosmid.dbc.checkInvariant
import org.infosmid.dbc.precondition
class BankAccount(
var balance: Double = 0.0,
var overdraftLimit: Double = 100.0
) : HasInvariant {
/**
* Invariant definition: Balance must never drop below the negative overdraft limit,
* and the overdraft limit itself must be non-negative.
*/
override fun invariant(): Boolean {
return balance >= -overdraftLimit && overdraftLimit >= 0.0
}
/**
* Scoped invariant check:
* Verifies the invariant BEFORE and AFTER the block executes.
* Throws InvariantException if either check fails.
*/
fun withdraw(amount: Double) = checkInvariant("Invariant violated during withdrawal") {
precondition(amount > 0.0) { "Withdrawal amount must be positive" }
balance -= amount
}
fun deposit(amount: Double) = checkInvariant("Invariant violated during deposit") {
precondition(amount > 0.0) { "Deposit amount must be positive" }
balance += amount
}
/**
* Immediate invariant check on the current state.
*/
fun updateLimit(newLimit: Double) {
precondition(newLimit >= 0.0) { "Limit must be non-negative" }
overdraftLimit = newLimit
this.checkInvariant("Invalid overdraft limit update")
}
}You can enable or disable excludable contract checks globally or per category (precondition, postcondition, invariant).
For each check category, the system resolves flags in this order:
-
Category Setting:
dbc.<category>(e.g.,dbc.precondition,dbc.postcondition,dbc.invariant). -
Global Setting:
dbc.enabled. -
Platform Default: The platform debug signal (
truein debug builds/tests,falseotherwise).
Recognized boolean string values: true, 1, yes, on, enabled (case-insensitive) or false, 0, no, off, disabled.
| Platform | Configuration Source | Example |
|---|---|---|
JVM |
System Properties |
|
Android |
|
|
Apple (iOS / macOS) |
|
|
Linux / POSIX |
Environment Variables |
|
JavaScript / Wasm |
|
|
You can modify contract verification flags dynamically in Kotlin code:
import org.infosmid.dbc.config.Dbc
import org.infosmid.dbc.config.DbcKind
// Enable or disable specific check categories
Dbc.preconditions = true
Dbc.postconditions = false
Dbc.invariants = true
// Alternatively, use enum-based helpers
Dbc.set(DbcKind.POSTCONDITION, true)
// Enable or disable all categories simultaneously
Dbc.setAll(false)
// Re-read host environment/platform settings, discarding programmatic changes
Dbc.reload()The library defines the following exception hierarchy:
-
DesignByContractException(inherits fromRuntimeException)-
PreConditionException(thrown when a precondition fails) -
PostConditionException(thrown when a postcondition fails) -
InvariantException(thrown when an invariant fails)
-
-
Build all targets:
./gradlew assemble -
Run tests across all targets:
./gradlew check allTests -
Run JVM tests:
./gradlew jvmTest -
Run Android tests:
./gradlew testAndroidHostTest -
Run JS & Wasm tests:
./gradlew jsNodeTest wasmJsNodeTest wasmWasiNodeTest -
Generate documentation:
./gradlew asciidoctorHtml dokkaGeneratePublicationHtml siteDocsZip -
Publish to Maven Local:
./gradlew publishToMavenLocal
Licensed under the Apache License 2.0.