eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Spring Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

Partner – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

Course – Spring Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

1. Overview

The Law of Demeter (LoD), or principle of least knowledge, provides object-oriented design principles for modular software development. It helps to build components that are less dependent on each other and loosely coupled.

In this tutorial, we’ll delve into the Law of Demeter and its application in Java.

2. Understanding the Law of Demeter

The Law of Demeter is one of several design guidelines in object-oriented programming. It recommends that objects should avoid accessing the internal data and methods of other objects. Instead, an object should only interact with its immediate dependencies.

The concept was first introduced in a paper by Karl J. Lieberherr, et al. It states that:

For all classes C, and for all methods M attached to C, all objects to which M sends a message must be instances of classes associated with the following classes:

  • The argument classes of M (including C)
  • The instance variable of classes of C

(Objects created by M, or by functions or methods which M calls, and objects in global variables are considered as arguments of M.)

Simply put, the Law says that a method of class should only invoke the methods of:

  • Classitself
  • An object created by X
  •  An object passed as an argument to X
  •  An object held in an instance variable of C
  • A static field

This sums up the law in five points.

3. Examples of the Law of Demeter in Java

In the previous section, we distilled the Law of Demeter into five key rules. Let’s illustrate these points with some sample code.

3.1. The First Rule

The first rule says that a method X of class should only invoke the methods of C:

class Greetings {
    
    String generalGreeting() {
        return "Welcome" + world();
    }
    String world() {
        return "Hello World";
    }
}

Here, the generalGreeting() method invokes the world() methods in the same class. This adheres to the law as they belong to the same class.

3.2. The Second Rule

Method X of class C should only invoke the methods of an object created by X:

String getHelloBrazil() {
    HelloCountries helloCountries = new HelloCountries();
    return helloCountries.helloBrazil();
}

In the code above, we create an object of HelloCountries and invoke helloBrazil() on it. This follows the law as the getHelloBrazil() method itself created the object.

3.3. The Third Rule

Furthermore, the third rule state that method X should only invoke an object passed as an argument to X:

String getHelloIndia(HelloCountries helloCountries) {
    return helloCountries.helloIndia();
}

Here, we pass an HelloCountries object as an argument to getHelloIndia(). Passing the object as an argument gave the method close proximity to the object, and it can invoke its method without violating the rule of Demeter.

3.4. The Fourth Rule

Method X of class should only invoke the method of an object held in an instance variable of C:

// ... 
HelloCountries helloCountries = new HelloCountries();
  
String getHelloJapan() {
    return helloCountries.helloJapan();
}
// ...

In the code above, we create an instance variable, “helloCountries“, in the Greetings class. Then, we invoke the helloJapan() method on the instance variable inside the getHelloJapan() method. This conforms to the fourth rule.

3.5. The Fifth Rule

Finally, method X of class C can invoke the method of a static field created in C:

// ...
static HelloCountries helloCountriesStatic = new HelloCountries();
    
String getHellStaticWorld() {
    return helloCountriesStatic.helloStaticWorld();
}
// ...

Here, the method invokes helloStaticWorld() method on a static object created in the class.

4. Violating the Law of Demeter

Let’s examine some sample code that violates the Law of Demeter and look at a possible fix.

4.1. Setup

We’ll begin by defining an Employee class:

class Employee {
  
    private Department department = new Deparment();
  
    public Department getDepartment() {
        return department;
    }
}

The Employee class contains an object reference member variable and provides accessor methods for it.

Moving on, the Department class is defined with the following member variables and methods:

class Department {
    private Manager manager = new Manager();
  
    public Manager getManager() {
        return manager; 
    }
}

Furthermore, the Manager class contains the method to approve expenses:

class Manager {
    public void approveExpense(Expenses expenses) {
        System.out.println("Total amounts approved" + expenses.total())
    }
}

Finally, let’s look at the Expenses class:

class Expenses {
    
    private double total;
    private double tax;
    
    public Expenses(double total, double tax) {
        this.total = total;
        this.tax = tax;
    }
    
    public double total() {
        return total + tax;
    }
}

4.2. Usage

The classes exhibit tight coupling through their relationships. We’ll demonstrate a Law of Demeter violation by having the Manager approve Expenses:

Expenses expenses = new Expenses(100, 10); 
Employee employee = new Employee();
employee.getDepartment().getManager().approveExpense(expenses);

In the code above, we have chained calls that violate the Law of Demeter. The classes are tightly coupled and cannot operate independently.

Let’s fix this violation by having the Manager class as an instance variable in Employee. It will be passed in via the Employee constructor. Then, we’ll create submitExpense() method in the Employee class and invoke approveExpense() on Manager inside it:

// ...
private Manager manager;
Employee(Manager manager) {
    this.manager = manager;
}
    
void submitExpense(Expenses expenses) {
    manager.approveExpense(expenses);
}
// ...

Here’s the new usage:

Manager mgr = new Manager();
Employee emp = new Employee(mgr);
emp.submitExpense(expenses);

This revised approach adheres to the Law of Demeter by reducing the coupling between classes and promoting a more modular design.

5. Exception to the Law of Demeter

Chained calls usually signal a violation of the Law of Demeter, but there are exceptions. For example, the builder pattern doesn’t violate the Law of Demeter if the builder is instantiated locally. One of the rules states that “Method X of class C should only invoke the methods of an object created by X“.

Additionally, there are chained calls in Fluent APIs. Fluent APIs don’t violate the Law of Demeter if the chained calls are on locally created objects. But when the chained calls are on a non-locally instantiated object or returns a different object, then it violates the Law of Demeter.

Also, there are cases where we could violate the Law of Demeter when dealing with data structures. The typical data structure usage, like instantiating, mutating, and accessing them locally, doesn’t violate the Law of Demeter. In a case where we’re calling a method on an object obtained from a data structure, then the Law of Demeter may be violated.

6. Conclusion

In this article, we learned the application of the Law of Demeter and how to adhere to it in object-oriented code. Additionally, we delved into each law with code examples. The Law of Demeter promotes loose coupling by limiting object interactions to immediate dependencies.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Spring Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

Course – Spring Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 30% off until 31st March, 2026

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments