Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Strategy and Template Method in Java and Spring: From an SLA if-Ladder to Policy Beans, a Lambda Map, a Sealed Switch and an Import Skeleton
  • The State Pattern in Modern Java: A Ticket Lifecycle as Sealed Records, Where an Illegal Move Does Not Compile
  • When Not to Use a Design Pattern: Five Java Smells, the Patterns the Language Replaced, and a One-Page ADR for Saying No
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

When Not to Use a Design Pattern: Five Java Smells, the Patterns the Language Replaced, and a One-Page ADR for Saying No

Five tiny Java programs, each with a pattern that earns nothing. The same call prints 'invoice region eu', then 'us', because a singleton is global state. A factory returns an equal object to plain new. Five do-nothing decorators take the stack from 3 frames to 8. Then Visitor, Strategy and Builder replaced by a sealed switch, a lambda and a record.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Object-Oriented Programming

What you will learn

  • Recognise the golden hammer: a pattern applied because it is known, not because it is needed
  • Spot five smells in small Java programs: a lone interface, a global singleton, a factory for one class, an empty decorator stack and an anemic model
  • Replace Visitor, a one-line Strategy class and a Builder with a sealed switch, a lambda and a record constructor
  • Ask five questions before adding a pattern and record the decision in a short ADR

Before you start

  • Java interfaces, records and lambdas
  • The Strategy and State patterns

Owning a router does not mean every joint should be a dovetail. A shelf needs two screws and two minutes. A drawer that is pulled hard every day earns the dovetail. Patterns work the same way. You choose one by looking at the problem in front of you, not at the toolbox. This article shows five places where a pattern costs more than it gives, each as a tiny Java program with its real output.

The golden hammer

Learn one good tool and everything starts to look like a nail. An if with two branches, a class with one job, a value that never changes, a loop over a list, one object made once, a single log line: each gets stamped "pattern". Most of them needed nothing at all.

Smell 1: an interface with one implementation

// The interface has one implementation and nobody plans a second.
interface TicketLister {
    List<String> openTickets();
}

static class TicketListerImpl implements TicketLister {
    @Override
    public List<String> openTickets() {
        return List.of("T-101", "T-102");
    }
}
[T-101, T-102]

Two types to read for one behaviour, and the output is exactly what it would be without the interface. Use the class, and add the interface when a second implementation is real. A second one that exists only for a mock is not a reason to start with it.

Smell 2: a singleton used as global state

// A singleton used as global state: any class can change it from anywhere.
static class Settings {
    static final Settings INSTANCE = new Settings();
    String region = "eu";
}

static class Invoices {
    String label() {
        return "invoice region " + Settings.INSTANCE.region;
    }
}

static class Reports {
    void switchRegion() {
        Settings.INSTANCE.region = "us";
    }
}
invoice region eu
invoice region us

Same call, different answer, because another class changed the region from somewhere else. Pass the region into Invoices through its constructor and the surprise disappears.

Smell 3: a factory for one class

// A factory for a class with one shape and no choice to make.
static class TicketFactory {
    static Ticket create(String id, String plan) {
        return new Ticket(id, plan);
    }
}

Ticket viaFactory = TicketFactory.create("T-101", "pro");
Ticket direct = new Ticket("T-101", "pro");
System.out.println(viaFactory.equals(direct));
true

The factory added a class and a call and changed nothing. Call new, and add a factory when the choice of class really varies.

Smell 4: a deep decorator stack

// Each wrapper adds nothing but one more call.
static class Wrap implements Desk {
    private final Desk next;

    Wrap(Desk next) {
        this.next = next;
    }

    @Override
    public String close(String id) {
        return next.close(id);
    }
}

Desk deep = new Wrap(new Wrap(new Wrap(new Wrap(new Wrap(new RealDesk())))));

RealDesk.close reports the stack depth it sees:

plain: closed T-101, stack depth 3
five wrappers: closed T-101, stack depth 8
Stack depth with and without wrappers. The plain call reaches RealDesk with a stack depth of 3. With five Wrap decorators that only pass the call on, the depth is 8: five extra frames in every stack trace, and no extra behaviour. RealDesk.close RealDesk.close Wrap.closeWrap.close Wrap.closeWrap.closeWrap.close plain: depth 3 depth 8 5 frames, no behaviour
Every wrapper that does no work is one more frame to read in every stack trace.

Keep the wrappers that do real work, such as logging, caching or a retry, and remove the rest. (When a decorator does earn its place, it looks like decorators and proxies.)

Smell 5: an anemic model, by default

// Anemic: only getters and setters. Every rule has to live in some service, and it is easy to forget one.
static class AnemicTicket {
    private String status = "OPEN";
    private final List<String> comments = new ArrayList<>();
    String getStatus() { ... }
    void setStatus(String status) { ... }
    List<String> getComments() { ... }
}

// Rich: the ticket guards its own rule.
static class Ticket {
    private boolean closed;
    private final List<String> comments = new ArrayList<>();

    void close() {
        closed = true;
    }

    void comment(String text) {
        if (closed) {
            throw new IllegalStateException("a closed ticket takes no comment");
        }
        comments.add(text);
    }
}
anemic: CLOSED, comments 1
rich: a closed ticket takes no comment

The anemic ticket is closed and still accepts a comment. A rule that lives only in a service is skipped by the next caller that does not go through it. Let the object guard its own rule, as the sealed ticket states do in the State pattern article.

Patterns the language replaced

// Visitor, replaced: a sealed interface and a switch. The compiler checks every case.
sealed interface Shape permits Circle, Square {
}

record Circle(double radius) implements Shape {
}

record Square(double side) implements Shape {
}

static double area(Shape shape) {
    return switch (shape) {
        case Circle circle -> Math.PI * circle.radius() * circle.radius();
        case Square square -> square.side() * square.side();
    };
}

// Builder, replaced: a record with a second constructor for the defaults.
record Ticket(String id, String plan, boolean urgent) {
    Ticket(String id) {
        this(id, "basic", false);
    }
}

// Strategy class, replaced: a lambda.
DoubleUnaryOperator fee = amount -> amount * 0.02;
area of Square 3 = 9.0
fee on 200 = 4.0
Ticket[id=T-1, plan=basic, urgent=false]

Add a Triangle to permits and the switch stops compiling until it has a case. The idea of each pattern is still there, and the ceremony moved into the language.

Five questions before you add a pattern

  1. What problem do I have today? Not someday.
  2. What is the simplest code that solves it?
  3. What does the pattern add: types, calls, names to learn?
  4. Does Java or Spring already do it?
  5. Would the next reader see why it is there?

Write the no down

An architecture decision record is useful for the pattern you added and for the one you did not. An example:

TitleFee rules stay one method for now
StatusAccepted
ContextTwo plans, one rule each, and the rules change a few times a year
DecisionNo Strategy classes yet. Revisit when a plan needs its own dependencies.
ConsequencesOne method to edit, less to read, and moving to Strategy later is a small change

A no that is written down saves the next person the same debate. The format is covered in ADRs and C4 diagrams. A pattern has to earn its place, and the Strategy beans earned theirs only once a fourth plan arrived.

Keep going in Java · 47 of 82

Previous
The State Pattern in Modern Java: A Ticket Lifecycle as Sealed Records, Where an Illegal Move Does Not Compile
Next post
Java equals and hashCode: Why a HashSet Needs Both
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • The golden hammer
  • Smell 1: an interface with one implementation
  • Smell 2: a singleton used as global state
  • Smell 3: a factory for one class
  • Smell 4: a deep decorator stack
  • Smell 5: an anemic model, by default
  • Patterns the language replaced
  • Five questions before you add a pattern
  • Write the no down
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.