Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

A record Email(String value) is used across a codebase. Where should normalisation (lowercase, trim) and validation go, and how do you avoid creating invalid instances through deserialization?

Put both the normalisation and the validation in the compact canonical constructor of Email, because every way of creating a record, including Java deserialization and Jackson, goes through the canonical constructor. Lowercase with Locale.ROOT so the result does not depend on the server's locale, keep the checks cheap because they run for every instance, and add a static factory such as Email.parse that returns an Optional or a result for untrusted user input while the constructor stays strict.

Why this question is asked

Small value types such as Email, Isbn or CountryCode spread through a codebase quickly. If each caller trims and lowercases on its own, we get duplicate accounts for Ada@Example.com and ada@example.com, and validation that differs between the web layer and the batch importer. Interviewers ask this design question to see whether we know where a record's rules belong and whether we know every path by which an instance can be created. In this answer, we will see the problem with scattered rules, move them into the compact constructor, check that deserialization cannot bypass it, deal with the locale trap, and add a factory for input that may be invalid.

1The Problem With Rules Scattered Across Callers

Start with the plain record and two callers that each clean the value a little differently. One trims, the other lowercases, and neither is wrong on its own.

Java
record Email(String value) {}
Email a = new Email(form.get("email").trim()); // " Ada@Example.com" -> "Ada@Example.com"
Email b = new Email(csvRow[2].toLowerCase()); // "ada@example.com"
System.out.println(a.equals(b)); // false: same person, two different values
Email c = new Email("not an email"); // accepted

So the same address produces two unequal records, a Set<Email> holds both, and a lookup by email misses. Worse, an invalid value is accepted and travels until something deep in the system fails on it. The type is called Email but promises nothing.

2Moving Normalisation and Validation Into the Compact Constructor

A compact canonical constructor runs for every construction, and it may reassign its parameters before the compiler stores them in the fields. That makes it the natural single place for both jobs: first normalise, then validate the normalised value.

Java
record Email(String value) {
private static final Pattern SHAPE = Pattern.compile("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$");
Email {
Objects.requireNonNull(value, "email");
value = value.strip().toLowerCase(Locale.ROOT);
if (value.length() > 254 || !SHAPE.matcher(value).matches()) {
throw new IllegalArgumentException("invalid email");
}
}
}
System.out.println(new Email(" Ada@Example.com ").value()); // ada@example.com
System.out.println(new Email("Ada@Example.com").equals(new Email("ada@example.com"))); // true
new Email("not an email"); // IllegalArgumentException

Now every Email in the program is trimmed, lowercased and shaped like an address, and equal addresses are equal records. Notice that the pattern is compiled once into a static field. Validation runs for every instance, including every row of a large import and every message read from a queue, so it must stay cheap: a precompiled pattern and a length check, not a DNS lookup or a database query.

A small word of honesty about lowercasing: strictly, the part before the @ may be case sensitive, but almost no real mail system treats it that way, and most products decide to lowercase. That is a product decision; whichever we choose, it belongs in this one place.

3Why Deserialization Cannot Bypass It

The second half of the question is about instances created without our code calling new. For ordinary classes this was a real risk: Java serialization rebuilt objects without running their constructors, and many JSON libraries used a no-argument constructor and then set fields by reflection. Records close both doors.

Step throughJSON request becomes an Email
ClientSpring MVCJacksonEmail record
POST {"value": " Ada@Example.com "}
readValue(body, Signup.class)
canonical constructor(" Ada@Example.com ")
strip, lowercase(ROOT), validate
Email[value=ada@example.com]
Signup with valid Email

6 messages in order. Play them, or step through them one at a time.

Jackson and Java serialization both create records through the canonical constructor, so the checks always run.

Java serialization always deserializes a record by reading the component values from the stream and calling the canonical constructor with them. Jackson, since version 2.12, binds JSON to records through the canonical constructor as well, because records have no setters and their fields are final. So a JSON body of {"value": "ADA@EXAMPLE.COM "} arrives as an Email with value ada@example.com, and {"value": "oops"} fails during binding. In Spring MVC that failure surfaces as an HttpMessageNotReadableException, which we can map to a 400 response. Reflection cannot help an attacker either: Field.set on a record's final field throws IllegalAccessException even after setAccessible(true).

4The Locale Trap in toLowerCase

String.toLowerCase() without an argument uses the JVM's default locale. In most locales that is harmless, but in Turkish the uppercase I lowercases to a dotless i, which is a different character.

Java
Locale.setDefault(Locale.forLanguageTag("tr"));
System.out.println("ADMIN@SITE.IO".toLowerCase()); // each I becomes a dotless i (U+0131), not ASCII
System.out.println("ADMIN@SITE.IO".toLowerCase(Locale.ROOT)); // admin@site.io

So the same input could produce different records on a server configured for Turkey, breaking equality and lookups across machines. Locale.ROOT is the neutral locale meant for machine values such as identifiers and protocol strings, and it gives the same result everywhere. The same advice applies to toUpperCase and to String.format with numbers.

5A Factory for Input That May Be Invalid

A strict constructor is right for the internal model, but for raw user input an exception is an awkward way to report a typo. A static factory gives callers a softer entry point without weakening the type.

Java
record Email(String value) {
Email { /* normalise and validate as above */ }
static Optional<Email> parse(String raw) {
try {
return Optional.of(new Email(raw));
} catch (IllegalArgumentException | NullPointerException e) {
return Optional.empty();
}
}
}
System.out.println(Email.parse("Ada@Example.com")); // Optional[Email[value=ada@example.com]]
System.out.println(Email.parse("oops")); // Optional.empty

Notice that parse goes through the constructor, so there is still only one set of rules. If the form needs to show why a value was rejected, parse can return a small sealed result type with Valid and Invalid variants instead of an Optional. For HTTP bodies, we can also put Bean Validation annotations such as @Email on request DTO components so the API returns field-level messages, while the Email record remains the final guard.

6Follow-up questions

Should the constructor ever call a database to check that the address is unique?

No. Uniqueness is a business rule that depends on other data, and constructors run during every deserialization, so a database call there would make reading a message depend on the database being reachable. The record checks local invariants; the service layer checks uniqueness, usually backed by a unique index.

Does Spring Data or JPA bypass the record constructor?

Records cannot be JPA entities, so the question usually comes up for embeddables or projections. Hibernate creates record embeddables and projections through their canonical constructor, so the rules still run. If you map Email with an AttributeConverter, the converter calls new Email(...) and the constructor runs there too.

What if old stored data contains addresses that the new rule rejects?

Then loading that data fails, so tightening the rule is a data migration as well as a code change. Clean or quarantine the old rows first, or keep the constructor rule compatible with what was stored, and apply stricter checks only at the point where new input enters the system.

7Conclusion

In this answer, we moved normalisation and validation of Email into its compact canonical constructor, so every instance is trimmed, lowercased with Locale.ROOT and checked once. We saw that Java serialization and Jackson both create records through the canonical constructor, so deserialization cannot produce an invalid Email, and that reflection cannot change record fields. We kept the checks cheap because they run for every instance, and added Email.parse returning an Optional for raw user input while the constructor stays strict.

What to say in the interviewAbout 90 seconds aloud

Open with

I would put both normalisation and validation in the compact canonical constructor of the Email record. Inside it I first reassign the parameter, value = value.strip().toLowerCase(Locale.ROOT), and then check it: not null, not too long, matches a precompiled pattern, otherwise throw IllegalArgumentException.

Then, if they want more

The compiler assigns the field after my code, so an invalid Email can never exist, and equal addresses become equal records, which fixes duplicate keys and failed lookups.

The reason this also covers deserialization is that records have no setters and final fields, so Java serialization always rebuilds a record by calling the canonical constructor, and Jackson since 2.12 binds records through the canonical constructor too. In Spring MVC, a bad email in a request body fails during binding and I map that to a 400.

Reflection cannot change record fields either. I use Locale.ROOT because toLowerCase with the default locale behaves differently in Turkish, where I becomes a dotless i, so the same input could give different values on different servers.

Because the constructor runs for every instance, including every message from a queue, I keep it cheap: no database or network calls, uniqueness belongs in the service layer. And for raw user input I add a static Email.parse that returns Optional or a small result type, so forms do not rely on exceptions, while the constructor stays strict.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A record Email(String value) is used across a codebase. Where should normalisation...": https://scrivio-interview-library.netlify.app/java/records/23add9bec6/