Mathematical Foundations β
Beneath the practical power of specifications lies elegant mathematics. Understanding these foundations transforms you from a specification user to a specification master.
The Beautiful Truth β
Specifications are applied mathematics. Every specification is:
- A predicate function from mathematical logic
- A set membership test from set theory
- A boolean expression from boolean algebra
This isn't abstract theoryβit's the foundation that guarantees your business logic is correct.
Boolean Algebra: The Core β
The Fundamental Operations β
Specifications implement the three basic boolean operations:
// AND: Conjunction (β§)
$spec1->and($spec2) // Both must be true
// OR: Disjunction (β¨)
$spec1->or($spec2) // At least one must be true
// NOT: Negation (Β¬)
$spec->not() // Inverts the result
Truth Tables β
Every specification operation has a precise truth table:
AND Operation β
spec1 | spec2 | spec1 β§ spec2 |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
OR Operation β
spec1 | spec2 | spec1 β¨ spec2 |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
NOT Operation β
spec | Β¬spec |
---|---|
true | false |
false | true |
Boolean Laws in Specifications β
These mathematical laws guarantee predictable behavior:
Commutative Laws β
// AND is commutative
$a->and($b) β‘ $b->and($a)
// OR is commutative
$a->or($b) β‘ $b->or($a)
Associative Laws β
// AND is associative
($a->and($b))->and($c) β‘ $a->and($b->and($c))
// OR is associative
($a->or($b))->or($c) β‘ $a->or($b->or($c))
Distributive Laws β
// AND distributes over OR
$a->and($b->or($c)) β‘ ($a->and($b))->or($a->and($c))
// OR distributes over AND
$a->or($b->and($c)) β‘ ($a->or($b))->and($a->or($c))
De Morgan's Laws β
// NOT of AND
$a->and($b)->not() β‘ $a->not()->or($b->not())
// NOT of OR
$a->or($b)->not() β‘ $a->not()->and($b->not())
Proof: De Morgan's Law in Practice β
class DeMorganProof extends TestCase
{
public function test_de_morgan_and_law()
{
$activeSpec = new WhereSpecification('status', 'active');
$verifiedSpec = new WhereSpecification('verified', true);
// Left side: NOT (A AND B)
$leftSide = $activeSpec->and($verifiedSpec)->not();
// Right side: (NOT A) OR (NOT B)
$rightSide = $activeSpec->not()->or($verifiedSpec->not());
// Test with all possible inputs
$testCases = [
['status' => 'active', 'verified' => true],
['status' => 'active', 'verified' => false],
['status' => 'inactive', 'verified' => true],
['status' => 'inactive', 'verified' => false],
];
foreach ($testCases as $case) {
$candidate = (object) $case;
$this->assertEquals(
$leftSide->isSatisfiedBy($candidate),
$rightSide->isSatisfiedBy($candidate),
"De Morgan's law failed for: " . json_encode($case)
);
}
}
}
Set Theory: The Structure β
Specifications as Sets β
Every specification defines a set:
$activeUsers = new WhereSpecification('status', 'active');
// Defines the set: {u β Users | u.status = 'active'}
$premiumUsers = new WhereSpecification('subscription', 'premium');
// Defines the set: {u β Users | u.subscription = 'premium'}
Set Operations Through Specifications β
Intersection (AND) β
$activePremium = $activeUsers->and($premiumUsers);
// Set intersection: ActiveUsers β© PremiumUsers
Union (OR) β
$activeOrPremium = $activeUsers->or($premiumUsers);
// Set union: ActiveUsers βͺ PremiumUsers
Complement (NOT) β
$inactiveUsers = $activeUsers->not();
// Set complement: Users \ ActiveUsers
Set Difference β
$activeNonPremium = $activeUsers->and($premiumUsers->not());
// Set difference: ActiveUsers \ PremiumUsers
Venn Diagrams in Code β
class SetOperationsSpecification
{
public function visualizeVennDiagram()
{
$setA = new WhereSpecification('category', 'electronics');
$setB = new WhereSpecification('price', '>', 100);
return [
'only_A' => $setA->and($setB->not()), // A \ B
'only_B' => $setB->and($setA->not()), // B \ A
'both_A_and_B' => $setA->and($setB), // A β© B
'either_A_or_B' => $setA->or($setB), // A βͺ B
'neither_A_nor_B' => $setA->not()->and($setB->not()), // (A βͺ B)'
];
}
}
Predicate Logic: The Language β
First-Order Logic β
Specifications are predicates in first-order logic:
// Predicate: IsActive(x)
class IsActiveSpecification extends AbstractSpecification
{
public function isSatisfiedBy(mixed $x): bool
{
return $x->status === 'active';
}
}
// Universal quantification: βx β Users, IsActive(x)
$allUsersActive = User::all()->every(
fn($user) => $isActiveSpec->isSatisfiedBy($user)
);
// Existential quantification: βx β Users, IsActive(x)
$someUserActive = User::all()->contains(
fn($user) => $isActiveSpec->isSatisfiedBy($user)
);
Logical Implications β
class ImplicationSpecification extends AbstractSpecification
{
public function __construct(
private SpecificationInterface $antecedent,
private SpecificationInterface $consequent
) {}
public function isSatisfiedBy(mixed $candidate): bool
{
// P β Q β‘ Β¬P β¨ Q
return !$this->antecedent->isSatisfiedBy($candidate) ||
$this->consequent->isSatisfiedBy($candidate);
}
}
// If user is premium, then they must be verified
$premiumImpliesVerified = new ImplicationSpecification(
new WhereSpecification('subscription', 'premium'),
new WhereNullSpecification('email_verified_at', false)
);
Category Theory: The Abstraction β
Specifications as Morphisms β
In category theory terms:
- Objects are your domain entities
- Morphisms are specifications
- Composition is specification chaining
// Morphism composition
class MorphismComposition
{
// f: A β B (specification that maps A to boolean)
private SpecificationInterface $f;
// g: B β C (specification that maps B to boolean)
private SpecificationInterface $g;
// g β f: A β C (composition)
public function compose(): SpecificationInterface
{
return $this->f->and($this->g);
}
}
Functors and Natural Transformations β
// Functor: Maps specifications to queries
class SpecificationToQueryFunctor
{
public function map(SpecificationInterface $spec): Builder
{
return $spec->toQuery(new Builder());
}
}
// Natural transformation: Between functors
class CacheableTransformation
{
public function transform(SpecificationInterface $spec): CacheableSpecification
{
return new CacheableSpecification($spec);
}
}
Lattice Theory: The Hierarchy β
Specifications Form a Boolean Lattice β
class SpecificationLattice
{
// Top element (always true)
public function top(): SpecificationInterface
{
return new AlwaysTrueSpecification();
}
// Bottom element (always false)
public function bottom(): SpecificationInterface
{
return new AlwaysFalseSpecification();
}
// Join (least upper bound) - OR
public function join(SpecificationInterface $a, SpecificationInterface $b): SpecificationInterface
{
return $a->or($b);
}
// Meet (greatest lower bound) - AND
public function meet(SpecificationInterface $a, SpecificationInterface $b): SpecificationInterface
{
return $a->and($b);
}
// Complement
public function complement(SpecificationInterface $spec): SpecificationInterface
{
return $spec->not();
}
}
Partial Order Relations β
class SpecificationOrder
{
// a β€ b if a implies b
public function lessThanOrEqual(
SpecificationInterface $a,
SpecificationInterface $b
): bool {
// For all x, if a(x) then b(x)
return $this->implies($a, $b);
}
private function implies(
SpecificationInterface $a,
SpecificationInterface $b
): bool {
// Test with sample data
foreach ($this->generateTestCases() as $case) {
if ($a->isSatisfiedBy($case) && !$b->isSatisfiedBy($case)) {
return false;
}
}
return true;
}
}
Computational Complexity β
Time Complexity Analysis β
class ComplexityAnalysis
{
public function analyzeSpecification(SpecificationInterface $spec): array
{
return [
'evaluation_complexity' => $this->evaluationComplexity($spec),
'query_complexity' => $this->queryComplexity($spec),
'composition_depth' => $this->compositionDepth($spec),
'space_complexity' => $this->spaceComplexity($spec),
];
}
private function evaluationComplexity(SpecificationInterface $spec): string
{
if ($spec instanceof WhereSpecification) {
return 'O(1)'; // Constant time comparison
}
if ($spec instanceof AndSpecification || $spec instanceof OrSpecification) {
return 'O(n)'; // Linear in number of sub-specifications
}
if ($spec instanceof WhereHasSpecification) {
return 'O(m)'; // Linear in related records
}
return 'O(n*m)'; // Worst case
}
}
Formal Verification β
Proving Specification Correctness β
class SpecificationProof
{
/**
* Prove that a specification satisfies its invariants
*/
public function proveInvariants(SpecificationInterface $spec): bool
{
// Invariant 1: Double negation elimination
$doubleNegation = $spec->not()->not();
assert($this->equivalent($spec, $doubleNegation));
// Invariant 2: Idempotence of AND
$idempotentAnd = $spec->and($spec);
assert($this->equivalent($spec, $idempotentAnd));
// Invariant 3: Idempotence of OR
$idempotentOr = $spec->or($spec);
assert($this->equivalent($spec, $idempotentOr));
// Invariant 4: Identity elements
$withTrue = $spec->and(new AlwaysTrueSpecification());
assert($this->equivalent($spec, $withTrue));
$withFalse = $spec->or(new AlwaysFalseSpecification());
assert($this->equivalent($spec, $withFalse));
return true;
}
private function equivalent(
SpecificationInterface $a,
SpecificationInterface $b
): bool {
// Test equivalence with exhaustive cases
foreach ($this->generateAllPossibleInputs() as $input) {
if ($a->isSatisfiedBy($input) !== $b->isSatisfiedBy($input)) {
return false;
}
}
return true;
}
}
Algebraic Properties β
The Specification Monoid β
class SpecificationMonoid
{
// Identity element for AND
public function andIdentity(): SpecificationInterface
{
return new AlwaysTrueSpecification();
}
// Identity element for OR
public function orIdentity(): SpecificationInterface
{
return new AlwaysFalseSpecification();
}
// Associative binary operation
public function combine(
SpecificationInterface $a,
SpecificationInterface $b
): SpecificationInterface {
return $a->and($b); // or $a->or($b) for OR-monoid
}
// Fold operation
public function fold(array $specifications): SpecificationInterface
{
return array_reduce(
$specifications,
fn($carry, $spec) => $carry ? $carry->and($spec) : $spec,
$this->andIdentity()
);
}
}
The Specification Ring β
class SpecificationRing
{
// Addition operation (OR)
public function add(
SpecificationInterface $a,
SpecificationInterface $b
): SpecificationInterface {
return $a->or($b);
}
// Multiplication operation (AND)
public function multiply(
SpecificationInterface $a,
SpecificationInterface $b
): SpecificationInterface {
return $a->and($b);
}
// Additive identity (always false)
public function zero(): SpecificationInterface
{
return new AlwaysFalseSpecification();
}
// Multiplicative identity (always true)
public function one(): SpecificationInterface
{
return new AlwaysTrueSpecification();
}
// Additive inverse (not possible in boolean algebra)
// Multiplicative inverse (not defined for all elements)
}
Practical Mathematical Applications β
Optimization Through Algebra β
class AlgebraicOptimizer
{
public function optimize(SpecificationInterface $spec): SpecificationInterface
{
// Apply algebraic simplifications
// Remove double negations
if ($spec instanceof NotSpecification) {
$inner = $spec->getSpecification();
if ($inner instanceof NotSpecification) {
return $this->optimize($inner->getSpecification());
}
}
// Simplify tautologies
if ($spec instanceof AndSpecification) {
if ($spec->getLeft() instanceof AlwaysTrueSpecification) {
return $this->optimize($spec->getRight());
}
if ($spec->getRight() instanceof AlwaysTrueSpecification) {
return $this->optimize($spec->getLeft());
}
}
// Apply absorption law: A β¨ (A β§ B) = A
// Apply other algebraic laws...
return $spec;
}
}
Statistical Analysis β
class SpecificationStatistics
{
public function analyzeSelectivity(SpecificationInterface $spec, array $dataset): array
{
$satisfied = array_filter(
$dataset,
fn($item) => $spec->isSatisfiedBy($item)
);
$total = count($dataset);
$selected = count($satisfied);
return [
'selectivity' => $selected / $total,
'cardinality' => $selected,
'entropy' => $this->calculateEntropy($selected, $total),
'information_gain' => $this->calculateInformationGain($spec, $dataset),
];
}
private function calculateEntropy(int $positive, int $total): float
{
if ($positive === 0 || $positive === $total) {
return 0;
}
$p = $positive / $total;
$n = 1 - $p;
return -($p * log($p, 2) + $n * log($n, 2));
}
}
The Mathematical Beauty β
Specifications aren't just practicalβthey're mathematically elegant:
- Closure: Operations always produce valid specifications
- Completeness: Can express any boolean logic
- Soundness: Mathematical laws always hold
- Decidability: Always terminate with true/false
Your Mathematical Toolkit β
With these foundations, you can:
- Prove your business logic is correct
- Optimize specifications algebraically
- Predict performance mathematically
- Compose with mathematical confidence
The Power of Math
Understanding the mathematics behind specifications transforms you from someone who uses the pattern to someone who masters it.
Ready for Domain-Driven Design? β
Now that you understand the mathematical foundations, see how specifications bridge the gap between business language and code.
Explore Domain-Driven Design β
References β
Boole, George (1854). An Investigation of the Laws of Thought. Cambridge: Macmillan and Co.
Halmos, Paul R. (1960). Naive Set Theory. Princeton, NJ: D. Van Nostrand Company.
Mendelson, Elliott (2015). Mathematical Logic. 4th ed. Chapman and Hall/CRC. ISBN 978-1-4822-3778-8.
Rosen, Kenneth H. (2018). Discrete Mathematics and Its Applications. 8th ed. McGraw-Hill Education. ISBN 978-1-259-67651-2.
Mac Lane, Saunders (1998). Categories for the Working Mathematician. 2nd ed. Springer-Verlag. ISBN 0-387-98403-8.
Knuth, Donald E. (1997). The Art of Computer Programming, Volume 1: Fundamental Algorithms. 3rd ed. Addison-Wesley. ISBN 0-201-89683-4.
Pierce, Benjamin C. (1991). Basic Category Theory for Computer Scientists. MIT Press. ISBN 0-262-66071-7.
Birkhoff, Garrett & Bartee, Thomas C. (1970). Modern Applied Algebra. McGraw-Hill.
Davey, B.A. & Priestley, H.A. (2002). Introduction to Lattices and Order. 2nd ed. Cambridge University Press. ISBN 0-521-78451-4.