DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Using Java Class Extension Library for Data-Oriented Programming
  • JQueue: A Library to Implement the Outbox Pattern
  • Using Barcodes in iText 7
  • Predicting Stock Trend Using Deep Learning

Trending

  • Ensuring Configuration Consistency Across Global Data Centers
  • Grafana Loki Fundamentals and Architecture
  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  1. DZone
  2. Coding
  3. Java
  4. Using Java Class Extension Library for Data-Oriented Programming - Part 2

Using Java Class Extension Library for Data-Oriented Programming - Part 2

Effectively separate data from domain-specific logic in data-oriented programming, utilizing dynamic extensions with the Java Class Extension Library.

By 
Gregory Ledenev user avatar
Gregory Ledenev
·
Dec. 19, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
6.4K Views

Join the DZone community and get the full member experience.

Join For Free

This is the second article that presents an object-oriented programming (OOP) approach to effectively separate data from domain-specific logic in data-oriented programming, utilizing the dynamic class extensions using the Java Class Extension Library. You can read the first article there.

Problem

Let us reconsider the same scenario where we are building a warehouse application designed to handle the shipping of various items. We have established a hierarchy of classes to represent the goods we have:

Java
 
class Item {…}
class Book extends Item {…}
class Furniture extends Item {…}
class ElectronicItem extends Item {…}


To implement shipping logic for each item, one might be tempted to add a ship() method directly to each Item class. While this is straightforward, it can lead to bloated classes filled with unrelated operations — such as shipping, storing, retrieving from a database, and rendering.

Instead of mixing these responsibilities, it is better to keep items primarily as data classes and separate domain-specific logic from them.

In the first article, we presented a way to achieve that separation using static class extensions with the Java Class Extension library. We defined and implemented extensions as usual Java classes and then utilized the Java Class Extension library to find matching extension classes and create extension objects. This approach is simple, direct, and efficient. 

However, some developers would prefer doing that without introducing more extension classes and in a more functional style. The Java Class Extension library now provides such an ability by introducing dynamic class extensions. So, it is possible to define extensions by composing them as sets of lambda operations and let the Java Class Extension library create extensions dynamically on the fly.

Dynamic Class Extensions With Java Class Extension Library

Class DynamicClassExtension provides a way to mimic class extensions (categories) by composing extensions as a set of lambda operations. To specify an extension: 

  1. Create a Builder for an interface you want to compose an extension for by using the DynamicClassExtension.sharedBuilder(class) method.
  2. Specify the name of an operation using Builder.opName(String).
  3. List all the method implementations per particular classes with lambdas using the Builder.op(...) or Builder.voidOp(...).
  4. Repeat 2 and 3 for all operations.

For example, the following code creates Item_Shippable extensions for Item classes. There are explicit ship() method implementations for all the Item classes. Though, the log() method is implemented for the Item class only, so extensions for all the Item descendants will utilize the same log() method.

Java
 
  class Item {...}
  class Book extends Item {...}
  class Furniture extends Item {...}
  class ElectronicItem extends Item {...}
  class AutoPart extends Item {...}

  interface Item_Shippable {
      ShippingInfo ship();
      void log(boolean isVerbose);
  }
  ...
 DynamicClassExtension.sharedBuilder(Item_Shippable.class).
      nameOp("ship").
          op(Item.class, item -> ...).
          op(Book.class, book -> ...).
          op(Furniture.class, furniture -> ...).
          op(ElectronicItem.class, electronicItem -> ...).
      nameOp("log").
          voidOp(Item.class, (Item item, Boolean isVerbose) -> {...}).
      build();


Finding an extension and calling its methods is simple and straightforward:

Java
 
Book book = new Book("The Mythical Man-Month");
Item_Shippable itemShippable = DynamicClassExtension.sharedExtension(book,
	Item_Shippable.class);
itemShippable.log(true);
itemShippable.ship();


Shipping a collection of items is equally straightforward:

Java
 
Item[] items = {
    new Book("The Mythical Man-Month"), 
    new Furniture("Sofa"), 
    new ElectronicItem(“Soundbar")
};

for (Item item : items) {
    DynamicClassExtension.sharedExtension(item, Item_Shippable.class).ship();
}


Supporting a new Item class using the Java Class Extension library requires just adding the operations for that new Item class. No need to change any other code. That is it.

Conclusion

Java Class Extension library provides a valuable alternative for class extensions (not supported in Java) with just a little more verbose code and a little more complex implementation. Both static and dynamic approaches offer comparable performance, so their choice ultimately depends on personal preferences, style, habits, and specific requirements.

Details

For most cases, a shared instance of DynamicClassExtension should be used. However, if there is a need for different implementations of extensions in different places or domains it is possible to create and utilize new instances of DynamicClassExtension.

Inheritance Support

DynamicClassExtension takes care of inheritance, so it is possible to design and implement a class extension hierarchy that fully or partially resembles the original classes' hierarchy. If there are no explicit extension operations specified for a particular class - its parent extension will be utilized. For example, if there are no explicit extension operations defined for AutoPart objects — base the ship() and the log(boolean) operations specified for Item will be used instead.

Caching

The caching of extension objects is supported out of the box. Cache utilizes weak references to release extension objects that are not in use. However, to perform a full cleanup, either the cacheCleanup() should be used, or automatic cleanup can be initiated via the scheduleCacheCleanup(). If automatic cache cleanup is used — it can be stopped by calling the shutdownCacheCleanup().

Limitations

The following are the limitations of DynamicClassExtension:

  1. Overloaded operations are not supported. For example, it is not possible to define both log(boolean) and log(String) operations
  2. Operations having more than one parameter are not supported.

About Java Class Extension Library

The library is free under the terms of the MIT License and available for download at GitHub.

By leveraging this library, developers can maintain a clean separation between data classes and domain-specific logic while adhering to OOP principles. This results in a flexible and extensible codebase that enhances maintainability and reduces errors.

Library Data (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Using Java Class Extension Library for Data-Oriented Programming
  • JQueue: A Library to Implement the Outbox Pattern
  • Using Barcodes in iText 7
  • Predicting Stock Trend Using Deep Learning

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!