InsightBefore this article, read Java OOP: Four Pillars, Relationships, and Generics.
You enter your password, press Sign in, and expect the application to let you in.
A week later, your company asks for another option: “Can employees sign in with their company account?”
Then another requirement arrives: disabled users must not get access, even if their password is correct. And the security team wants a saved login record and an email alert.
The login page still has one button. Behind that button, several different jobs now need to work together. 🔐
This is where design principles become useful. They help us decide which object owns each job, which parts may change, and what callers can safely expect.
We will build the design of a login and authentication service, not memorize twelve definitions and hope they make sense later.
🧭 What Are We Going to Build?

Imagine a business application used by customers and employees. It supports:
Password login: The user submits local credentials.
Company SSO: The user signs in through the company’s identity provider.
Account checks: A verified identity must map to an application account that is allowed to sign in.
A browser session: After the application accepts the login, the framework establishes the authenticated session.
A saved login record and alert: In our example’s product requirements, each accepted login must have a saved record and a pending notification.
SSO means Single Sign-On. An employee signs in through their organization’s identity system instead of creating another password for our application.
We are not building our own password-hashing algorithm or identity protocol. We use established security components and organize the surrounding application clearly.
Spring Security is a concrete Java reference: it separates authentication management, providers, and success/failure handling. Our application contracts below are simplified teaching boundaries, not copies of every Spring interface. Spring Security authentication architecture
First, Separate Two Questions
Authentication asks: “Who are you?”
The application checks the proof supplied by the user or identity provider.
Authorization asks: “What are you allowed to do?”
A successfully verified employee may still have no access to an administrator page. Similarly, a disabled application account must not be admitted merely because its identity proof is valid.
In this article, we focus on identity verification and the application policy that decides whether sign-in is allowed. Permissions on individual resources need their own checks.
Follow One Sign-In Request
The user starts a password login or company SSO.
The relevant security component verifies the proof.
The application finds the account linked to that verified identity.
The account policy checks whether sign-in is allowed.
The application commits its login record and pending alert together.
After acceptance, the framework establishes the browser session.
A worker sends the alert later.
If verification fails, we stop. If the account is disabled, we stop. We do not “fall back” to allowing access.
The database record in step 5 is not the browser session. Keeping those ideas separate will prevent confusion when we discuss transactions.
🧱 The Few Objects You Need to Understand
An interface is a contract: it describes what a caller can ask for. A class implementing the interface supplies the behavior. An adapter connects our contract to a framework, database, or external service.
Our main collaborators are:
IdentityVerifier: Verify proof and return a trusted identity.
AccountLookup: Find the application account linked to that identity.
LoginPolicy: Decide whether that account may sign in.
LoginWriter: Save the login record and pending alert together.
NotificationWorker: Attempt alert delivery after the transaction commits.
LoginService: Coordinate the application workflow.
A collaborator is simply another object that helps a class do its job. You do not need a separate microservice for each collaborator.
💻 A Note About the Code
The focused examples explain one decision at a time. The runnable example later joins the decisions together using Java 17.
The runnable verifier is explicitly a test fixture, not a real password or SSO implementation. Real verification and browser-session security belong to Spring Security or another maintained security framework.
This is an original educational design based on documented capabilities. It is not a claim about a particular company’s private implementation.
🎯 Why Interviewers Care About These Principles
An interviewer may say, “Add company SSO,” or “The email provider is down.”
They are not just checking whether you remember what the letter O stands for. They are checking whether you can explain:
What changes, and what stays stable?
Which object owns the new behavior?
Can an implementation be replaced safely?
What happens on failure?
Can you test the business decision without a real database or identity provider?
Does the abstraction solve a real problem?
A good answer connects a principle to a specific design decision.
“I separated email delivery from login persistence so an email outage does not hold a database transaction open.”
That teaches the interviewer more than “My design follows SOLID.”
🧩 SOLID: Five Questions About the Same Login Service

S — Single Responsibility: Who owns each job?
O — Open/Closed: Where does a new login method fit?
L — Liskov Substitution: Does a replacement keep the promises callers rely on?
I — Interface Segregation: What does this particular caller need?
D — Dependency Inversion: Does application policy depend on contracts or technical details?
These principles work together. None requires an interface for every class.
1. 🎯 S — Single Responsibility Principle

A module should have one coherent reason to change.
In simple words: give a class a clear job, and avoid mixing jobs that change for unrelated reasons.
Robert C. Martin connects a responsibility to the people requesting its changes. A password-verification change and an email-template change may come from different owners. They should not both force edits to one large login class. Original SRP explanation
⚠️ The Problem: One Class Owns Everything
Imagine one LoginEverything class containing password checks, SSO calls, account rules, SQL, session handling, and email formatting.
A developer fixing an email template now has to navigate security code. A database change affects the same file as credential verification.
The problem is not that the class has six methods. The problem is that it has several independent reasons to change.
✅ Give Each Responsibility a Home
The verifier owns proof checking. The policy owns the account rule. The writer owns the database transaction. The worker owns delivery.
The service coordinates them:
import java.time.Clock;
import java.util.UUID;
final class LoginService {
private final IdentityVerifier verifier;
private final AccountLookup accounts;
private final LoginPolicy policy;
private final LoginAlertTemplate alertTemplate;
private final LoginWriter writer;
private final Clock clock;
LoginService(
IdentityVerifier verifier,
AccountLookup accounts,
LoginPolicy policy,
LoginAlertTemplate alertTemplate,
LoginWriter writer,
Clock clock) {
this.verifier = verifier;
this.accounts = accounts;
this.policy = policy;
this.alertTemplate = alertTemplate;
this.writer = writer;
this.clock = clock;
}
LoginRecord login(LoginRequest request) {
VerifiedIdentity identity = verifier.verify(request);
Account account = accounts.find(identity.key())
.orElseThrow(LoginRejected::new);
policy.check(account);
LoginRecord record = new LoginRecord(
UUID.randomUUID().toString(),
account.id(),
request.method(),
clock.instant()
);
LoginAlert alert = alertTemplate.create(record, account);
// Save the login record and pending alert together.
// A worker delivers the alert after commit.
writer.save(record, alert);
return record;
}
}🧠 Why This Demonstrates SRP
Each object has a clear job:
IdentityVerifier: Verify the user’s proof.
AccountLookup: Find the linked application account.
LoginPolicy: Decide whether that account may sign in.
LoginAlertTemplate: Prepare the alert message.
LoginWriter: Save the record and pending alert together.
LoginService: Coordinate the login process.
Now, changing the alert wording means changing LoginAlertTemplate—not editing verification or database code.
The service still calls several collaborators. That does not violate SRP: it owns the sequence, while its collaborators own the details.
📨 A More Realistic Boundary: The Transactional Outbox

Our product requires a saved login record and a pending alert for each accepted sign-in.
We cannot make the database and an email provider behave like one local transaction.
If we save the record and then crash before sending the email, the alert can be missed. If we send first and saving fails, the alert can describe an operation the application did not record.
Instead, the writer saves two things in one transaction:
The login record.
A durable instruction to send the alert.
A worker reads that instruction and sends the email later. This is the Transactional Outbox pattern.
Think of it as a saved to-do item. The transaction records both what happened and the work that must follow.
This improves recovery and separates jobs. It does not guarantee inbox delivery or make browser-session creation atomic with the database. We will walk through the database code and failure cases later.
🧠 One Responsibility Can Need Several Methods
A login policy may check account status and tenant membership. Those checks can belong together if they support one coherent admission policy.
SRP is not “one method per class.” Splitting every line into a separate class can make the workflow harder to follow.
🎤 SRP Interview Practice
Beginner — Does SRP mean one method per class?
No. It means one coherent responsibility, which may require several methods.
Intermediate — Does LoginService violate SRP because it calls four collaborators?
No. It owns workflow coordination. The collaborators own verification, lookup, policy, and storage details.
Advanced — Why keep email delivery outside the transaction?
The email provider has independent network failures and timing. Save the intent transactionally, then let a worker attempt delivery.
An answer you can say aloud:
“I kept the login workflow separate from proof verification, persistence, and email delivery because those parts change for different reasons.”
2. 🚪 O — Open/Closed Principle

Support new behavior through useful extension points instead of repeatedly rewriting stable behavior.
Our application starts with password login. Then the company asks for SSO.
We want to add the method-specific verification without copying the entire login workflow.
⚠️ The Naive Approach
One method grows several branches:
// Conceptual sketch: protocol implementations are not shown.
if (method == PASSWORD) {
// Password verification, account checks, saving, email...
} else if (method == COMPANY_SSO) {
// SSO verification, duplicated account checks, saving, email...
}Soon the two branches enforce slightly different account rules. A new login method adds another copy.
✅ Keep the Workflow Behind a Stable Contract
import java.util.Map;
import java.util.Objects;
public class IdentityVerifierDemo {
enum LoginMethod {
PASSWORD,
COMPANY_SSO
}
record LoginRequest(LoginMethod method, String proof) {
LoginRequest {
Objects.requireNonNull(method);
Objects.requireNonNull(proof);
}
@Override
public String toString() {
return "LoginRequest[method=" + method + ", proof=REDACTED]";
}
}
record IdentityKey(String issuer, String subject) {
IdentityKey {
Objects.requireNonNull(issuer);
Objects.requireNonNull(subject);
if (issuer.isBlank() || subject.isBlank()) {
throw new IllegalArgumentException(
"Identity fields are required"
);
}
}
}
record VerifiedIdentity(IdentityKey key) {
VerifiedIdentity {
Objects.requireNonNull(key);
}
}
static final class LoginRejected extends RuntimeException {
LoginRejected() {
super("Unable to verify identity");
}
}
interface IdentityVerifier {
// Return a verified identity, or reject the request.
VerifiedIdentity verify(LoginRequest request);
}
// TEST ONLY: fixture labels simulate password-verification outcomes.
// This is not a real password-checking implementation.
static final class PasswordFixtureVerifier
implements IdentityVerifier {
@Override
public VerifiedIdentity verify(LoginRequest request) {
if (request.method() != LoginMethod.PASSWORD
|| !"VALID_PASSWORD_FIXTURE".equals(request.proof())) {
throw new LoginRejected();
}
return new VerifiedIdentity(
new IdentityKey("local", "user-42")
);
}
}
// TEST ONLY: fixture labels simulate trusted SSO-verification outcomes.
// Comparing a string does not validate an actual SSO token.
static final class CompanySsoFixtureVerifier
implements IdentityVerifier {
@Override
public VerifiedIdentity verify(LoginRequest request) {
if (request.method() != LoginMethod.COMPANY_SSO
|| !"VALID_SSO_FIXTURE".equals(request.proof())) {
throw new LoginRejected();
}
return new VerifiedIdentity(
new IdentityKey(
"https://identity.example",
"employee-7"
)
);
}
}
// Select the verifier registered for the requested login method.
static final class RoutingIdentityVerifier
implements IdentityVerifier {
private final Map<LoginMethod, IdentityVerifier> providers;
RoutingIdentityVerifier(
Map<LoginMethod, IdentityVerifier> providers) {
this.providers = Map.copyOf(providers);
}
@Override
public VerifiedIdentity verify(LoginRequest request) {
IdentityVerifier selected =
providers.get(request.method());
if (selected == null) {
throw new LoginRejected();
}
return selected.verify(request);
}
}
public static void main(String[] args) {
IdentityVerifier verifier =
new RoutingIdentityVerifier(Map.of(
LoginMethod.PASSWORD,
new PasswordFixtureVerifier(),
LoginMethod.COMPANY_SSO,
new CompanySsoFixtureVerifier()
));
verifyAndPrint(verifier, new LoginRequest(
LoginMethod.PASSWORD,
"VALID_PASSWORD_FIXTURE"
));
verifyAndPrint(verifier, new LoginRequest(
LoginMethod.COMPANY_SSO,
"VALID_SSO_FIXTURE"
));
verifyAndPrint(verifier, new LoginRequest(
LoginMethod.PASSWORD,
"INVALID_FIXTURE"
));
verifyAndPrint(verifier, new LoginRequest(
LoginMethod.COMPANY_SSO,
"INVALID_FIXTURE"
));
}
// The shared caller knows the interface, not provider details.
static void verifyAndPrint(
IdentityVerifier verifier,
LoginRequest request) {
try {
VerifiedIdentity identity = verifier.verify(request);
System.out.println(
request.method() + " -> verified: "
+ identity.key().issuer() + " / "
+ identity.key().subject()
);
} catch (LoginRejected failure) {
System.out.println(
request.method() + " -> rejected"
);
}
}
}The service asks for a verified identity. It does not need to know how an OIDC callback or password hash is checked.
The verification boundary selects the appropriate method-specific component. The common application workflow continues after verification.
When adding another provider, update the provider configuration or adapter registration and test the integration. The common account policy and persistence workflow can remain unchanged.
Open for extension does not mean “no file ever changes.”
🧭 Four Ideas That Make This Clear
- The Main System Only Cares About the Contract
The main LoginService has one simple job: it coordinates the application workflow, including account checks and saving the login record and pending alert. The framework creates the browser session after acceptance. It expects a clean contract that says, “Verify this request.” It does not want to know messy transport details, like the exact HTTP payload format of a third-party provider.
- Keep Shared Logic and Variations Separate
When you add a new login method, you change only the specific verification plugin (the variation point). You do not change or duplicate the shared, high-level workflow code—such as creating the user account or saving the login history database entry.
- Use the Strategy Pattern to Swap Behaviors
This setup uses the Strategy Pattern. It places different authentication mechanisms behind a single, common contract. This separates method-specific verification logic (like OTP validation) away from the core, unchanging shared login workflow.
- Different Logins Need Different Inputs
A password string and a Google SSO authorization token are completely different types of data. While a generic “request envelope” hides these details from the main engine, the specific plugins (adapters) must still accept and validate their own highly typed, unique inputs.
Spring Security’s provider architecture is a real example of method-specific authentication behind shared orchestration. Authentication architecture
🎬 A Real-World Reference: Netflix’s Conductor

Conductor originated at Netflix. A workflow engine coordinates steps and keeps track of their progress; the published project separates that engine from persistence modules. The original Netflix repository is archived, so this is a documented design reference—not a claim about Netflix’s current private implementation. Netflix Conductor repository
🗄️ Pluggable Storage, in Simple Words
A workflow engine needs to save its progress.
If database commands are scattered throughout the engine, changing the database also means changing orchestration logic.
Conductor exposes contracts for:
Metadata: The definitions of workflows and tasks.
Execution: The progress of running workflows.
Indexing: Information used to search executions.
Queues: Tasks waiting to be processed.
A storage implementation supplies those capabilities. Our OCP interpretation is that storage details can vary behind the engine’s established boundaries. Conductor source and documentation
Imagine a deployment now requires workflow records in a regional PostgreSQL database.
If SQL commands are mixed into orchestration logic, engineers must change the engine as well as storage. With suitable contracts, a PostgreSQL adapter can own those commands while the engine continues asking for the same capabilities.
That is an illustrative requirement, not a reported Netflix migration or a claim that an adapter alone satisfies data-residency law.
A different adapter still needs configuration, migration, and tests. An interface does not make two databases identical or protect against every failure.
🧩 Custom Tasks, in Simple Words
The engine knows how to coordinate work; the worker knows how to perform its specific job.
Imagine a video-processing workflow needs a content-checking step before encoding. An external worker can perform the check and report its result. The engine coordinates the next step; it does not need the scanning algorithm inside its own code. This scenario is illustrative, not a reported Netflix feature.
Conductor also documents custom system-task extension and registration. A plug-in does not automatically isolate failures. Conductor source and documentation
Connection to our login service: The login workflow coordinates the process. A provider adapter owns its verification details. Put new behavior where that behavior belongs.
🎤 OCP Interview Practice
Beginner — Does OCP ban editing existing code?
No. Bug fixes, changed contracts, and configuration can require edits.
Intermediate — Where do you add a new SSO provider?
At the verification adapter or framework configuration boundary, while keeping the common workflow stable where its requirements have not changed.
Advanced — Does OCP remove integration risk?
No. New providers still need configuration, security checks, and shared-contract tests.
An answer you can say aloud:
“I separated provider-specific verification from the common workflow, so adding a provider does not require rewriting account checks and persistence.”
3. 🔄 L — Liskov Substitution Principle

A replacement must keep the promises of the contract its caller depends on.
The compiler checks whether the required methods exist. LSP asks whether those methods behave honestly.
This is the idea of behavioral subtyping described by Liskov and Wing. Original paper
At its core, LSP means that if you have a parent contract (an interface or base class), every single child class extending it must honor the exact same business rules and behavioral promises.
If a child class compiles perfectly but secretly alters, weakens, or skips those fundamental business rules, it violates LSP. This is dangerous because the main system expects every child to act honestly. When a child behaves unpredictably, it can introduce hidden logic bugs or security flaws, making it impossible to safely replace the parent with that child. In short: Software signatures get you through the compiler, but behavioral honesty satisfies LSP.
🔐 Our Promise: Success Means the Proof Was Verified
For IdentityVerifierwe agree:
Valid proof for a supported method returns the correctly verified identity.
Invalid or unsupported proof is rejected.
Provider outages are reported as operational failures, never converted into a successful login.
The verifier does not create a session, send an alert, or invent account permissions.
We can replace the internal verification implementation. We cannot weaken “verified” into “someone submitted a request.”
⚠️ The Bad Replacement
Someone creates an “easy login” verifier:
final class UnsafeVerifier implements IdentityVerifier {
private final IdentityKey identity;
UnsafeVerifier(IdentityKey identity) {
this.identity = identity;
}
@Override
public VerifiedIdentity verify(LoginRequest request) {
// Deliberately broken: no proof is checked.
return new VerifiedIdentity(identity);
}
}It compiles. It satisfies the method signature.
But the caller assumes that receiving VerifiedIdentity means verification happened. This replacement returns success for invalid proof, breaking that assumption and allowing unauthorized access.
That is the LSP violation. It does not need an exception to be wrong.
✅ Test the Same Promise Against Each Implementation
import java.util.Objects;
public class VerifierContractTest {
record LoginRequest(String proof) {
LoginRequest {
Objects.requireNonNull(proof);
}
}
record VerifiedIdentity(String userId) {
VerifiedIdentity {
Objects.requireNonNull(userId);
}
}
static final class LoginRejected extends RuntimeException {
LoginRejected() {
super("Unable to verify identity");
}
}
interface IdentityVerifier {
VerifiedIdentity verify(LoginRequest request);
}
// TEST FIXTURE ONLY: not real password verification.
static final class PasswordFixtureVerifier
implements IdentityVerifier {
@Override
public VerifiedIdentity verify(LoginRequest request) {
if (!"VALID_PASSWORD_FIXTURE".equals(request.proof())) {
throw new LoginRejected();
}
return new VerifiedIdentity("user-42");
}
}
// Deliberately broken: returns success without checking proof.
static final class UnsafeVerifier implements IdentityVerifier {
@Override
public VerifiedIdentity verify(LoginRequest request) {
return new VerifiedIdentity("user-42");
}
}
// Shared contract test: invalid proof must be rejected.
static void requireRejected(
IdentityVerifier verifier,
LoginRequest invalidRequest) {
try {
verifier.verify(invalidRequest);
} catch (LoginRejected expected) {
return; // Expected rejection: the test passes.
}
// Verification returned normally, meaning invalid proof was accepted.
throw new AssertionError("Invalid proof was accepted");
}
public static void main(String[] args) {
LoginRequest invalidRequest =
new LoginRequest("INVALID_FIXTURE");
// The correct fixture rejects invalid proof.
requireRejected(
new PasswordFixtureVerifier(),
invalidRequest
);
System.out.println(
"PasswordFixtureVerifier: PASS - invalid proof rejected"
);
// The unsafe implementation fails the same test.
try {
requireRejected(
new UnsafeVerifier(),
invalidRequest
);
System.out.println("UnsafeVerifier: PASS");
} catch (AssertionError failure) {
// Catch only to display the deliberately failing test.
System.out.println(
"UnsafeVerifier: FAIL - " + failure.getMessage()
);
}
}
}Run the same rejection check against each implementation, using invalid input appropriate to the method it supports.
A correct verifier rejects it. The unsafe verifier fails the check.
This is only one contract test. Also test valid proof, identity mapping, unsupported methods, provider failures, and protocol-specific checks.
🧠 The Formal Terms Without the Mystery
Precondition: What must the caller provide? A replacement must not demand stricter input than the contract promises to accept.
Postcondition: What does success guarantee? A replacement must not weaken “identity verified” into “identity guessed.”
Invariant: What must remain valid? Required identity fields and account-state rules must stay valid.
History constraint: What changes over time are allowed? A subtype must not introduce mutations that break an abstraction’s immutability promise.
A documented exception is not automatically a violation. A network-backed verifier can report an agreed operational failure. Returning success because verification is unavailable is a different matter.
✅ The Right Fix
Keep insecure test shortcuts out of production verification.
Use test fixtures to simulate trusted results inside tests, with clear names and controlled wiring. They are not replacements for real security checks in a deployed application.
Also, do not “prove LSP” by sending a password to an OIDC-only component. Method-specific supported inputs belong in the contract. Substitution must be judged within that agreed scope.
🎤 LSP Interview Practice
Beginner — What is LSP in one sentence?
A replacement must preserve the behavior promised by the type the caller uses.
Intermediate — Why does UnsafeVerifier violate it?
It returns a verified identity without checking proof, so success no longer means what the caller expects.
Advanced — Must every implementation produce identical internal behavior?
No. Internals may differ. The common observable guarantees must hold.
An answer you can say aloud:
“If the caller trusts a successful result to mean identity was verified, every implementation must preserve that guarantee. Compiling is not enough.”
4. 🧩 I — Interface Segregation Principle

A caller should not depend on operations it does not need.
Imagine this broad account interface:
interface AllAccountOperations {
Optional<Account> find(IdentityKey key);
void resetPassword(String accountId, String resetProof);
void save(LoginRecord record, LoginAlert alert);
}A login workflow needs account lookup and login persistence. It does not need password-reset operations.
An SSO-only account adapter might not manage a local password at all. Forcing it to implement reset behavior creates an inaccurate contract.
✅ Separate Useful Capabilities
interface AccountLookup {
Optional<Account> find(IdentityKey key);
}
interface LoginWriter {
void save(LoginRecord record, LoginAlert alert);
}
interface PasswordResetter {
// A real implementation validates reset proof and policy.
void resetPassword(String accountId, String resetProof);
}Each client depends on the capability it uses.
A class may implement several interfaces. We are separating what callers see, not necessarily demanding a different class for every operation.
🧠 Small Does Not Mean One Method
A password-reset capability may need request creation, proof consumption, and password replacement. Those operations can form one coherent contract.
ISP is about client needs—not making interfaces as tiny as possible.
🎤 ISP Interview Practice
Beginner — Why avoid a huge account interface?
It couples callers to unrelated capabilities and can force implementations to pretend they support operations they cannot perform.
Intermediate — Can one class implement several small interfaces?
Yes. Clients can still depend on only the capabilities they need.
Advanced — How is ISP different from SRP?
SRP considers a module’s responsibility. ISP considers the operations a particular client must depend on.
An answer you can say aloud:
“My login workflow depends on lookup and recording, not account administration or password-reset operations.”
5. 🔌 D — Dependency Inversion Principle

Application policy should depend on suitable contracts, not be tied directly to technical implementations.
Imagine you are building a LoginService or a controller. Instead of directly hardcoding an external vendor SDK (like AWS or Google Login) or writing raw database queries inside that class, you establish an abstract boundary. You create a clean interface—acting as a standard “socket”—that defines the capability you need (e.g., verifyUser).
Different technical implementations (like an AWS adapter, a Google adapter, or an in-memory test double) can then be engineered to plug directly into that socket. By passing this abstract socket into your class constructor, your core application can trigger operations seamlessly without ever knowing or caring which specific vendor or database is working behind the scenes. This decouples your core architecture, leaving it completely adaptable and easily testable.
Our login rule is: verify identity, find the account, check admission, and save the required record.
That rule should not be written in terms of a vendor SDK or SQL driver.
The “Wall Socket” Analogy
Imagine you are building a Core Power Grid for a house.
The Wrong Way: You hardwire a specific brand of microwave directly into the kitchen wall wires. If that microwave breaks, or if you want to switch it out for a coffee maker, you have to tear down the entire wall and rewrite the electrical wiring.
The DIP Way: You install a standard three-prong electrical socket in the wall. The wall grid doesn’t know or care what you plug into it. It just promises to deliver electricity to any device that fits the three-prong shape.
In this scenario:
High-Level Policy (The House): Wants electricity.
The Abstraction (The Socket): The contract defining the shape of the plugs.
Low-Level Detail (The Appliance): The actual microwave, TV, or vacuum.
⚠️ The Naive Approach
class TightlyCoupledLoginService {
// HARDWIRED! The service creates its own specific vendor tools.
private final VendorIdentitySdk verifier = new VendorIdentitySdk();
private final SqlLoginRepository repository = new SqlLoginRepository();
public void loginUser() {
verifier.checkTokenWithAWS(); // Hardcoded to AWS!
repository.saveToMySqlDatabase(); // Hardcoded to MySQL!
}
}Why is this terrible?
It’s Trapped: The core business rule of “logging in a user” is permanently glued to AWS and MySQL. If your company decides to switch to Google Login or a MongoDB database next week, you have to rip open this file and rewrite the core login logic.
Untestable: You cannot run a fast unit test on this code. To test if your login logic works, the test must actually reach out to the real internet to talk to AWS and a real running MySQL database. If the database goes down, your tests fail even if your login code is perfect.
✅ Depend on the Capabilities the Workflow Needs
InsightThis next program demonstrates dependency wiring only. Its Google, AWS, SQL, and session messages are simulated console output, not real integrations or security guarantees. Use the downloadable workflow examples at the end for the fuller account-policy and persistence model.
import java.util.Objects;
public class DependencyInversionDemo {
// ==========================================
// 🔌 THE "SOCKETS" (THE ABSTRACT CONTRACTS)
// ==========================================
// Socket 1: Responsibility is strictly checking user identity credentials
interface IdentityVerifier {
boolean verify(String tokenOrPassword);
}
// Socket 2: Responsibility is strictly saving data logs to a storage system
interface LoginRepository {
void saveLoginLog(String username, boolean status);
}
// ==========================================
// 🧠 THE CORE CORE SERVICE (USES THE SOCKETS)
// ==========================================
static final class LoginService {
// The service ONLY knows about the sockets. It has NO idea about AWS, Google, or SQL.
private final IdentityVerifier verifier;
private final LoginRepository repository;
// DIP in action: Sockets are passed (injected) through the constructor from the outside
public LoginService(IdentityVerifier verifier, LoginRepository repository) {
this.verifier = Objects.requireNonNull(verifier, "Verifier socket cannot be null");
this.repository = Objects.requireNonNull(repository, "Repository socket cannot be null");
}
public void processLogin(String username, String credential) {
System.out.println("\n[LoginService] Starting login workflow for: " + username);
// Core logic triggers the socket operations completely blind to the actual vendor logic
boolean isSuccess = verifier.verify(credential);
repository.saveLoginLog(username, isSuccess);
if (isSuccess) {
System.out.println("[LoginService] Access GRANTED. Session created successfully.");
} else {
System.out.println("[LoginService] Access DENIED. Notification triggered.");
}
}
}
// ==========================================
// 🛠️ THE PLUGS (THE TECHNICAL IMPLEMENTATIONS)
// ==========================================
// Implementation Plug A: Google Single Sign-On
static final class GoogleIdentityVerifier implements IdentityVerifier {
@Override
public boolean verify(String token) {
System.out.println(" -> [Google SDK] Reaching out to ://googleapis.com...");
return "valid-google-token".equals(token);
}
}
// Implementation Plug B: AWS Cognito Authentication
static final class AwsCognitoVerifier implements IdentityVerifier {
@Override
public boolean verify(String password) {
System.out.println(" -> [AWS SDK] Querying Amazon Cognito User Pools securely...");
return "secure-aws-password".equals(password);
}
}
// Implementation Plug C: Standard SQL Database Database
static final class SqlLoginRepository implements LoginRepository {
@Override
public void saveLoginLog(String username, boolean status) {
System.out.println(" -> [MySQL Driver] INSERT INTO login_audit (user, success) VALUES ('"
+ username + "', " + status + ");");
}
}
// Implementation Plug D: Lightweight Fast Mock for Testing
static final class FastTestMockVerifier implements IdentityVerifier {
@Override
public boolean verify(String ignored) {
System.out.println(" -> [Test Mock] Instantly returning true (No network calls!)");
return true;
}
}
// ==========================================
// 🚀 EXECUTION & ASSEMBLY ENVIRONMENT (MAIN)
// ==========================================
public static void main(String[] args) {
System.out.println("=== SCENARIO 1: ASSEMBLING PRODUCTION ENVIRONMENT WITH GOOGLE LOGINS ===");
// 1. We grab the Google and SQL concrete plugs
IdentityVerifier googleVerifier = new GoogleIdentityVerifier();
LoginRepository sqlRepo = new SqlLoginRepository();
// 2. We plug them straight into the shared Service socket architecture
LoginService prodGoogleService = new LoginService(googleVerifier, sqlRepo);
prodGoogleService.processLogin("john_doe", "valid-google-token");
System.out.println("\n=== SCENARIO 2: MIGRATING SYSTEM COMPONENT TO AWS ENTIRELY COMPATIBLE ===");
// We seamlessly swap out the Google plug for the AWS plug.
// Notice that the 'LoginService' source code is completely unchanged!
IdentityVerifier awsVerifier = new AwsCognitoVerifier();
LoginService prodAwsService = new LoginService(awsVerifier, sqlRepo);
prodAwsService.processLogin("admin_user", "secure-aws-password");
System.out.println("\n=== SCENARIO 3: HIGH SPEED UNIT TESTING ECOSYSTEM ===");
// In a test, we don't want real database writes or real network SDK delays.
// We comfortably pass in our lightweight fake test mock double instead.
IdentityVerifier testVerifier = new FastTestMockVerifier();
LoginService testService = new LoginService(testVerifier, sqlRepo);
testService.processLogin("test_runner", "any-random-dummy-input");
}
}🧠 How the Code Demonstrates DIP
The LoginService class source code remains 100% untouched throughout all three drastically different runtime execution environments.
The interfaces (IdentityVerifier and LoginRepository) serve as the boundaries preventing third-party concrete vendor leakage.
You can easily plug Google, AWS, or Test Mocks dynamically into the constructor on lines 60, 68, and 76 without breaking the core code rules.
🧭 Why Is It Called “Inversion”?
In traditional software design, high-level business rules depend on low-level technical details. Business Rules ➔ Databases/SDKs.
DIP completely flips (inverts) this relationship:
[ High-Level Business Rules (LoginService) ]
│
▼
[ Abstract Contracts / Interfaces ] <─── (The Business defines this boundary!)
▲
│
[ Low-Level Technical Details (SQL Drivers, Vendor SDKs) ]Now, the low-level details (the database code, the security SDKs) have to adapt themselves to fit the interface defined by the business logic. The source-code dependency points up toward the abstraction, not down toward the concrete tech stack.
🧠 Clearing Up the Jargon (DIP vs. DI vs. IoC)
People often use these three terms interchangeably, but they are completely different things. Think of them as a hierarchy of concepts:
DIP (The Architectural Design Principle): This is the high-level mindset of deciding that your core application shouldn’t know about specific databases or third-party companies. It’s the decision to use “sockets.”
Dependency Injection / DI (The Physical Action): This is the literal coding mechanism of passing a tool into a class constructor rather than typing new inside the class.
Crucial note: Passing a concrete vendor SDK through the constructor is dependency injection, but it does not by itself achieve DIP. If the application workflow depends directly on vendor-specific operations, that boundary remains coupled to the vendor. Not every concrete dependency needs an interface; isolate the details that should not define application policy.
Inversion of Control / IoC (The Framework Automation): This is a framework (like Spring or Micronaut) acting as the factory manager. Instead of you manually typing new LoginService(new AwsVerifier(), new MySqlWriter()) in your main execution logic, the framework reads your configuration and automatically wires all the pieces together for you at startup.
🎤 DIP Interview Practice
Beginner — Does DIP mean every dependency needs an interface?
No. Add abstractions where they isolate meaningful policy, variation, or external details.
Intermediate — How does it help testing?
The workflow can use a test verifier and writer without contacting an identity provider or database.
Advanced — Does constructor injection guarantee DIP?
No. You must still inspect what types the application depends on and whose decisions those types expose.
An answer you can say aloud:
“The login policy depends on verification and persistence contracts. Framework and database adapters implement those contracts.”
6. ♻️ DRY — Don’t Repeat Yourself

In simple words:
When several parts of your application follow the same business rule, define that rule in one place and let those parts reuse it.
DRY is not just about removing repeated lines. It is about avoiding repeated knowledge such as who can sign in, how a discount is calculated, or when an order can be cancelled. The Pragmatic Programmer
Let’s understand it through our login system.
🏢 The Real-World Problem
Imagine that your application supports two ways to sign in:
Password login: The user enters a username and password.
Company SSO: The user signs in through the company’s identity provider.
These methods verify identity differently. However, both must follow one application rule:
A disabled application account cannot sign in.
Suppose an administrator disables an employee’s account in your application. The employee’s company SSO account might still work, but that must not give them access to your application.
This gives us two separate questions:
Identity verification: Who is this person?
Application admission: Is this account allowed to sign in here?
The first question depends on the login method. The second uses our shared account rule.
About the examples
Both examples below are complete, runnable Java programs using Java 17 or later.
They demonstrate the application step after identity verification succeeds. The identities in main() are test fixtures—not real password or SSO verification.
The methods return an approved account ID. They do not create a session or issue a token.
⚠️ Before DRY: Each Handler Owns a Copy of the Rule
Here, password login and company SSO have separate handlers.
Each handler independently checks whether the account is enabled.
Save this example as DryBeforeDemo.java.
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
public class DryBeforeDemo {
record IdentityKey(String issuer, String subject) {}
// Trusted backend result AFTER password or SSO verification.
record VerifiedIdentity(IdentityKey key) {}
record Account(String id, boolean enabled) {}
interface AccountLookup {
Optional<Account> find(IdentityKey key);
}
static final class LoginRejected extends RuntimeException {
LoginRejected() {
super("Sign-in rejected");
}
}
static final class PasswordLoginHandler {
private final AccountLookup accounts;
PasswordLoginHandler(AccountLookup accounts) {
this.accounts = Objects.requireNonNull(accounts);
}
String admit(VerifiedIdentity identity) {
Account account = accounts.find(identity.key())
.orElseThrow(LoginRejected::new);
// Application rule owned by this handler.
if (!account.enabled()) {
throw new LoginRejected();
}
return account.id();
}
}
static final class CompanySsoLoginHandler {
private final AccountLookup accounts;
CompanySsoLoginHandler(AccountLookup accounts) {
this.accounts = Objects.requireNonNull(accounts);
}
String admit(VerifiedIdentity identity) {
Account account = accounts.find(identity.key())
.orElseThrow(LoginRejected::new);
// The same application rule copied into a second handler.
if (!account.enabled()) {
throw new LoginRejected();
}
return account.id();
}
}
public static void main(String[] args) {
runScenario("Enabled account:", true);
runScenario("Disabled account:", false);
}
private static void runScenario(String label, boolean enabled) {
// Test fixtures, NOT actual authentication implementations.
VerifiedIdentity passwordIdentity = new VerifiedIdentity(
new IdentityKey("local", "user-42"));
VerifiedIdentity ssoIdentity = new VerifiedIdentity(
new IdentityKey(
"https://identity.example",
"employee-7"
));
Account account = new Account("account-42", enabled);
// Both identities are linked to the same application account.
Map<IdentityKey, Account> store = Map.of(
passwordIdentity.key(), account,
ssoIdentity.key(), account
);
AccountLookup accounts =
key -> Optional.ofNullable(store.get(key));
PasswordLoginHandler password =
new PasswordLoginHandler(accounts);
CompanySsoLoginHandler sso =
new CompanySsoLoginHandler(accounts);
System.out.println(label);
showResult(
"Password",
() -> password.admit(passwordIdentity)
);
showResult(
"Company SSO",
() -> sso.admit(ssoIdentity)
);
}
private static void showResult(
String label, Supplier<String> action) {
try {
System.out.println(label + ": accepted " + action.get());
} catch (LoginRejected rejected) {
System.out.println(label + ": rejected");
}
}
}What does this code do?
The example links two verified identities to the same application account:
A local identity represents the password login.
A company identity represents the SSO login.
AccountLookup finds the application account associated with either identity.
Each handler then makes its own decision:
if (!account.enabled()) {
throw new LoginRejected();
}For an enabled account, both handlers return its ID. For a disabled account, both reject the attempt.
Why is this a problem if the code works?
The problem appears when the business rule changes.
Suppose the application introduces a new account status:
An account must be enabled and must not be suspended.
A developer updates the password handler but forgets the SSO handler.
Now the same account may be rejected through password login but accepted through SSO.
The original code worked. The duplicated ownership made it easy for the two paths to disagree later.
The duplicated knowledge is not merely a if statement. It is the rule determining whether an account may sign in.
✅ After DRY: One Policy, One Shared Workflow
We can improve the design by giving each responsibility a clear home:
Account.canSignIn() answers whether the account’s state permits sign-in.
LoginPolicy.check() enforces that answer.
LoginService.admit() runs the shared application admission workflow.
Password and SSO still verify identity differently. After verification, both use the same service.
Save this example as DryAfterDemo.java.
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
public class DryAfterDemo {
record IdentityKey(String issuer, String subject) {}
// Trusted backend result AFTER password or SSO verification.
record VerifiedIdentity(IdentityKey key) {}
record Account(String id, boolean enabled) {
boolean canSignIn() {
return enabled;
}
}
interface AccountLookup {
Optional<Account> find(IdentityKey key);
}
static final class LoginRejected extends RuntimeException {
LoginRejected() {
super("Sign-in rejected");
}
}
static final class LoginPolicy {
void check(Account account) {
if (!account.canSignIn()) {
throw new LoginRejected();
}
}
}
static final class LoginService {
private final AccountLookup accounts;
private final LoginPolicy policy;
LoginService(
AccountLookup accounts,
LoginPolicy policy) {
this.accounts = Objects.requireNonNull(accounts);
this.policy = Objects.requireNonNull(policy);
}
// Both verified login paths use this same application workflow.
String admit(VerifiedIdentity identity) {
Account account = accounts.find(identity.key())
.orElseThrow(LoginRejected::new);
policy.check(account);
return account.id();
}
}
public static void main(String[] args) {
runScenario("Enabled account:", true);
runScenario("Disabled account:", false);
}
private static void runScenario(String label, boolean enabled) {
// Test fixtures, NOT actual authentication implementations.
VerifiedIdentity passwordIdentity = new VerifiedIdentity(
new IdentityKey("local", "user-42"));
VerifiedIdentity ssoIdentity = new VerifiedIdentity(
new IdentityKey(
"https://identity.example",
"employee-7"
));
Account account = new Account("account-42", enabled);
Map<IdentityKey, Account> store = Map.of(
passwordIdentity.key(), account,
ssoIdentity.key(), account
);
AccountLookup accounts =
key -> Optional.ofNullable(store.get(key));
LoginService logins =
new LoginService(accounts, new LoginPolicy());
System.out.println(label);
showResult(
"Password",
() -> logins.admit(passwordIdentity)
);
showResult(
"Company SSO",
() -> logins.admit(ssoIdentity)
);
}
private static void showResult(
String label, Supplier<String> action) {
try {
System.out.println(label + ": accepted " + action.get());
} catch (LoginRejected rejected) {
System.out.println(label + ": rejected");
}
}
}Output from Both Examples
Enabled account:
Password: accepted account-42
Company SSO: accepted account-42
Disabled account:
Password: rejected
Company SSO: rejectedThe output stays the same because this refactoring changes the organization of the rule, not the intended behavior.
🔍 Understanding the Improved Design
- The account owns the state-based decision
boolean canSignIn() {
return enabled;
}Instead of making every caller understand which account fields determine eligibility, the account provides a meaningful operation.
The caller asks:
“Can this account sign in?”
It does not need to reconstruct the answer.
If a global suspension rule is introduced, the account’s eligibility decision can incorporate that new state. Password and SSO handlers do not need their own copies of the condition.
- The policy enforces the decision
void check(Account account) {
if (!account.canSignIn()) {
throw new LoginRejected();
}
}canSignIn() returns a decision. check() Turns a negative decision into a rejected operation.
These methods are not two copies of the same condition:
The account knows how its state affects eligibility.
The policy provides the common enforcement point.
For a smaller application, calling canSignIn() directly from the shared service may be enough. A separate policy class is useful when admission rules deserve their own focused responsibility.
DRY does not require adding a class for every condition.
- The shared workflow makes reuse straightforward
Account account = accounts.find(identity.key())
.orElseThrow(LoginRejected::new);
policy.check(account);
return account.id();Both login methods use this workflow after identity verification.
That matters because simply creating LoginPolicy is not sufficient. If one handler forgets to call it, the rule can still be bypassed.
The shared workflow gives both paths the same enforcement point.
- Different verification methods remain separate
Password verification and company SSO verification are not the same business operation.
We should not combine them into one large method just to reduce the number of classes.
The useful boundary is:
Different ways to prove identity, followed by one shared application admission policy.
🛠️ How to Apply DRY in a Real Project
Step 1: Identify the knowledge being repeated
Start by describing the rule in plain English.
In our example:
Disabled application accounts cannot sign in through any supported login method.
This is more useful than saying, “These methods contain the same three lines.”
Step 2: Confirm that the rule really is shared
Ask:
If this requirement changes, should every caller change in the same way?
For the disabled-account rule, the answer is yes.
However, a password-specific rule may not apply to SSO. For example, requiring a local password reset does not automatically mean company SSO should be blocked.
Share rules because their meaning is the same—not because their code happens to look similar.
Step 3: Choose a meaningful owner
Use a name that describes the responsibility:
LoginPolicy
Avoid putting unrelated rules into a catch-all class such as:
CommonUtils
A focused name helps future developers find and reuse the rule.
Step 4: Connect every relevant entry point
In a production application, the password route and the SSO callback should both reach the application admission check before access is granted.
Keep actual authentication in the appropriate security components. For example, Spring Security has password authentication support through DaoAuthenticationProvider and separate OAuth2/OIDC login support. Password authentication documentation, OAuth2 login documentation
Never accept a client-supplied VerifiedIdentity as proof of authentication. In these examples, it represents trusted backend output after verification.
Step 5: Test the rule and its integration
Test the policy directly:
An enabled account is allowed.
A disabled account is rejected.
Then test the actual login routes:
Password login rejects a disabled account.
Company SSO rejects a disabled account.
An identity with no linked application account is rejected.
An eligible, linked account can proceed.
Policy tests prove the rule works. Route tests prove the application actually uses it.
🎤 How to Explain This in an Interview
A clear interview answer
“DRY means giving shared business knowledge one authoritative owner. In a login system, password login and company SSO verify identity differently, but both must reject disabled application accounts. If each handler implements that rule separately, they can drift when requirements change. I would put the shared eligibility decision in a focused domain operation or policy and route both verified login paths through the same admission workflow. I would keep method-specific verification separate and test both routes to ensure neither bypasses the policy.”
This answer explains:
What the principle means.
Where the duplication exists.
Why the duplication is risky.
How you would improve the design.
What you would deliberately keep separate.
How you would verify the result.
What makes this better than “I moved duplicate code into a method”?
Moving code is an implementation step.
An interviewer wants to understand the design decision:
“I identified one business rule with multiple copies and gave it one clear owner.”
That shows you understand why the refactoring matters.
🧠 Interview Practice Questions
- What is DRY?
DRY means avoiding multiple independent representations of the same knowledge.
In code, this often means giving a shared business rule one implementation that relevant callers reuse.
- Does identical code always violate DRY?
No.
Two pieces of code can look identical while representing different requirements.
The important question is whether they should change together for the same business reason. The Pragmatic Programmer
- Why should password and SSO share LoginPolicy?
Because application account eligibility applies regardless of how identity was verified.
A valid company identity does not override a disabled application account.
- Why not combine password and SSO verification too?
Because their verification rules are different.
DRY should remove duplicated knowledge without hiding meaningful differences.
- How does DRY relate to Single Responsibility?
They complement each other:
DRY: Avoid multiple owners of the same knowledge.
Single Responsibility: Give each component a coherent responsibility.
Here, the policy enforces admission rules, while the service coordinates the workflow.
- Does the shared policy need to be a Singleton?
No.
One authoritative implementation does not mean exactly one Java object must exist.
Several instances of the same stateless LoginPolicy can enforce the same rule. DRY is about ownership of knowledge, not object count.
- Does DRY make this login system fully secure?
No.
It reduces the risk of inconsistent application rules. Authentication, session handling, account-state freshness, and other security concerns still need proper implementation.
For example, sharing a policy does not automatically solve an account being disabled immediately after its state was read.
⚠️ Common Mistakes
Extracting every repeated line: Similar syntax does not always mean shared knowledge.
Creating a large utility class: Unrelated rules should not be forced into one owner.
Sharing method-specific restrictions: A password-only rule may not belong in the global login policy.
Creating a policy but not using it everywhere: Test the entry points, not just the policy.
Removing necessary boundary checks: Browser validation does not replace server-side enforcement.
Overengineering a simple rule: A focused method can be enough; interfaces and patterns are not mandatory.
🎯 Final Mental Model
Before DRY:
“Every login handler remembers the account rule.”
After DRY:
“Every login path asks the same owner to enforce the account rule.”
The goal is not merely fewer lines. The goal is fewer places where the same business decision can disagree.
7. 🧘 KISS — Keep It Simple

Choose the clearest solution that meets the requirements.
KISS is commonly expanded as “Keep It Simple, Stupid.” Here, we will use the friendlier “Keep It Simple.”
The idea is:
Choose the clearest solution that correctly meets the requirements.
Simple does not mean the fewest lines. It means that another developer can understand what the code does without solving a puzzle.
A short expression is not always a simple explanation.
⚠️ The Compact Version
// Compact, but harder to debug as the rule grows.
Account account = accounts.find(verifier.verify(request).key())
.filter(Account::canSignIn)
.orElseThrow(LoginRejected::new);This is valid Java.
It performs several operations:
Verify the identity.
Extract the identity key.
Find the linked application account.
Check whether the account can sign in.
Reject the attempt if the account is missing or ineligible.
The expression is short. However, several decisions are packed into one place.
Imagine investigating a failed login. Did identity verification fail? Was no account linked? Was the account disabled?
The chain does not make those stages as visible.
✅ The Readable Version
VerifiedIdentity identity = verifier.verify(request);
Account account = accounts.find(identity.key())
.orElseThrow(LoginRejected::new);
policy.check(account);Now the workflow reads like a short explanation:
Verify the person. Find their application account. Apply the admission policy.
Each stage has a name and a clear boundary.
A developer can inspect identity, place a breakpoint after account lookup, or examine the policy separately.
The external response can remain a generic rejection. Making internal steps clear does not require exposing sensitive failure details to the user.
Are Fluent APIs Bad?
No.
The compact version can be appropriate when the operation is small and familiar.
KISS does not ban Optional, streams, builders, or fluent APIs. It asks whether the chosen form makes this particular behavior easier to understand.
🧠 Simple Does Not Mean Incomplete
These are not useful forms of simplicity:
Accepting a login without verifying its proof.
Ignoring an identity-provider failure.
Skipping the disabled-account rule.
Reporting success before required storage succeeds.
Removing required validation or tests.
That is not simplifying the solution. It is leaving part of the requirement unsolved.
🎤 KISS Interview Practice
Beginner — Does simple mean fewer lines?
No. A longer method with clear, named stages can be easier to understand than one dense expression.
Intermediate — Why separate the login stages?
Verification, account lookup, and admission are different decisions. Keeping them visible makes debugging and later changes easier.
Advanced — Can a design pattern support KISS?
Yes, when it simplifies a real problem. A pattern that introduces unnecessary indirection does the opposite.
An interview-ready answer:
“I apply KISS by making the login workflow easy to follow. Identity verification, account lookup, policy enforcement, and persistence remain visible steps. I do not remove required checks to shorten the code, and I introduce patterns only when they solve an actual problem.”
8. 🛑 YAGNI — You Aren’t Gonna Need It

YAGNI means:
Do not build a capability now just because you imagine needing it later.
Our current product requires:
Password login.
Company SSO.
It does not currently require a biometric system, a provider plug-in marketplace, or support for every identity protocol.
Building those capabilities would add code, configuration, tests, and maintenance before they deliver any current value. That is the kind of speculative work YAGNI warns against. Martin Fowler’s explanation of YAGNI
✅ Model the Actual Requirements
enum Method {
PASSWORD,
COMPANY_SSO
}These are the methods that the application currently supports.
We do not add unused methods simply to make the design look extensible.
But Should We Still Use an Interface?
An interface can be useful for a present requirement:
interface IdentityVerifier {
VerifiedIdentity verify(LoginRequest request);
}Here, it separates the application workflow from authentication mechanics.
It also lets us test the workflow without contacting a real identity provider.
Those are current benefits—not imaginary future requirements.
The same reasoning applies to account lookup and persistence boundaries.
What About Passkeys Later?
When passkeys become a real requirement, we can add the appropriate verification implementation and connect it to the workflow.
We should explain where that feature would fit without implementing it prematurely.
YAGNI does not mean “make future changes impossible.” It means “avoid paying for unneeded capabilities today.”
KISS vs YAGNI
They answer different questions:
KISS: How clearly can we build the required behavior?
YAGNI: Do we need to build this behavior now?
A feature can be implemented simply and still be unnecessary.
🎤 YAGNI Interview Practice
Beginner — Should we implement passkeys to demonstrate extensibility?
Not unless they are in scope. Explain the extension point instead.
Intermediate — Does an interface violate YAGNI?
Not necessarily. It may isolate an existing external dependency, support testing, or represent current variation.
Advanced — Does YAGNI mean skipping tests or security controls?
No. Required correctness and security are part of the current solution, not speculative features.
An interview-ready answer:
“I implement the login methods required today. I keep useful boundaries around verification and persistence because they help the current design and testing. I would not build a plug-in platform or additional login protocols without a concrete requirement.”
9. 🤝 Law of Demeter — Limit Knowledge of Other Objects

Talk to the objects you need, without digging through their internal object graph.
The Law of Demeter encourages objects to know only what they need about their collaborators. Its familiar shorthand is “only talk to your friends.” Northeastern University’s explanation
In practical terms:
Ask another object for a meaningful answer instead of digging through its internal structure.
⚠️ The Getter-Chain Problem
Imagine an older account model where the service reads:
boolean enabled = account.getProfile()
.getSettings()
.getAccessFlags()
.isEnabled();To answer one question, the service must know several implementation details:
An account contains a profile.
A profile contains settings.
Settings contain access flags.
Access flags contain the enabled status.
Now imagine that account access settings move out of the profile.
The login service must change, even though its actual question has not changed:
“Can this account sign in?”
✅ Ask the Account That Question
record Account(
String id,
boolean enabled,
String alertEmail) {
boolean canSignIn() {
return enabled;
}
}The policy uses the meaningful operation:
final class LoginPolicy {
void check(Account account) {
if (!account.canSignIn()) {
throw new LoginRejected();
}
}
}The policy does not need to understand profiles, settings, or access flags.
The account owns the state-based answer. If its internal representation changes, callers can continue asking the same question.
Do Not Turn It into a Dot-Counting Rule
This expression has several dots:
accounts.find(identity.key())
.orElseThrow(LoginRejected::new);That alone does not make it a design problem.
The concern is whether the caller depends on an unnecessary internal object graph—not how many dots appear.
Similarly, do not create hundreds of forwarding getters just to shorten chains. Prefer meaningful operations or small, cohesive values.
🎤 Law of Demeter Interview Practice
Beginner — What is wrong with the getter chain?
It makes the caller understand an internal structure that is unrelated to its responsibility.
Intermediate — How does canSignIn() help?
It expresses the question the caller actually needs answered while hiding the account’s representation.
Advanced — Should we wrap every nested getter?
No. That creates another kind of complexity. Expose meaningful behavior rather than mechanically forwarding every field.
An interview-ready answer:
“The login policy needs to know whether the account can sign in. It should not navigate profiles and settings to reconstruct that answer. I expose a meaningful account operation so the caller depends on the decision rather than the internal structure.”
10. 🔗 Coupling and Cohesion — Clear Jobs, Controlled Dependencies

Coupling is how much one component depends on another.
Cohesion is how well the work inside one component belongs together.
Think outside and inside:
Outside the class: What details does it depend on?
Inside the class: Do its methods support the same purpose?
- High Cohesion: Give Related Work One Owner
⚠️ The Bad Way (Low Cohesion)
Imagine a utility class named LoginUtils that builds SQL database queries, checks passwords, formats email text, and closes network sockets. Because it handles completely unrelated tasks, it has low cohesion. Simply renaming it to a generic name like LoginManager does not fix its broken structural boundaries.
✅ The Good Way (High Cohesion)
Instead, break the unrelated work apart and give each specific task its own dedicated owner class:
final class AlertTemplate {
LoginAlert render(LoginRecord record, Account account) {
return new LoginAlert(
record.id(),
account.alertEmail(), // Use the trusted database email, not random request data
"A new sign-in was accepted for your account."
);
}
}Why this works: The AlertTemplate class focuses purely on one thing: the wording of the alert. It does not download user profiles, check passwords, or physically broadcast the email across the network.
- Controlled Coupling: Focus Your Dependencies
You can never achieve “zero dependencies” because a business workflow like LoginService naturally needs to coordinate multiple operations (such as credential checking, account lookups, and audit logging). The goal is controlled coupling, not zero coupling.
How to maintain healthy boundaries:
Keep your dependencies tightly focused and highly visible.
Prevent technical details (like raw database schemas or messy HTTP vendor payloads) from bleeding into your core business workflow logic.
Warning Signs of Bad Boundaries: Look out for code dependency cycles (Class A needing Class B, which needs Class A), shared global variables, massive multi-purpose interfaces, or cases where a small feature update repeatedly breaks unrelated parts of the codebase.
🎤 Coupling and Cohesion Interview Practice
Beginner — What is the difference?
Coupling concerns dependencies between components. Cohesion concerns related responsibilities inside a component.
Intermediate — Can an interface still create tight coupling?
Yes. A broad contract exposing vendor payloads can still force callers to know too much.
Advanced — What would you inspect in a dependency cycle?
Which responsibility creates the reverse dependency, and whether data or a contract belongs at a clearer boundary.
11. 🧭 Separation of Concerns — Keep Different Decisions Apart

A concern is a kind of work: parsing HTTP, verifying identity, applying policy, storing data, or presenting an error.
Separation of concerns organizes those decisions across methods, classes, and packages.
SRP helps choose a module’s responsibility. Separation of concerns also helps organize the larger program.
Follow the Boundaries
The HTTP layer reads a request and maps outcomes to responses.
The verification adapter understands password or SSO mechanics.
The application workflow applies account policy and records the accepted operation.
The database writer understands transactions.
The framework manages the authenticated browser session.
The worker and notification adapter handle alert delivery.
These can all live inside one application. Clear concerns do not require separate microservices.
⚠️ Keep Rules Out of the Wrong Place
Do not hide the “disabled accounts cannot sign in” rule in email code.
Do not let a SQL adapter decide whether unverified proof should count as login success.
Do not make a domain account open an HTTP connection to an identity provider.
Some enforcement is deliberately repeated at different security boundaries. Keep the rules consistent and their purpose explicit.
🎤 Separation-of-Concerns Interview Practice
Beginner — Do we need separate services for every concern?
No. Focused objects and packages inside one application are often enough.
Intermediate — Where does the account-admission rule belong?
In the application policy, enforced before access is accepted—not buried in transport or notification code.
Advanced — When is another layer unnecessary?
When it adds only forwarding without isolating a meaningful decision or dependency.
12. 🧩 Compose Objects Instead of Building Everything in One Class

A service can have focused helpers instead of inheriting all their behavior.
When you rely blindly on inheritance to share code, you create a new subclass for every single feature combination.
If your app handles different login methods (Password vs. SSO), different databases (SQL vs. In-Memory), and different alerts (Email vs. SMS), inheritance forces you to build messy, giant classes like:
PasswordSqlEmailLoginService
SsoSqlEmailLoginService
PasswordInMemoryNoEmailLoginService
SsoSqlSmsLoginService
Every single time a business manager asks for a new choice, the number of required subclasses multiplies, and the codebase becomes an unmaintainable nightmare.
The Solution: Composition (Assembling Lego Bricks) 🧱
Instead of creating massive, specialized subclasses, you create one single LoginService and hand it small, focused helper objects (collaborators) through its constructor.
LoginService service = new LoginService(
verifier, // Can be Password or SSO
accountLookup, // Can be SQL or In-Memory
new LoginPolicy(),
loginWriter, // Saves the login record and pending alert together
Clock.systemUTC()
);How this changes your system:
Production: You plug real production adapters into the constructor slots.
Testing: You plug lightweight, controlled test doubles into those same slots to get predictable, fast results.
The Composition Root: The specific place in your code where these Lego bricks are physically snapped together at startup or inside configuration settings.
🌳 When is Inheritance Still Allowed?
You should only use inheritance when a child class represents a true, permanent, and stable version of its parent contract, ensuring it strictly follows the Liskov Substitution Principle (LSP).
Do not build deep subclass hierarchies just to save yourself from typing a few matching lines of code. Composition requires explicit wiring and managing more small files, so keep your design balanced and proportionate to your actual business needs.
🔍 This Is Not Automatically UML Composition
Holding a collaborator is object composition as a coding technique.
It does not automatically imply strong lifecycle ownership, represented by a filled diamond in UML. An injected shared repository can outlive the service using it.
🎤 Object-Composition Interview Practice
Beginner — What does composition mean here?
The service uses other objects to provide focused behavior.
Intermediate — Why does it reduce subclass combinations?
Independent choices can vary independently.
Advanced — Does an injected collaborator imply strong UML ownership?
No. Lifetime and ownership need a separate modeling decision.
13. 🪜 A Framework You Can Use in an LLD Interview

You do not need to begin by drawing twelve principles.
Begin with the problem. Let the principles guide your decisions.
1️⃣ Confirm the Scope
“For this version, are we supporting password and company SSO? Is recording each accepted login mandatory? Must the user wait for the alert?”
Scope tells us what must exist now. It also prevents speculative features.
2️⃣ Name the Important Things
We have a login request, verified identity, application account, login record, and pending alert.
Define their meaning before discussing classes.
3️⃣ Give Each Job an Owner
Verification, account policy, persistence, session management, and alert delivery change for different reasons.
Assign them clear homes. Keep coordination readable.
4️⃣ Find the Actual Variation
Password and company SSO have different verification details. Database and gateway adapters have technical details.
Introduce contracts at those meaningful boundaries. Keep a concrete policy if no policy hierarchy is needed.
5️⃣ Write the Promises and Failure Behavior
What does successful verification guarantee? What does a successful writer call mean? Can email delivery be repeated? What happens on a provider outage?
These questions protect LSP and make tests useful.
6️⃣ Walk Through a Change and a Crash
Add a provider. Change the alert template. Stop the process after database commit. Reject a disabled account.
If you cannot explain where the change belongs or how the failure is handled, the diagram is not enough.
14. ⚖️ Principles Work Together—They Are Not Separate Checklists
DRY and SRP: Share the same admission rule, but do not merge password verification and notification delivery because both happen during login.
OCP and YAGNI: Keep a useful verification boundary. Do not implement ten providers nobody requested.
KISS and SOLID: A few clear objects help. A maze of pass-through interfaces does not.
ISP and cohesion: Group operations that serve one client need. Do not create a separate interface for every line.
Law of Demeter and separation of concerns: Ask an account a meaningful question. Do not let the workflow navigate another subsystem’s private object graph.
Composition and LSP: Wire useful collaborators together, and ensure each implementation keeps its contract.
The aim is not to maximize the number of principles visible in a class diagram.
The aim is to make the required behavior understandable, testable, and safe to change.
15. 🚧 Common Mistakes to Avoid
SRP as method counting: A cohesive responsibility can need several methods.
OCP as “never edit files”: Configuration and changed requirements still cause edits.
LSP as matching signatures: Success must preserve the promised meaning.
ISP as one-method interfaces everywhere: Split by client needs, not arbitrary size.
DI confused with DIP: Supplying a concrete dependency does not automatically isolate policy from its API.
DRY as merging similar syntax: Similar comparisons may represent unrelated rules.
KISS as the shortest code: A readable sequence can be better than a clever expression.
YAGNI as skipping security: Required safeguards are part of today’s problem.
Law of Demeter as counting dots: Hidden structural knowledge is the concern.
“Utils” classes with unrelated jobs: Prefer cohesive names and responsibilities.
More layers assumed to mean better design: Every boundary needs a reason.
Object composition confused with lifecycle ownership: Injected references do not automatically imply UML composition.
Logging treated as a durable audit: Diagnostic output is not a committed business record.
Outbox treated as exactly-once delivery: Repeated delivery attempts remain possible.
Login record confused with browser session: They have different owners and failure boundaries.
SOLID treated as production readiness: Operational and security guarantees need separate verification.
⚡ A Quick Review Before Your Interview

SRP: Give each coherent job a home.
OCP: Extend where behavior genuinely varies.
LSP: A replacement must keep its promises.
ISP: Expose the capabilities each caller needs.
DIP: Keep policy expressed through suitable contracts.
DRY: Give shared business knowledge one owner.
KISS: Prefer the clearest solution that meets the scope.
YAGNI: Do not implement speculative promises.
Law of Demeter: Avoid unnecessary knowledge of other objects’ internals.
Coupling and cohesion: Keep jobs related and dependencies controlled.
Separation of concerns: Make different kinds of decisions visible.
Object composition: Assemble collaborators instead of creating an inheritance combination for everything.
🏁 Final Thoughts
We started with one button: Sign in.
Behind it, we discovered several responsibilities: verification, account admission, persistence, session management, and alert delivery.
Design principles helped us give those responsibilities clear owners. They helped us introduce a new provider without copying the workflow, reject an unsafe implementation, test failures, and explain why an external email call does not belong inside a database transaction.
That is the useful meaning of good low-level design.
💡 Build the simplest design that keeps today’s promises—and gives tomorrow’s real changes a sensible place to go.
Download and Run the Examples
These are teaching examples, not a complete authentication system. The verifier is a test fixture. PostgreSQL and gateway integration require separate configuration and testing.
Save all Java files in one folder, then run:
javac --release 17 LoginDemo.java LoginDemoTest.java JdbcLoginWriter.java HttpLoginAlertDelivery.java
java LoginDemo
java LoginDemoTestContinue Learning
Continue learning
Did this explanation help?
Your quick rating stays in this browser. Use the email option if you want the feedback to reach Rahul.