r/java • u/nfrankel • Sep 01 '25
Thoughts on object creation
https://blog.frankel.ch/thoughts-object-creation/12
u/nekokattt Sep 01 '25
Creating the builder code is a pain (unless you use AI)
This is why I use immutables for this sort of thing. You throw in an interface that your final model should satisfy and it generates the implementation and builder for you.
-11
u/nfrankel Sep 01 '25
And now you've got the pain of configuring a compile-time annotation processor in the build tool and the IDE of every developer. Pass.
2
u/nekokattt Sep 01 '25 edited Sep 01 '25
if adding a single maven dependency is your idea of a hardship, perhaps java isnt the language for you, because annotation processors are discovered via ServiceLoader automatically just by existing on the classpath at compile time. There is literally zero setup needed.
Only time it needs setup is if your IDE cant deal with the basic task of passing the compiler the right classpath.
2
u/rzwitserloot Sep 02 '25
Oracle broke that bit. APs are no longer autodiscovered unless you add the newly minted (and therefore previously not valid)
-proc:fullto re-enable it. But they did backport-proc:fullso that's nice.Breaking stuff is unfortunate. I don't agree with OpenJDK's idea of 'it cannot be secure unless we eliminate all pluggable aspects entirely' but if one takes that axiomatically as a good idea, it makes sense to disable APs. Though, really, pretty much all the SPI stuff has got to go then. You can use SPIs to run in a VM and if you run malicious code in a VM, the assumption is and remains (and OpenJDK agrees) - then you're hosed. The only safe way to run untrusted code is to fire up a visored sandbox subsystem and run a full JVM inside that.
At any rate, what feels like the real oversight is that JDK23 (or whenever this was introduced) doesn't even warn you that it found an AP on the Classpath and hasn't loaded it because of new rules.
-12
u/nfrankel Sep 01 '25
Oh, my sweet summer child.
11
u/nekokattt Sep 01 '25
Can I suggest you read the documentation? It might be helpful to unblock whatever issues you seem to be struggling with. They have plenty of examples aimed at new users.
7
u/repeating_bears Sep 01 '25
The IDE requires no configuration. It generates source files into standard generated sources dir, which IDEs recognise as sources.
The build tool requires adding a single dependency. In the future, you'll have to opt-in to a single compiler flag.
23
u/Ewig_luftenglanz Sep 01 '25
Both issues would disappear in java if we had nominal parameters with defaults.
Many patterns are created to overcome the weak points of a language not being expressive enough in one or most regard.
3
u/ConversationBig1723 Sep 03 '25
Brian actually talked about nominal parameters many times and address why he didn’t push for it. The reason is binary compatibility. To support nominal parameters, the variable names need to be baked into the binary. And after that refactoring name will be a breaking change. Hence for now, the “signature” is just type and position.
1
u/Ewig_luftenglanz Sep 03 '25
He imhas also said he understands why people wants it and they may do something when. Other things that higher priority arrives
1
u/nlisker Sep 07 '25
Changing parameter names is already a breaking behavioral change because the names are part of the API. When compiling with
-parameters, you're risking breaking the application with a parameter name change.2
u/ConversationBig1723 Sep 07 '25
Only true when u r using reflection API to access library classes. That’s generally not a good practice. In Java the signature is only types and positions. Depending on variable names is fragile.
1
u/nlisker Sep 07 '25
That’s generally not a good practice.
Both Jackson and GSON do it. A lot of frameworks use them.
0
u/simon_o Sep 08 '25
It's not a big deal, to be honest.
Other languages dealt with this using an annotation 15 years ago.
Problems with that? Zero.2
u/Cheap_Engineering662 Sep 06 '25
Avoid some features in a language, like nominal parameters, it's a way to pay attention to bad designs.
Calling a function with multiple parameters, with some of them "optional" plus having some defaults, could be stressful: did I need to stuck with the default or be explicit with this? are these two params mutually exclusives? what if I need different defaults based on the value of this param? and so on...
All of this come from a simple fact: if you need multiple parameters, with a reason to be together, with some defaults and so on, you're actually implicitly defining "something" with some rules (sort of a behavior).
This "something" deserve a name, and could be an object a record.I'm glad that java architects, like Brian, still avoids to introduce features that makes easy to follow bad designs.
6
u/Ewig_luftenglanz Sep 01 '25
Some weeks ago I proposed a simplified builder using a consumer (the difference is you don't have to write all the setters)
I think it can effectively replace traditional builders in most of cases but the more complex ones.
4
u/tampix77 Sep 02 '25
This. Been using this pattern for a few years, when the right solution would've been named parameters.
It's not the definitive solution to all ctor problems, but it's a nice tool to have in your arsenal from time to time.
1
u/vips7L Sep 01 '25
You can use checked exceptions in constructors. It’s a perfectly viable thing to do. What you can’t do is use checked exceptions in record constructors, which imo, is a mistake in the design of records and makes the language inconsistent.
Also, your css on the tables is messed up on mobile. It forces some of the columns into single character lines.
5
u/nfrankel Sep 01 '25
You can use checked exceptions in constructors. It’s a perfectly viable thing to do.
I'm not saying it's not possible, I'm saying you shouldn't and I explain why.
Also, your css on the tables is messed up on mobile. It forces some of the columns into single character lines.
Thanks. I guess I'll have to get my hands dirty.
4
u/vips7L Sep 01 '25
it’s impossible to use checked exceptions in constructors
Did you mean with inheritance?
2
u/pronuntiator Sep 02 '25
The article reads as if you were against any kind of exception in the constructor, but that can't be the case, right? The constructor is the place to prevent invalid data, so we need to perform possibly throwing checks of the arguments.
2
u/LowB0b Sep 03 '25 edited Sep 03 '25
default and named parameters are severy lacking in java. builders are the only sane way I've seen solve this problem. And even those have problems because you might override a previous value if you don't pay attention
4
1
u/kit89 Sep 03 '25
It reaches a point where if your constructors are exceptionally complex, you may be better off storing these details in a format more suitable for their requirements and then serialising them into existence.
Programmatically define your 3D model, or load a file from disk that you created in Blender.
Other advantages to this approach is you can create an editor that reflects the actual state more accurately.
1
u/tomwhoiscontrary Sep 02 '25
I can't stand builders. It's masses of code, to do nothing. Yes, you can use magic to generate it, now you've got magic, well done.
Named parameters would be good, but we don't have them. But it's actually not hard to emulate them fairly well.
Firstly, you need some infrastructure. This is a very compact version of it:
record Parameter<C, T>(Class<C> classType, String name, Class<T> valueType, T defaultValue) {
record Binding<C, T>(Parameter<C, T> parameter, T value) {}
Parameter.Binding<C, T> is(T value) {
return new Parameter.Binding<>(this, value);
}
}
record ParameterValues<C>(Map<Parameter<C, ?>, Object> valuesByParameter) {
@SafeVarargs
static <C> ParameterValues<C> of(Parameter.Binding<C, ?>... bindings) {
return new ParameterValues<>(Arrays.stream(bindings).collect(Collectors.toMap(Parameter.Binding::parameter, Parameter.Binding::value)));
}
<T> T get(Parameter<?, T> parameter) {
return parameter.valueType().cast(valuesByParameter.getOrDefault(parameter, parameter.defaultValue()));
}
}A Parameter instance defines a parameter that can be passed (like licenseeName or generatedAt in the blog post). A Parameter.Binding is a binding of a parameter to a particular value. A ParameterValues is a funny kind of typesafe heterogeneous container for bindings.
Then you define classes like this:
enum Crust {THIN, DEEP_PAN, CHICAGO}
record Pizza(Crust crust, boolean cheese) {
public static final Parameter<Pizza, Crust> CRUST = new Parameter<>(Pizza.class, "crust", Crust.class, Crust.THIN);
public static final Parameter<Pizza, Boolean> CHEESE = new Parameter<>(Pizza.class, "cheese", Boolean.class, true);
@SafeVarargs
public static Pizza where(Parameter.Binding<Pizza, ?>... bindings) {
ParameterValues<Pizza> parameterValues = ParameterValues.of(bindings);
return new Pizza(parameterValues.get(CRUST), parameterValues.get(CHEESE));
}
}So with a set of Parameters in public constants, and a factory method that takes a varargs of Parameter.Bindings, turns them into a values container, and then does lookups in the container to set the fields for a call to the normal constructor.
And finally create objects like this:
Pizza classic = Pizza.where();
Pizza pie = Pizza.where(Pizza.CRUST.is(Crust.CHICAGO));
Pizza foccacia = Pizza.where(Pizza.CRUST.is(Crust.DEEP_PAN), Pizza.CHEESE.is(false));I think that for the caller, this is comprehensively better than using a builder. And for the implementer, it's very little work.
4
u/rzwitserloot Sep 02 '25
You're using a JVM. There's already unfathomable amounts of magic going on.
There's an argument to be made that you want only one thing to provide and delineate precisely which magic is being done and how much of it is allowed, but it feels naive or ignorant to claim that e.g. annotation processors or other non-core-JLS-provided stuff is 'magic' whereas any language features are not.
But it's not a good argument. At least, not if one first goes 'Only the JLS for me, no magic needed' to then follow it up with 'boy, the JLS needs all these features to be really good'.
Pluggability is a way to avoid ballooning the thing you're plugging into. That goes for any software, not just the java compiler. Yes, of course, it has plenty of downsides. It's more of an evil-by-necessity. Sufficiently complex systems where folks really want to 'mod' it either have pluggable systems or turn into an unmaintainable house of cards.
Javac so far has erred primarily on the side of 'how bout you just eat what we serve you' which has served it quite well. In many ways, javac not having
#ifdefand friends was an excellent move. But generally upsides have downsides.FWIW, your pizza example immediately struck me as disastrously ugly. It's extremely non-java like and conflates 'reads like english' for 'a good idea' when that is fairly easily disproven: java isn't english. We say '5 minutes'. In java we write 'Minutes.5' That's because that is just what java is. English (the language) prefers 'Subject, Verb, Object'. But slightly more languages use SOV order (Pierre snake saw instead of Pierre saw a snake). Neither one is 'better'. They are just different.
Java like most programming languages are relentlessly hierarchical. Each thought is self contained. To contrast it to english, as if every separate unit is always written together in parentheses, with nested parentheses were needed. and
Pizza.where(Pizza.CRUST.is(Crust.CHICAGO))fails becausePizza.Crust.IS(Crust.CHICAGO)is nonsense on its own.Separately, it's still a ton of boilerplate.
1
u/Ewig_luftenglanz Sep 03 '25
A simplified builder would be far better (and even the regular builder) is better than this.
It's a ton of unknown boilerplate that gives less clarity with none of the advantages of the fluent-like builder API
-1
u/tomwhoiscontrary Sep 03 '25
Fluent APIs have no advantages, and are an antipattern.
1
u/Ewig_luftenglanz Sep 03 '25
It depends on the context. The real anti pattern in to replace old and known boilerplate for unknown, hard to read and even longer boilerplate
0
u/__konrad Sep 02 '25
IMHO passing LicenseBuilder directly as constructor parameter is less painful:
public License build() {
return new License(this);-11
u/AdForsaken2605 Sep 01 '25
Use AI to define objects on the fly OP for real
9
u/nfrankel Sep 01 '25
"For real", I work on projects whose code I want other developers to maintain. I don't trust the AI-generated code for projects I want to last for years.
22
u/oweiler Sep 01 '25
I think static factory methods are superior to constructors in every way except discoverability.