Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Semantics: State or Dependency, Not Both

DZone's Guide to

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 ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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?

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}