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

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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?

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:
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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}