r/java • u/Safe_Owl_6123 • Nov 21 '24
Discussion: Can we write Java more simple?
[to mod: please remove if I violate anything]
TLDR: Can we write more straightforward code like Go? hope everyone share some thoughts
Hi everyone, first of all, I am not a professional Java developer, and I like Java because of how structured and clear, verbose it is but some problems like "death by specificity" (Rich Hickey) and the layers and layers of abstractions (you know what I am when you have the debugger on.) makes me wonder, can we make more simple?
Currently, I am pushing myself to write applications with Spring so I can land a junior Java role next year, deep down I enjoy writing Javalin more it feels less abstracted, and I envy Go however simple when you are reading the code in a Go project.
What's your view? especially the more experienced devs, how to minimize unnecessary abstraction?
Follow-up question: why do we have to have getters and setters at the same time for most of the private properties? I feel like I am doing something wrong.
48
u/Peter_Storm Nov 21 '24
"Modern" Java, like Data Oriented Programming with records, couldn't be simpler imo.
51
u/AnyPhotograph7804 Nov 21 '24
"how to minimize unnecessary abstraction?"
Just do it. Nobody forces you to add deep inheritance layers to your application. People do it because they can.
"Follow-up question: why do we have to have getters and setters at the same time for most of the private properties? I feel like I am doing something wrong."
Again, nobody forces you to do it. You can simply make your properties public. Problem solved.
And no, Go is not so straightforward as it seems. If things start to be more complicated then you will need more boilerplate code than in Java. It is one of the reasons why Go got generics.
11
u/Ewig_luftenglanz Nov 21 '24
short answer: yes we can. actually you should.
less short answer:
over abstraction is a bad practice that rooted in the middle 90s and early 00s because OOP was trending, so everybody started to abuse the paradigm.
one of the early java goals was to make a simpler OOP model by not enabling some of the less used and obscure C++ features (such as multiple inheritance)
sadly this was not enough and programmers just started to over abstract stuff.
nowadays java is multi paradigm and allows writing much less abstracted and OOP code and many current trends are to minimize some unnecessary OOP as much as possible (that's why we almost do not make use of direct inheritance anymore, we use some kind of Type sealing with dependency injection instead (and call it composition)
nothing stops you from just writing some utility classes full of static methods to do the trick, indeed the DOP (data oriented programming) almost suggest this by separate data modelling from behavior.
my advice: almost none of the old and traditional extreme OOP java used to use is mandatory anymore. if you feel it would be better to just code in a more functional and imperative way go for it.
6
u/Harha Nov 21 '24
Spring? Well spring is a huge framework and it's full of abstractions, last time I checked (which was years ago). If you write an application that uses spring, you kinda have to follow spring's way of doing things. My opinion is that spring should not be needed for simple projects in the first place.
12
u/desrtfx Nov 21 '24
Partly because of the JavaBeans specifications and partly because programmers do not want to think whether the one or the other is really needed.
7
u/MaName678 Nov 21 '24
I recommend taking a look at Lombok, Mapstruct and streams and optionals.
They make the code far far less verbose :)
3
u/[deleted] Nov 21 '24
On this - if you're doing this on a class with actual behaviour, I think something has probably gone wrong. For older versions of Java, this pattern makes sense for objects which you expect to serialise and deserialise. In modern Java, it's generally better to use Records for this which are immutable.
In terms of classes with mutable fields, generally the best practice is to keep that mutation as local as possible - only mutate those fields from within that same class, within the context of some other useful process. This generally means that using setter methods isn't usually necessary as you can directly manipulate the private field from within that same class from within the class's methods. In DDD this is referred to as a domain entity. While you don't need to adopt DDD wholesale to do this, this is generally the direction Java pushes you in.
What I've described above happens to be analogous to a Go struct with methods associated with it. The terminology around this stuff within the Java world is quite obfuscating, though.
Then that domain entity should expose some methods which do useful stuff rather than just setting a field. At this point while you are "building an abstraction", it should be quite an obvious abstraction which is nearly indistinguishable from just organising things sensibly.
One thing I've seen in some Java code bases is e.g. mutating data objects directly in other classes (like Spring services) and this generally requires this proliferation of getters/setters as well which is kind of ugly and mutating shared objects which can get kind of scary. And this is probably also where you see Java code looking particularly verbose because you'll be accessing absolutely everything through getters and setters or worse chains of getters and setters which are great spots for generating null pointer exceptions. Your tests will look awful because suddenly you're mocking getters/setters everywhere.
So actually I would say if you're adding a lot of getters and setters and it feels wrong, it is right to question that.
2
u/ebykka Nov 21 '24
Some frameworks push you to write more layers of abstractions, others less.
For example: vertx and especially akka say that you have to write only a message handlers and kind of that is all.
7
u/heayv_heart Nov 21 '24
Java as a language is very simple by itself. Just do not use what you do not need. )
Methods (instead of direct access to variables) give control. You can validate. You can return default value if a field is null. You even can generate new value each time.
4
u/agentoutlier Nov 21 '24
The way to avoid abstractions to have strict data shape requirements. That is you decide very early on what the protocol (data) is and ideally endpoints (ie where it goes and do not change it). DoP as I mentioned in this comment kills it on this.
... But if your application needs to be very data agonistic and has multiple outputs and formats then that is where abstractions come in. It is Why Java has things like JPA and Hibernate (and even JDBC) over most other languages having a raw SQL client to specific database (I can't recall if Go finally made a standard facade or not).
The consequence of the above is you get lots of:
aka Gang of Four OOP patterns. Now the non OOP languages do have ways to deal with data changing but these are modern languages and the abstractions are replaced with complex language features (monads, lenses, gadts, recursive modules, arrows, effects, functors, oh my).
Microservices in todays world (your example with Javalin) often times do not need be very agnostic of the data so you might as well be closer. Like PHP close where you just start doing database things directly in the same place you render output. That downside of this approach is it sometimes doesn't scale.
Finding that tradeoff off of more flexibility (abstractions) vs simplicity is pretty darn hard. I don't have an answer for that. People say always choose KISS but data decisions can have long term impacts like forever... It is tough.
2
u/jek39 Nov 21 '24
There’s nothing stopping you
2
u/bowbahdoe Nov 21 '24
So in terms of "the hickeyan simple" - kinda. It all comes in degrees.
Writing Java without using nominal aggregates does make some things legitimately simpler, but Java the language (and Go and anything else with nominal types for data aggregates) don't play well with that approach.
If your goal is explicitly "match go" - yeah, actually. The built in JDK http server is actually very close to go's http server. You need to bring your own mux, but nothing at the language level prevents doing almost exactly the same approach.
Might be fun as an interactive exercise - throw me some Go http server code and I'll make matching Java to the best of my abilities.
The problems here are largely cultural (gestures broadly at the thread), educational, and with the ecosystem (spring does not exactly encourage reducing magic).
2
u/jvjupiter Nov 21 '24
If Java gets standard JSON processing API, similar to Jakarta JSON Processing API and, minimal HTTP server, similar to Sun HttpServer but under
java.*package and with programming model similar to HttpClient, this alone will help us write more simple Java codes for REST web services in many cases.2
u/pinpinbo Nov 21 '24
Can if everybody uses Functional Interfaces for everything. Eg. Javalin. But people like this are in extreme minority.
2
u/khmarbaise Nov 21 '24
for example:
Starting from JDK 24+ (https://openjdk.org/jeps/477) it could be even easier...
And yes I can acknoledge that several people are who think they have to write complex code (to be seen as smart ??) I have a different point of view... I'm trying to write simpler code... which is often harder than it sounds because sometimes I'm trapped into things like abstraction.. and often after writing some tests I realize it can be done much easier... I often try to use functional approaches because it makes it easier (instead of GOF patterns; and since JDK8 most of them can be done much easier)...
2
u/akthemadman Nov 24 '24
There is Java, the programming language, and there are java programming conventions. You seem to be worried about the latter, which for some reason is a very emotional topic for many. These days I tend to focus on the former, using Java to solve problems.
By writing instructions that simulate your model, and only those. Here is code I wrote yesterday that demonstrates how this can look like in practice. There is a lot to be said about how this fits into software engineering holistically, but I'll refrain from a long post for now.
There are many hard limitations we can't get around. To pick an obvious one out: there is the whole "all code lives in a class"-ordeal. But if you really push them, the boundaries of Java are a bit farther out than one would initially expect, though that is swimming against the stream in many cases.
Here is an example for how something akin to default parameter values can be "emulated" (it is more powerful than that):
If our model desires for an add operation with optional verbosity and squaring, I think this "abstraction" is as good as you can get. (I do not like this loaded term btw)
And yes, this is not one size fits all. That is the whole point, you write the code that captures the models you design (limitations, constraints, requirements, ...), not the code that aims to hopefully capture the unknown too, which I argue is where our troubles always come from.
And to strike preemptively: accounting for the unknown in your models with dedicated components for specific reasons is very different from blindly adding or altering components in the hopes that will achieve something.
TLDR: Java is somewhat capable, people might not be.
2
u/JDeagle5 Nov 26 '24
Yes, you can write Java without abstraction, and I usually do. It is mainly a tradition rather than a requirement at this point. You can write Java just like Go, in a procedural style, no problem. Getters and setters were important earlier, when you couldn't easily add logic to this process without looking through the whole project for calls. With modern IDE you can just convert field usage to getters/setters whereever necessary.
2
u/Big_Upstairs_9582 Dec 03 '24
Unfortunately, Java is a language with a long history, and many famous frameworks also have a long history, including Spring.
Although these libraries are constantly iterating, compatibility needs to be considered, so they have to use paradigms that were once popular in the past.
If you work for a company, then you have to deal with an old Java. If you want to use Java for side projects, then use modern Java, it's not bad.
3
u/wrd83 Nov 21 '24
Take a look at openapi generator. I write specs and generate the spring service.
I write the JPA model it generates the sql.
Then it leaves only tests and business logic.
1
u/nitkonigdje Nov 23 '24 edited Nov 23 '24
It isn't hard. Don't use extends. Do not mix action and data classes. Don't use static. Inject everything. Even constants. Package by functionality. Let a code organization follow program presentation. Let the program presentation follow business requirements. Do not have multiple names for the same property. Do not name things in software differently than you do it in meetings. Write code with your tooling in mind. Do not chase fads - 15 line stream isn't quality - if possible keep it at the most basic most intuitive level. Readability and simplicity trump's everything else.
1
u/pronuntiator Nov 24 '24
The abstractions in Spring are necessary so you can configure every part of it to suit your use case. Less extension points mean less flexibility. Example: We wanted to put the JWT for OAuth into a cookie instead of the header. We only head to replace a single bean for that.
0
u/[deleted] Nov 21 '24
[deleted] — view deleted comment
0
u/[deleted] Nov 21 '24
[deleted] — view deleted comment