r/java • • Aug 03 '25

Teach Me the Craziest, Most Useful Java Features — NOT the Basic Stuff

I want to know the WILD, INSANELY PRACTICAL, "how the hell did I not know this earlier?" kind of Java stuff that only real devs who've been through production hell know.

Like I didn't know about modules recently

393 Upvotes

279 comments sorted by

View all comments

209

u/JustADirtyLurker Aug 03 '25

You can create enums of functions that implement a base prototype. I learned this from an old Jfokus presentation by Edson Yanaga. You don't use it often but when you do it is a fantastic code organization thing.

46

u/seinecle Aug 03 '25

Can somebody illustrate with an example please?

160

u/shinmai_rookie Aug 03 '25

I don't have time to type an example myself but I think this (from ChatGPT) is what the user above you is referring to: in Java, you can have functions (abstract or otherwise) in an enum, and override them inside any enum value you want, like in an anonymous class (which I suspect they are).

enum Operation {
    ADD {
        @Override
        double apply(double x, double y) {
            return x + y;
        }
    },
    SUBTRACT {
        @Override
        double apply(double x, double y) {
            return x - y;
        }
    },
    MULTIPLY {
        @Override
        double apply(double x, double y) {
            return x * y;
        }
    },
    DIVIDE {
        @Override
        double apply(double x, double y) {
            return x / y;
        }
    };

    // Abstract method that each enum constant must implement
    abstract double apply(double x, double y);
}

66

u/snuggl Aug 03 '25

I use this for simple finite state machines, it’s real nice!

28

u/Big-Dudu-77 Aug 03 '25

I’ve been working on Java a long time and never seen this. Thanks!

5

u/shinmai_rookie Aug 03 '25

Fair enough, I learned about it when studying for the official certificate, since it appears in a lot of preparation exercises hahah

→ More replies (1)

29

u/__konrad Aug 03 '25

Pitfall: After adding methods, Operation.ADD.getClass() is different than Operation.class and Operation.ADD.getDeclaringClass() should be used...

55

u/GuyWithLag Aug 03 '25

Yes, this is a Java subreddit, but I love how concise this can be done in Kotlin:

enum class operation(private val op: (Double, Double) -> Double) { 
  ADD { a, b -> a + b },
  SUBTRACT { a, b -> a - b },
  MULTIPLY { a, b -> a * b },
  DIVIDE { a, b -> a / b },
  ;

  fun apply(x: Double, y: Double) = op(x, y)
}

25

u/Ok-Scheme-913 Aug 03 '25

As mentioned by others, this is storing a lambda instead of being a method on the instance directly.

Java could also do that:

enum Operation {
  ADD((a,b) -> a+b)
;

  Operation(BiFunction<Double, Double, Double> op) {
    this.op = op;
  }

  BiFunction<Double, Double, Double> op;
}

16

u/Dagske Aug 03 '25

Or use DoubleBinaryOperator rather than BiFunction<Double,Double,Double>. It's more concise and you avoid the costly cast.

5

u/GuyWithLag Aug 03 '25

Oh I know - I'd not do the lambda indirection in performance-sensitive code.

10

u/Efficient_Present436 Aug 03 '25

you can do this in java as well by having the function be a constructor argument instead of an overridable method, though it'd still be less verbose in kotlin

→ More replies (3)

4

u/matthis-k Aug 04 '25

It's kind of like a quick strategy pattern, for more complex and longer functions I would recommend extracting into actual classes, otherwise if you have 50 100 line functions you really don't want that (for example for support off different apis, Made up usecase but I think the idea is clear)

3

u/Mozanatic Aug 03 '25

Having the enum implement an interface instead of an abstract method would be better.

→ More replies (1)

3

u/znpy Aug 03 '25

That looks cool indeed!

13

u/Polygnom Aug 03 '25

This is kinda obsolete with sealed types now. But its still a very useful pattern.

13

u/shinmai_rookie Aug 03 '25

I think "obsolete" is a bit of an exaggeration haha. When you need a small amount of stateless classes with a relatively simple behaviour (for your own definitions of small and simple), enums give you less boilerplate (no need to define private constructors, or final class Whatever extends Whatever), they're all more neatly packed together, and you get autocomplete from your IDE (if applicable), not to mention EnumSets if you need them and an easier access to all the possible values without reflection (Operation.values if memory holds, but I'm a bit rusty).

4

u/Polygnom Aug 03 '25

I said "kinda" for a reason. You get a couple things with sealed types you dont get with enzms and vice versa. Biggest advantage of sealed types is that you can restrict the subset of allowed values, which you cannot with enums (there is an old JEP forcenhanced enums that would allow this, but it sees little traction).

→ More replies (1)

14

u/JustADirtyLurker Aug 03 '25

I don't agree. They both have their use cases. If all you need is a polymorphic function, not a full blown class hierarchy, the Enum pattern above allows you to have it directly.

5

u/GuyWithLag Aug 03 '25

Actually these cases are very useful when you need to do some kind of serialization/deserialization and don't want to have a twin as a DTO.

→ More replies (3)
→ More replies (5)

21

u/FearlessAmbition9548 Aug 03 '25

I do this and my team started calling the pattern “strategy lite”

3

u/Wyvernxx_ Aug 04 '25

A pretty on point description of what it actually does.

4

u/Least_Bee4074 Aug 04 '25

Back in 2010 I worked with a guy who had done this to implement a series of different web reports, so the class ended up getting massive - I think when I left there were like 70 different reports in that enum.

IMHO, much better to go just a map and an interface. Otherwise the coupling can get very bad, and because you’re in an enum, there is now way out except to tear it all apart

5

u/oweiler Aug 03 '25

This is something I've used a lot in Advent of Code, in production code not so much. Still a neat thing to know.

2

u/Paul-D-Mooney Aug 03 '25

This is interesting. I usually create a map of some value to a function or a predicate to a function when I have to get really fancy. I’ll add this to the tool box

→ More replies (7)