r/DomainDrivenDesign • u/AMINEX-2002 • May 25 '26
How we prevented invalid Quran verses from ever existing in our system
So we're building a Quran app and we ran into a classic DDD invariant enforcement problem. Thought I'd share because it's a clean real-world example.
The problem
The Quran has a strict structure. Al-Fatiha has exactly 7 verses. Al-Baqarah has exactly 286. Every surah has a fixed, known, immutable verse count.
Our system had this:
java
public record AyahRankInSurah(int value) {
public AyahRankInSurah {
if (value < 1)
throw new IllegalArgumentException("rank must be >= 1");
}
}Looks fine right? But nothing stopped this from happening anywhere in the codebase:
java
new Ayah(surahId_alFatiha, new AyahRankInSurah(300), ...)Verse 300 of Al-Fatiha. Doesn't exist. Never existed. Never will. But our system would happily create it.
Why it's tricky
The >= 1 check is easy — the value object knows that itself. But rank <= maxForThisSurah requires external knowledge. The Ayah doesn't know how many verses its surah has. That data lives in a JSON file loaded by a provider.
So we had:
The data => done
The rule => done
The enforcement => :((
What we tried first
Put the check in the use case:
java
// application layer
int max = metadataProvider.getMaxAyahForSurah(surahId);
if (rank > max) throw new InvalidAyahRankException(...);
ayahRepository.save(new Ayah(...)); // still directly constructableThe problem? Anyone can bypass the use case and construct an Ayah directly. The invariant lives one layer above the object it protects. That's not an invariant, that's just a hope.
edit :
im looking for the solution .
im not junior yet so every suggestion would be appreciated <33


