Over a million developers have joined DZone.

Semantics: State or Dependency, Not Both

Programming languages use variables to store state and to store references to dependencies. Should they be treated separately?

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

The more I program, the easier it gets. However, the more questions arise regarding programming.

This week, I was thinking about Object-Oriented Programming (OOP). I’ve been told that OOP is about encapsulating state and behavior in a single isolated unit.

In languages I know, state translates into attributes and behavior into methods.

public class Cat {
    private Color color;
    public void mew() { ... }

That said, unit testing requires the ability to test in isolation: this has been enabled by Dependency Injection (whether manual or framework-based). Dependencies are also translated into attributes, though most (if not all) never change through the instance lifecycle.

public class MechanicalCat {
    private final RepairmentManager repairmentMgr;
    public MechanicalCat(RepairmentManager repairmentMgr) {
        this.repairmentMgr = repairmentMgr;

Now, we have both state and dependencies handled as attributes. For Java, it makes sense because Dependency Injection became mainstream much later than the language. More modern JVM languages introduced the concept of val, which makes an attribute immutable. Here’s a Kotlin port of the above code:

class Cat(val color:Color) {
    fun void mew() { ... }

class MechanicalCat(var repairmentMgr:RepairmentManager)

However, these semantics are only about mutability/immutability. Java already had the same semantics with a different syntax – the final keyword.

I was wondering if we could have different semantics for state and dependencies? Any language creator reading this blog and thinking this might be a good idea to separate between them?

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

java,oop,kotlin,language features,semantics,languages

Published at DZone with permission of Nicolas Frankel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}