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

  • JSON-Based Serialized LOB Pattern
  • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects
  • How to Perform Object Level Recovery in SQL Server
  • Using Salesforce Search Instead of a Query Using Mule 4

Trending

  • DZone's Article Submission Guidelines
  • A Complete Guide to Modern AI Developer Tools
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Real Objects vs. Data Containers

Real Objects vs. Data Containers

This take on objects and object-oriented programming suggests converting data containers and structures into real objects, then tackles the performance issues involved.

By 
Héctor Valls user avatar
Héctor Valls
·
Jun. 13, 17 · Tutorial
Likes (29)
Comment
Save
Tweet
Share
22.2K Views

Join the DZone community and get the full member experience.

Join For Free

After more than three years of working as backend (and mobile) programmer, mostly in the Java Virtual Machine ecosystem, I have realized that no one of those procedural MVC/MVP/MVVM patterns has made me feel comfortable when implementing new features or big changes in a project. Also, ER-ending classes (Controller, Manager, Helper, etc.), which are well-accepted and used in many frameworks, don’t help with that either: they will get bigger and bigger, and you will have to segregate them without any logical criteria. And when that happens, you’re screwed. Maintainability becomes really hard.

In the last few months, I have been heavily influenced by Yegor Bugayenko and what he claims is “pure” object-oriented programming. Instead of treating objects as simple (and silly) data containers/data structures, we should give them the power and trust them. Convert them into real objects.

Can you see any difference between this Java code:

public class User {
    private String id;
    private String username;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}


And this C code:

struct User{
    char  id[50];
    char  username[50];
};


Not at all. Because there is none. However, we write objects like above and are convinced we are object-oriented developers. But we aren’t. We must think of objects as something more than simple in-memory data structures exposing its state to everybody. Objects should wrap its real-life representation. 

Let’s say we need to write a class File (in Java) with a method, content(), that returns its content in a byte array. A first implementation could be something like this:

public class File {
    private String path;
    private byte[] content;
    public File(String path, byte[] content) {
        this.path = path;
        this.content = content;
    }
    //getters and setters
}
public class FileSystem {
    public byte[] getFileContent(String path) {
        return /* read file bytes from disk */;
    }
}

And we would use it this way:

FileSystem fs = new FileSystem();
String path = "/tmp/conf.xml";
File confFile = new File(path, fs.getFileContent(path));

Done.

To be honest, I think this implementation is a mess. Don’t you?

If we change the content of file /tmp/conf.xml, the configFile object becomes inconsistent. The File class is not representing a real file, but a bunch of bytes. It has been reduced to a data container. A C struct. It can’t be considered an object at all.

This is a nice implementation for the same class:

public interface File {
    byte[] content();
 }
public final class FileSystemFile implements File {
    private final String path;
    public FileSystemFile(String path) {
        this.path = path;
    }

    @Override
    public byte[] content() {
        return /* read file bytes from disk */;
    }
}

And we use it this way:

File confFile = new FileSystemFile("/tmp/conf.xml");

Much better, right? Now, configFile is a real object. We have converted Filetype in an interface. This way, we can have more implementations like RemoteFile, if needed.

You may think that this implementation is not efficient because each time we call the content() method, a disk read is performed. It may be slow, depending on the system and the application requirements. You are right. So now,  object composition and the decorator design pattern come into action.

We are going to create a class, CachedFile, that wraps a File and caches its content, so just one disk read will be performed:

public final class CachedFile implements File {
    private final File origin;
    private byte[] cached;
    public CachedFile(File origin) {
        this.origin = origin;
        this.cached = null;
    }
    @Override
    public byte[] content() {
        if (this.cached == null) {
            this.cached = origin.content(); //real disk read
        }
        return this.cached;
    }
}

(This is a very naive cache implementation. Also, you must never use null. I did it just for the example.)

And we use it this way:

File confFile = new CachedFile(new FileSystemFile("/tmp/conf.xml"));

It looks great for me!

What if I tell you that this approach can be applied to database objects, too?

Let’s go back to the User example. A real, stored in-database User would look like this:

public interface User {
    public String id();
    public String username();
}
public DatabaseUser implements User {
    private final String id;
    private final Database db;
    public DatabaseUser(String id) {
        this.id = id;
        this.db = db;
    }
    @Override
    public String id() {
        return this.id;
    }
    @Override
    public String username() {
        return /* SELECT username FROM users WHERE id = this.id */;
    }
}

Now, a User is not just a bunch of data. Its state is not being exposed. It is a real object. Again, we can “decorate” it with a cache or whatever we want for throughput optimization.

If you liked it this approach of OOP, I strongly recommend you to read Yegor’s posts and his book Elegant Objects.

Object (computer science) Data (computing) Container Database

Published at DZone with permission of Héctor Valls. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • JSON-Based Serialized LOB Pattern
  • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects
  • How to Perform Object Level Recovery in SQL Server
  • Using Salesforce Search Instead of a Query Using Mule 4

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!