Return to site

🚫🔤 AVOID STRINGS WHEN TYPES FIT BETTER

· java,cleancode,programmmer

🔸 TL;DR

Strings are a poor substitute for real types. If the data is a number, boolean, enum, date/time, money, or a composite/value object, model it as such. You’ll gain validation, discoverability, compiler checks, and clearer intent. 🧠✅

Section image

🔸 WHY STRINGS ARE A POOR SUBSTITUTE

▪️ Hard to validate at compile time (everything looks “valid”).

▪️ Encourage magic values (“YES”, “Y”, “true”, “1”…).

▪️ Fragile parsing & comparisons; easy i18n and casing bugs.

▪️ Hide domain meaning—future readers must guess intent.

▪️ Block IDE refactors and auto-completion. 🛠️

🔸 WHAT TO USE INSTEAD

▪️ Numeric? Use int, long, BigDecimal (for money/precision). 🔢

▪️ Boolean? Use boolean/Boolean. ✔️/❌

▪️ Choice set? Use an enum (Status.ACTIVE, not "active"). 🧩

▪️ Date/Time? Use LocalDate, Instant, ZonedDateTime. 📅

▪️ IDs with rules? Use typed value objects (Email, OrderId). 🏷️

▪️ Units? Use types that encode units (Duration, Period, domain classes). ⏱️

▪️ Aggregates? Create records/classes with named fields, not delimited strings. 📦

🔸 QUICK EXAMPLES (JAVA)

▪️ "true" ➜ boolean subscribed

▪️ "42" ➜ int retries

▪️ "ACTIVE" ➜ enum Status { ACTIVE, SUSPENDED }

▪️ "2025-11-09" ➜ LocalDate goLive

▪️ "john@acme.com" ➜ record Email(String value) { /* validate format */ }

▪️ "10:EUR" ➜ record Money(BigDecimal amount, Currency currency) {}

🔸 TAKEAWAYS

▪️ Model intent, not storage.

▪️ Let the type system catch bugs early.

▪️ Your future self (and teammates) will thank you. 🙏

▪️ Refactor strings into strong types as soon as you see rules or invariants emerging.

#CleanCode #Java #TypeSafety #Refactoring #SoftwareEngineering #DomainModeling #DDD #SpringBoot #BestPractices #CodeQuality

Go further with Java certification:

Java👇

Spring👇

SpringBook👇