Code of Shadows:Mastering Decorator Pattern in Java – Po & Shifu’s Thriller Story of Clean Code

 


The Logging Conspiracy 

It was a cold, misty morning at the Jade Palace. The silence was broken not by combat… but by a mysterious glitch in the logs.

Po (rushing in): "Shifu! The logs… they're missing timestamps!"

Shifu (narrowing his eyes): "This is no accident, Po. This is a breach in the sacred code path. The timekeeper has been silenced."

Traditional OOP Decorator

Shifu unfurled an old Java scroll:

//Interface
package com.javaonfly.designpatterns.decorator.oops;
public interface Loggable {

public void logMessage(String message);
}
//Implementation
package com.javaonfly.designpatterns.decorator.oops.impl;
import com.javaonfly.designpatterns.decorator.oops.Loggable;
public class SimpleLogger implements Loggable {
@Override
public void logMessage(String message) {
System.out.println(message);
}
}
//Implementation
class TimestampLogger implements Loggable {
private Loggable wrapped;

public TimestampLogger(Loggable wrapped) {
this.wrapped = wrapped;
}

public void logMessage(String message) {
String timestamped = "[" + System.currentTimeMillis() + "] " + message;
wrapped.logMessage(timestamped);
}
}

//Calling the decorator
public class Logger {
public static void main(String[] args){
Loggable simpleLogger = new SimpleLogger();
simpleLogger.logMessage("This is a simple log message.");

Loggable timestampedLogger = new TimestampLogger(simpleLogger);
timestampedLogger.logMessage("This is a timestamped log message.");
}
}
//Output
This is a simple log message.
[1748594769477] This is a timestamped log message.

Po: "Wait, we’re creating all these classes just to add a timestamp?"

Shifu: "That is the illusion of control. Each wrapper adds bulk. True elegance lies in Functional Programming."

Functional Decorator Pattern with Lambdas

Shifu waved his staff and rewrote the scroll:

package com.javaonfly.designpatterns.decorator.fp;

import java.time.LocalDateTime;
import java.util.function.Function;

public class Logger {
  //higer order function
    public void decoratedLogMessage(Function<String, String> simpleLogger, Function<String, String> timestampLogger) {
        String message = simpleLogger.andThen(timestampLogger).apply("This is a log message.");
        System.out.println(message);
    }

    public static void main(String[] args){
        Logger logger = new Logger();

        Function<String, String> simpleLogger = message -> {
            System.out.println(message);
            return message;
        };

        Function<String, String> timestampLogger = message -> {
            String timestampedMessage =  "[" + System.currentTimeMillis() + "] " + ": " + message;
            return timestampedMessage;
        };

        logger.decoratedLogMessage(simpleLogger, timestampLogger);
    }
}
//Output
This is a log message.
[1748595357335] This is a log message.

Po (blinking): "So... no more wrappers, just function transformers?"

Shifu (nodding wisely): "Yes, Po. In Functional Programming, functions are first-class citizens. The Function<T, R> interface lets us compose behavior. Each transformation can be chained using andThen, like stacking skills in Kung Fu."

Breaking Down the Code – Functional Wisdom Explained

Po (scratching his head): "Shifu, what exactly is this Function<T, R> thing? Is it some kind of scroll?"

Shifu (gently): "Ah, Po. It is not a scroll. It is a powerful interface from the java.util.function package—a tool forged in the fires of Java 8."

"Function<T, R> represents a function that accepts an input of type T and produces a result of type R."

In our case:

Java
 
Function<String, String> simpleLogger

This means: “Take a String message, and return a modified String message.”

Each logger lambda—like simpleLogger and timestampLogger—does exactly that.

The Art of Composition — andThen

Po (eyes wide): "But how do they all work together? Like… kung fu moves in a combo?"

Shifu (smiling): "Yes. That combo is called composition. And the technique is called andThen."

Java
 
simpleLogger.andThen(timestampLogger)

This means:

  1. First, execute simpleLogger, which prints the message and passes it on.

  2. Then, take the result and pass it to timestampLogger, which adds the timestamp.

This is function chaining—the essence of functional design.

String message = simpleLogger
.andThen(timestampLogger)
.apply("This is a log message.");

Like chaining martial arts techniques, each function passes its result to the next—clean, fluid, precise.

Po: "So the message flows through each function like a river through stones?"

Shifu: "Exactly. That is the way of the Stream."

Functional Flow vs OOP Structure

Shifu (serenely): "Po, unlike the OOP approach where you must wrap one class inside another—creating bulky layers—the functional approach lets you decorate behavior on the fly, without classes or inheritance."

  • No need to create SimpleLoggerTimestampLogger, or interfaces.

  • Just use Function<String, String> lambdas and compose them.

The Secret to Clean Code

“A true master does not add weight to power. He adds precision to purpose.” – Master Shifu

This approach:

  • Eliminates boilerplate.
  • Encourages reusability.
  • Enables testability (each function can be unit-tested in isolation).
  • Supports dynamic behavior chaining.

Po's New Move: Making the Logger Generic

After mastering the basics, Po's eyes sparkled with curiosity.

Po: "Shifu, what if I want this technique to work with any type—not just strings?"

Shifu (with a deep breath): "Yes of course you can ! Try to write it, Dragon warrior."

Po meditated for a moment, and then rewrote the logger:

 public <T> void decoratedLogMessage(Function<T, T>... loggers) {
        Function<T, T> pipeline= Arrays.stream(loggers).sequential().reduce(Function.identity(), Function::andThen);
        T message = pipeline.apply((T) "This is a log message.");
        System.out.println(message);
    }
Po (bowing):
"Master Shifu, after learning to compose logging functions using 
Function<String, String>, I asked myself — what if I could decorate not just strings, but any type of data? Numbers, objects, anything! So I used generics and built this move..."

public <T> void decoratedLogMessage(Function<T, T>... loggers) 
"This declares a generic method where T can be any type — StringInteger, or even a custom User object.
The method takes a 
varargs of Function<T, T> — that means a flexible number of functions that take and return the same type."

Function<T, T> pipeline=
  Arrays.stream(loggers).sequential().reduce(Function.identity(), Function::andThen);
  • "I stream all the logger functions and reduce them into a single pipeline function using Function::andThen.

    • Function.identity() is the neutral starting point — like standing still before striking.

    • Function::andThen chains each logger — like chaining combos in kung fu!"

  • T message = pipeline.apply((T) "This is a log message.");
    

    I apply the final pipeline function to a sample input.
    Since this time I tested it with a String, I cast it as (T). But this method can now accept any type!"

    Shifu (smiling, eyes narrowing with pride):
    "You’ve taken the form beyond its scroll, Po. You have learned not just to use functions—but to respect their essence. This generic version... is the true Dragon Scroll of the Decorator."

    Modified Code by Po

  • package com.javaonfly.designpatterns.decorator.fp;
    
    import java.time.LocalDateTime;
    import java.util.Arrays;
    import java.util.function.Function;
    
    public class Logger {  
        public <T> void decoratedLogMessage(Function<T, T>... loggers) {
            Function<T, T> pipeline= Arrays.stream(loggers).sequential().reduce(Function.identity(), Function::andThen);
            T message = pipeline.apply((T) "This is a log message.");
            System.out.println(message);
        }
    
        public static void main(String[] args){
            Logger logger = new Logger();
            Function<String, String> simpleLogger = message -> {
                System.out.println(message);
                return message;
            };
    
            Function<String, String> timestampLogger = message -> {
                String timestampedMessage =  "[" + System.currentTimeMillis() + "] " + message;
                return timestampedMessage;
            };
            Function<String, String> JadeLogger = message -> {
                String JadeLoggedMessage =  "[jadelog] " + message;
                return JadeLoggedMessage;
            };
       
            logger.decoratedLogMessage(simpleLogger, timestampLogger,JadeLogger);
        }
    }
    //Output
    This is a log message.
    [jadelog] [1748598136677] This is a log message.

  • Wisdom Scroll: OOP vs Functional Decorator

    FeatureOOP DecoratorFunctional Decorator
    Needs ClassYesNo
    Uses InterfaceYesOptional
    ComposabilityRigidElegant
    BoilerplateHighMinimal
    FlexibilityModerateHigh (thanks to lambdas)


Final Words from Master Shifu

"Po, the world of code is full of distractions—designs that look powerful but slow us down. A true Kung Fu developer learns to adapt. To decorate without weight. To enhance without inheritance. To flow with functions, not fight the structure."


Part 1- Kung Fu Code: Master Shifu Teaches Strategy Pattern to Po – the Functional Way!

Kung Fu Code: Master Shifu Teaches Strategy Pattern to Po – the Functional Way!


 "There is no good or bad code . But how you write it… that makes all the difference.”-- Master Shifu


The sun had just touched the tips of the Valley of Peace. Birds chirped, the wind whispered tales of warriors, and Po—the Dragon Warrior—was busy trying to write some Java code. Yes, you read that right.

Master Shifu stood behind him, watching, amused and concerned.

Po (scratching his head): “Master Shifu, I’m trying to make this app where each Kung Fu move is chosen based on the enemy. But the code is… bloated. Classes everywhere. If OOP was noodles, this is a full buffet.”

Shifu (calmly sipping tea): “Ah, the classic Strategy Pattern. But there’s a better way, Po… a functional way. Let me show you the path.”

The Traditional (OOP) Strategy Pattern – Heavy Like Po’s Lunch   

Po wants to choose a fighting strategy based on his opponent.

// Strategy Interface
interface FightStrategy {
void fight();
}

// Concrete Strategies
class TigerFightStrategy implements FightStrategy {
public void fight() {
System.out.println("Attack with swift tiger strikes!");
}
}

class MonkeyFightStrategy implements FightStrategy {
public void fight() {
System.out.println("Use agile monkey flips!");
}
}

// Context
class Warrior {
private FightStrategy strategy;

public Warrior(FightStrategy strategy) {
this.strategy = strategy;
}

public void fight() {
strategy.fight();
}

public void setStrategy(FightStrategy strategy) {
this.strategy = strategy;
}
}

Usage

Warrior po = new Warrior(new TigerFightStrategy());
po.fight(); // Output: Attack with swift tiger strikes!

po.setStrategy(new MonkeyFightStrategy());
po.fight(); // Output: Use agile monkey flips!


Why This Is a Problem (and Why Po Is Annoyed)

Po: “So many files, interfaces, boilerplate! All I want is to change moves easily. This feels like trying to meditate with a noodle cart passing by!”

Indeed, OOP Strategy pattern works, but it's verboserigid, and unnecessarily class-heavy. It violates the spirit of quick Kung Fu adaptability!

Enter Functional Programming – The Way of Inner Simplicity

Shifu (nodding): “Po, what if I told you… that functions themselves can be passed around like scrolls of wisdom?”  

Po: “Whoa... like… JScrolls

Shifu: “No, Po. Java lambdas.” 

In functional programmingfunctions are first-class citizens. You don’t need classes to wrap behavior. You can pass behavior directly.

Higher-Order Functions – functions that take other functions as parameters or return them.

Po, In Java8 onwards , now we can do that easily with the help of lambda, lambda can wrap the functionality and can be pass to another method as a parameter.

Strategy Pattern – The Functional Way in Java



import java.util.function.Consumer;
class Warrior {
private Consumer<Void> strategy;

public Warrior(Consumer<Void> strategy) {
this.strategy = strategy;
}

public void fight() {
strategy.accept(null);
}

public void setStrategy(Consumer<Void> strategy) {
this.strategy = strategy;
}
}

But there’s a better, cleaner way with just lambdas and no class at all.

import java.util.function.Supplier;

public class FunctionalStrategy {

public static void main(String[] args) {
// Each strategy is just a lambda
Runnable tigerStyle = () -> System.out.println("Attack with swift tiger strikes!");
Runnable monkeyStyle = () -> System.out.println("Use agile monkey flips!");
Runnable pandaStyle = () -> System.out.println("Roll and belly-bounce!");

// Fighter is a high-order function executor
executeStrategy(tigerStyle);
executeStrategy(monkeyStyle);
executeStrategy(pandaStyle);
}

static void executeStrategy(Runnable strategy) {
strategy.run();
}
}

Shifu (with a gentle tone):

“Po, in the art of code—as in Kung Fu—not every move needs a name, nor every master a title. In our example, we summoned the ancient scroll of Runnable… a humble interface with but one method—run(). In Java8 , we called it Functional Interface.

Think of it as a silent warrior—it expects no inputs(parameters) , demands no rewards(return type), and yet, performs its duty when called.

Each fighting style—tiger, monkey, panda—was not wrapped in robes of classes, but flowed freely as lambdas.

And then, we had the executeStrategy() method…
a higher-order sensei.

It does not fight itself, Po. It simply receives the wisdom of a move—a function—and executes it when the time is right.

This… is the way of functional composition.
You do not command the move—you invite it.
You do not create many paths—you simply choose the next step.”

Benefits – As Clear As The Sacred Pool of Tears

  • No extra interfaces or classes
  •  Easily switch behaviors at runtime

  • More readable, composable, and flexible

  •  Promotes the power of behavior as data.

Real-World Example: Choosing Payment Strategy in an App

Map<String, Runnable> paymentStrategies = Map.of(
"CARD", () -> System.out.println("Processing via Credit Card"),
"UPI", () -> System.out.println("Processing via UPI"),
"CASH", () -> System.out.println("Processing via Cash")
);

String chosen = "UPI";
paymentStrategies.get(chosen).run(); // Output: Processing via UPI

Po: “This is amazing! It’s like picking dumplings from a basket, but each dumpling is a deadly move.” 

Shifu: “Exactly. The Strategy   was never about the class, Po. It was about choosing the right move at the right moment… effortlessly.” 

One move=One lambda.

The good part is this lambda only holds the move details nothing else. So any warrior can master these moves , to apply the move unnecessary he does not need to reference a bounded object which wrapped this move in a boilerplate class.

Final Words of Wisdom  

“The strength of a great developer lies not in how many patterns they know… but in how effortlessly they flow between object thinking and function weaving to craft code that adapts like water, yet strikes like steel.”-- Master Shifu, on the Tao of Design Patterns.


Coming Up in the Series

Clean code Tips1:: Urge to put comments? refrain to do it.


While you are writing code, assume you are writing a novel and your fellow coders is a reader of your novel, so anytime you think you have to put comment that means something wrong, you cant express yourselves through code. A real clean code does not need comments.


I know it is provocative to put complex business logic in plain English to easily explain the logic,  or Jira id/bug Id as a future reference in the codebase, but with time, the codebase evolves, methods are refactored but we forgot to refactor comments and your comment will be out of sync and gives a wrong interpretation about the method/code/business logic, undoubtedly a code smell,  if you need to put bug id for future reference put as a commit message but avoid comments remember clean code is self-explanatory.

Bounded Context in my view

In this article, I will share my view about Bounded Context,
What does it mean,?
Why is it required?
The connection between Bounded context and Microservices.
I will try to keep it simple, and this article targeted to that audience who will hear the term Bounded Context while developing Microservices but having a hard time to understanding the Bounded context concept.
Before deep dive into Bounded Context in terms of DDD(Domain Driven Design), Let's understand what is the meaning of that in the real world.
We know the human is the most intelligent species and created different countries for the ruling. But Question is Why they created different countries or Logical Boundaries? In what basis Boundary has been drawn between two countries,  before Human civilization, in the Earth, we only have land there is no concept of country.
One compelling answers come to my mind is that to separate the administration, culture, laws, economics, so each country abstracted its people from other countries unless it is an impossible task to create one Unified culture, language as in ancients time different tribes has there own languages and cultures.
In the same country, there are some predefined rules, language, style every citizen follows. They understand the common language, aware of laws, currency, style so as a brief I can say, Citizens are sync with each other in a country and country has one Unified culture which every citizen follows and understand.
In programming, We apply Bounded context in the same manner, to separate different models/subdomains  from each other in a Domain/Problem space, In a Domain-driven design --Strategic design part,  we introduce Bounded context so in a certain context a model has a certain meaning like the countries where for a particular country--ceratin language, currency has specific meaning, But in a different country that currency or language is not understandable, Because it has no meaning/different meaning respect to that country. Like the word Fool, In English it means Stupid but in Bengali it means Flower !!!!
So If we consider Country as a Bounded context, and language/currencies as a Model inside that context we can easily map the concept of the domain model in a certain bounded context. The model has some meaning for a Bounded context but the same model has no meaning/different meaning for another Bounded context, So by Bounded context, we create a logical boundary where the model and business terms have a certain meaning and the Bounded context separate/hide the models from the outer world. All communication should be done via API. So it is obvious that under a Bounded context -- model and business logic maintains a certain law and maintain its own persistence storage and that is not directly accessible to other Bounded Context.

BoundedContext Communication: Any design has two common parts, abstraction of the data model and communicates with other parts of the system. By Bounded context we separate the data model in a simple term abstracting the commonalities in the business but How one Bounded context communicate with others?
Here the concept of Context Map stepped in, Using Context map we can discover How one Context depends on other Bounded Context, Like are two Context has strong dependencies. or one domain sends a confirmation message to another domain(Conformist) or may use a shared kernel/Shared model, I will talk about Context map later in a separate article, But as of now, you can think context map is for communicating clearly between Bounded Contexts.
At this point, I believe you have a fair bit of idea what is a Bounded context, But still, if you have questions How it fits in Architecture? go to the next paragraph.
Let say we have to design Online Student management system where Student can register to the site choose course accordingly, Pay the Course fee and then he will be tagged to a batch and Teacher & Student is notified about the batch start date and time slot.
As an Architect, you have to identify the bounded context of the different domain related to this business logic.
If we divide the business logic based on related functionality we can found four basic functionality
1. Registration process: Which takes care of Registration of Student.
2. Payment System: Which will process the Course fee and publish online payment status.
3. Batch Scheduling: Upon confirmation of payment,  this function checks the Teacher availability, batch availability and based on that create a batch and assign the candidates or update an existing batch with the candidate.
4. Notification System: It will notify Teacher and Student about the timings and slot information.

So, There are  4 bounded contexts Registration, Payments, Scheduler, and Notification.
Now let's dig down How each Module represents Teacher and Student and Course Models.
Registration process: It only wants the Student information and it needs it demographic information like Name, age, sex, address and which course student chooses.
There is no mean of Teacher in this context
Payment System : It treats Student as Candidates In Payment System only Student/Candidates financial information is required like Account number and based on the course fees it deduct the amount from given account, So here perspective of a student is totally different, Information needed in payment Service is totally different from Registration although Payment system may need few pieces of information like name, address of the student those are very minimal information.
The term "Teacher"  is not valid here, In payment System Teacher treated as Faculty and they can be permanent or Contractor based on the Faculty type Payment System choose the payment calculation either per hour basis or per anum basis.
Batch Scheduling: In case of Batch Scheduling System, it needs bare minimum information from Teacher and Student like name, Address etc. But it needs detailed information, of Course, Batches under the Courses etc.
Notification System: For Notification System, we just need the Teacher and Student email address or Phone number and name nothing else, And it needs the name of the Student management system and Course details, here Student management site acts as Sender and Teacher and Student denotes as Reciever.



Till now we have seen,  same Domain Objects Teacher, Student, Course have different meaning and use-cases for different Context, This is the beauty of Bounded Context ,we have multiple canonical models for same domain Object based on different context, So developers, Business, user are always in the same page when they are talking about a context, the concept of ubiquitous language is woven here, using ubiquitous language DDD create a unified system where every participant understand the language based on the context.
Now, the common question is why the Bounded context term is so popular in Microservices?
To answer this questions first we have to understand that DDD is applicable for Monolith as well as in Microservice, But in case of Monolith, it is vaguer and more of a logical segregation so only good developers can see it. The main reason is in monolith we have a single giant codebase, may we break it multimodule based on DDD create ACL/Translator when one module talks to another but still it needs other modules as dependent jars to invoke its method. Another point is as this is a single code base and multiple coders working on them so some not so skillfull coder can pollute the boundary or domain Object, Architecht can't create a physical boundary based on Bounded Context, But in Microservice architechture it is inherent as Microservice said that rather than a large code base we can create Small services which have it own code base and services are talk to each other through API or messaging, so It clearly says that understand the Business Domain break the Business logic in to multiple Bounded Contexts and each Bounded Context will be a separte codebase and they comuunicate through Context Map, To design the Context map you have to design API carefully, may you can use Port and Hub architechture So your code under the Bounded context is not comminicate with Outerworld and never polluted. Microservice offers this type of strong segregation of Bounded Context. Bounded Context is more visible and understandable in the context of Microservice.
Conclusion: Bounded Context is the basic needs, when you are trying to break a large business logic it helps you to understand how different part of the system use domain objects in a different manner with different terminology. Bounded Context is just a view to properly organize the business logic based on functionality but to make the business logic works --  communication between Bounded context needed, and it uses Context Map for the same. In my next article, I will discuss Context Map.

Change Method Call On the Fly:: CallSite

In my previous article, I talked about invokeDynamic, In this article, I will show you the coding how you can leverage the power of invokedynamic.
We all know that to load a class dynamically and call a method at runtime we use Java Reflection, Framework developers are often used Reflection to load class runtime and call a method at runtime. But Reflection has a performance cost as it does the security checking each time, On the other hand, invokeDynamic solves that problem and we can use invokeDynamic to runtime call the method.
To call the method runtime we need Method handle, Mow the interesting thing is we also change the underlying method call based on some parameters, It is a very powerful thing to do, the Same call can invoke different implementation on runtime based on parameter !!!

I try to explain you by a simple example, Say there are two methods call bark and mewaoo, Now based on the animal passed I want to call the corresponding method dynamically?
I will show you the code first then explain the code,
package com.example.methodhandle;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
public class MethodHandleExample {
MutableCallSite callSite = null;
public void bark() {
System.out.println("I am a Dog :: So barking");
}
public void mewaoo() {
System.out.println("I am a Cat :: So Mewaooing");
}
public MethodHandle findMethodHandle(String command) throws NoSuchMethodException, IllegalAccessException {
MethodHandle mh = null;
if ("DOG".equalsIgnoreCase(command)) {
mh = createMethodHandle(MethodType.methodType(void.class), "bark");
} else if ("CAT".equalsIgnoreCase(command)) {
mh = createMethodHandle(MethodType.methodType(void.class), "mewaoo");
} else {
throw new RuntimeException("Give a Proper Command");
}
return mh;

}

public CallSite createCallSite(String command) throws NoSuchMethodException, IllegalAccessException {
if (callSite == null) {
callSite = new MutableCallSite(findMethodHandle(command));
} else {
callSite.setTarget(findMethodHandle(command));
}
return callSite;
}

public MethodHandle createMethodHandle(MethodType methodType, String methodName)
throws NoSuchMethodException, IllegalAccessException {
return MethodHandles.lookup().findVirtual(this.getClass(), methodName, methodType);
}
public static void main(String[] args) {
MethodHandleExample example = new MethodHandleExample();
try {
example.createCallSite("DOG").dynamicInvoker().invoke(example);
example.createCallSite("CAT").dynamicInvoker().invoke(example);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If I run this code output will be
I am a Dog :: So barking
I am a Cat :: So Mewaooing
Explanation:: To call bark and mewaoo method dynamically based on the passing parameter, We first need to create  MethodHandle for each method.
MethodHandle is such an Object which stores the metadata about the method, Such as the name of the method signature of the method etc.
So here, I create a generic method called createMethodHandle, which returns a method handle.
To create a Method handle we need two major thing name of the method and the MethodType Object, MethodType Object says about the signature of the method. name parameter denotes the name of the method.
I create a generic method called findMethodHandle, This method passes the required parameters to the createMethodHandle method based on the passed command, If the command is a dog, this method pass the method name as bark and method type as void as bark takes nothing and return nothing (Signature of bark method).
Now , to change the invocation of the method we need a Calliste --Which actually flips the call, For two methods we have two different method handle, Calliste bound with a Method handle and  actually call underlying  Method handle , MutableCallsite can change the underlying Method handle Object (Strategy), so Callsite change the MethodHandle based on the command given.
Here I create a method called createCallSIte, which create a single instance of a Callsite Object, and based on the command, Callsite change the target aka MethodHandle.

Conclusion: This is a simple example but using Callsite and Methodhandle you can create a factory of Strategy and based on the situation you can choose the optimum one, so developers perspective it just a method call but ad framework developer you can choose what to call when like lambda in java8 maintained LambdaMewtaFactory.