#Small questions while re-learning java
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
Yes, that is correct. The strictfp keyword in Java ensures that floating-point calculations are performed in a consistent manner across different platforms. If you encounter strictfp in a project using Java versions prior to Java 17, you only need to use it when defining floats and doubles to ensure consistent behavior. It does not have any impact on other data types or methods in your code.
Small questions while re-learning java
I'm not sure what you mean?
It can be applied to classes, non-abstract methods & interfaces
ChatGPT is correct but you rarely even need to use strictfp
Just the keyword "strictfp" it only affects the way floats and doubles are calculated, right?
so if I find it in a project with a java version sub 17, I need to use it when defining new classes, non-abstract methods & interfaces, I don't have to do anything or know anything else. It does not impact me otherwise, yeah?
Yeah, hence why I am asking :D there is not a lot of info out there, because it is rarely used.
It's only a problem if you're using hardware from like pre year 2000 and pre java17 lol
But yes it only affects double and float
and from Java 17, basically every float and double is strictfp anyways.
Ah in that way, yes basically useless nowadays.
SSE2 (Streaming SIMD Extensions 2) is one of the Intel SIMD (Single Instruction, Multiple Data) processor supplementary instruction sets introduced by Intel with the initial version of the Pentium 4 in 2000. It extends the earlier SSE instruction set, and is intended to fully replace MMX. Intel extended SSE2 to create SSE3 in 2004. SSE2 added ...
jep ?
Basically what drives the language forward, that explains the strictfp changes in 17
Got to say, that one? I never heard :D
instead of const Java uses static and final, which is fine I guess :D
The native keyword is neat, only now learned about it, no questions but... huh, neat :D
"throws" keyword... Ok I guess, can lead to some wacky code design I feel :D
"synchronized", "transient" and "volatile" seem to be the 3 keywords I struggle most understanding. I guess I will have to look into multi-threading and serialization in java.
Throws was already around, that's exception related
for transient keep in mind from which package it is. There are 2 flavours.
Yeah I know, but I did not remember it :D
oh?
And things threading wise will get even more interesting in 22 with structured concurrency, but I'll first let you catch up.
there's also a json related transient
How? Ah well :D
I will look into all that tomorrow
If you got something to type, please do :D
Certainly, but I don't want to give an overload.
I do advice is: also appreciate the little things
Oh yeah, if I do get too much info I say so, no worries :D
I do understand "synchronized", "transient" and "volatile" by themselves, but that is kind of useless without the context of multi-threading and serialization
which are imo too big of a topic to learn today too.
like text blocks
String multilineText = """
some
lipsum
"""
The var keyword
Sequenced collections from 21 so we can now do getFirst() rather than get(0)
The new Math clamp functions
...
Oh yeah! I got no idea anymore how collections work at all! :D
Onto the list it goes!
new Math clamp functions? like what?
Previously when you wanted to bound a number you had to write the logic yourself, now we have: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Math.html#clamp(double,double,double)
declaration: module: java.base, package: java.lang, class: Math
oh right, that's another enhancement: searchable javadoc
Neat! :D
You shouldn't use it anymore
Why?
You shouldn't use java default Serialization mechanism, and so transtient
Why?
Because JNI is getting replaced by Panama's Foreign Function and Memory API
When?
Because java default Serialisation is bad
There are talks about that
officially? or is it just best practice?
One of the two major parts of Project Panama is the "Foreign Function and Memory API" (the "FFM API") which saw its third preview in Java 21 and will be finalized in Java 22. In this talk, we will explore how the FFM API enables native methods and memory access with pure Java code and how high performance and safety can be achieved at the same t...
It is currently in the process of getting replaced by it
And it will officially released next month
Oh I see, good to know!
@fickle zephyr note that most of what you said exist since the start of java
And given you asked about floating points, also look at BigDecimal
Yeah, I was very much a beginner when I used Java, was my first language and I did not pick it up since.
I wanted to do my training with Java, but I ended up in Webdev and moved to Python, but now I got a new job and will be using Java.
For the first time since 2017, so I start at the basics. I can draw from my web and python experience and relearn java in a better way.
The school part which used Java was admittedly rather basic.
I call it re-learning because I genuinely started at the complete basics 5 hours ago.
you might also like
MOOC is a completely free introductory Java course created by the University of Helsinki, it is a great way to learn Java from the ground up.
It consists of two parts, one at beginner, and another at intermediate level. The end of the course is marked by creating your own Asteroids game clone!
Even though the instructions show how to configure and use NetBeans for the course, you can use IntelliJ. To use IntelliJ, simply install the TMC plugin by opening IntelliJ -> File -> Settings -> Plugins and searching for TMC. You will then be able to use IntelliJ to complete MOOC.
Visit MOOC here: https://java-programming.mooc.fi/
(the course is available in both English and Finnish)
About the course - Java Programming
Oh right, since you said 2017 if you're still on SVN take a look at git
subversion
I am afraid my approach back then to Java was "MAKE" and not at all structured or otherwise sensible. I started with Minecraft mods, then started making my own game engine. No Prior experience with Java. I did learn a lot and in some areas (visual programming with AWT/Swing/JavaFX) I got pretty far, but I do have holes in my knowledge I want to fill.
@fickle zephyr
Your question has been closed due to inactivity.
If it was not resolved yet, feel free to just post a message below
to reopen it, or create a new thread.
Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.
When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.
Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.
With enough info, someone knows the answer for sure 👍
Hey, I got time again! :D
I want to understand the transient keyword's interaction with the final keyword.
final Strings will be serialised and the transient keyword has no effect on them, what about other datatypes?
I have read, that the final modifier makes no difference when it has literal initialization, but what does that mean?
What? How is this even related?
Final don't prevent transient to work
In fact, they have literally nothing in common
Behavior With final and Behavior With final String Using new Operator have their own sections
that has nothing to do with transient though
its just how final and string literals work as per jls
which u can also see nicely here
So, the transient keyword has no effect on them?
final String a = "a";
System.out.println(a + "b" == "ab"); // outputs true
// versus
String a = "a";
System.out.println(a + "b" == "ab"); // outputs false
and that's about it?
the transient keyword plays no role in this particular example
Ah that's the difference between a true constant and a final variable
But realated to this, https://www.baeldung.com/java-transient-keyword I am not sure I am right, so I'll ask again, examples 4 and 4.1 would be the same without the transient keyword?
@ancient fossil @silent dew
My understanding is classes, variables, objects, or fields can be marked as transient, and will be exported and imported with their default values instead. the exception is that the keyword has no effect when used with the final keyword.
no. ur misunderstanding
in the first example with final and a literal, u dont have a variable to begin with
the variable bookCategory does essentially not exist
its not part of books
the jls determines that (bc of final and a string literal), its a compile-time-constant
so its inlined
bc of that, the transient keyword cant have effect on it
the variable that would be marked transient or not doesnt really exist
so transient preventing it from being serialized has no effect
since its absent already anyways
in the second example, u have a "regular object" that isnt compile-time-constant
so the variable is an ordinary variable
and having transient there will prevent it from being serialized
I see, thank you :)
So, now that I looked at it, it is time to ask why it is bad.
Certainly error prone, when used incorrectly, but is that all?
also security risks
there have been a few bigger incidents
with attacks
for example london substation was offline for a few days
yeah... understandable.
Java Serialization is well known to be one of the worst features of Java. It's been mentioned as such in various "Ask the Experts" panels over the past few years. Joshua Bloch's book "Effective Java" describes many dangers of serialization, and it devotes an entire chapter to the topic. But isn't this merely a recent group of Java platform desig...
since java serialization doesnt use any data scheme but supports deserializing arbitrary java objects. and worse, also graphs with cycles
and not just single objects
its the one big difference that no other serialization mechanisms offer
like json for example
no cycles, no arbitrary object graphs
- support for data schemes so that u dont deserialize other unrelated data
oooooooh wow, okay that is much worse than I expected :D
and thats just the security aspect
the other problem is, similar to the deprecated Clonable interface, it attempts to create objects by black magic
bypassing constructors
so it can easily bypass any invariants u check in ur constructor/setters
and its almost impossible to get it right with inheritance
since it just bypasses all ur constructors that u setup carefully
so unless u literally only have simple objects to serialize, chances are it will just get it wrong
Okay, I guess I see why it is that way, but damn is it bad
but sure, if ur just making some smaller personal use program, why not, its easy to use and boom u have a "save state" and "load state" mechanic in ur program in just 10 minutes
which is kinda cool tbh
it was also a major pillar of javas success back in the 90s
being the only programming language at the time with a proper serialization mechanism
Yee, still, I did not think it did all that
guess if it is propperly exported and imported doesn't really matter, but yeah, I can see it being error prone.
Or just duplicate code and do the same checks :D
It does
?
care to elaborate? :D If you properly export and import data that you are sure was not manipulated and do the checks yourself again... I think it's ok.
It is not a good system, and I'd use alternatives, but it is not the worst.
yeah so the main issue with that is that its super cumbersome
suppose theres some data in ur class that u want to recreate each time its created
u would put that code in ur constructor
Absolutely, that all is incapsulated in "error prone" for me :D
or some code that u need to trigger each time the objects are created
u would put that code in ur constructor
but deserialization doesnt use constructors
so u would likely run into that pitfall
Or make a method that is called by your constructor AND import method
Like, yeah. still, cumbersome, error prone, whatever you want to call it.
java deserialization goes through a magic method called private void readObject(java.io.ObjectInputStream stream) instead
so thats its "constructor"
but this method doesnt work correctly in presence of inheritance
u would want the animal class to setup its base class part
before the dog class takes its part
Wait, that's... new information
but instead, only dogs method is called
so it is even worse??? :D
and dog must then setup everything
same issue as with Clonable
if u make Animal and Dog Clonable, Dog must do all the clonable shit of animal
So... what do you use instead? I'd just export and import as JSON, but that's just me.
hmm, alright.
xml
fair
csv
jucky
bson, protobuf
the what?
Check the video I shared
I might, not sure I'll have the time.
bson is json but in binary instead of text.
protobuf is the same idea but driven to an extreme. its even better
they are primarily used when u have to send sth on the wire, since they are as compact as possible - instead of json which is just looong text
But thank you very much none the less :) @ancient fossil
Yeah, there are so many out there, and people told me not to use JSON and use something instead.
People don't even remember that anymore :D I don't either.
Java Serialization is well known to be one of the worst features of Java. It's been mentioned as such in various "Ask the Experts" panels over the past few years. Joshua Bloch's book "Effective Java" describes many dangers of serialization, and it devotes an entire chapter to the topic. But isn't this merely a recent group of Java platform desig...
protobuf is as compact as it can be. suppose u have a class with 2 ints and a double.
then protobuf will just save it as single binary compact stream consisting of 32+32+64 bits with the data in exactly that order
the "disadvantage" is that u cant make sense of this data unless u know its scheme
i.e. "2 ints, one double in that order"
if u know that scheme, u can read the data
therefore, its as compact as it can be. only transporting the pure data, no structure or type information at all
Yeah, that's neat! :D
@silent dew Thank you for your time! I'll keep learning and asking stuff here if anything comes up :)
Those people that told you not to use JSON either work at a FAANG (where it actually matters), or haven't built any decent sized application at all
Nope, gamedevs
I use JSON just because it's readable. Esp in bigger projects this is immensely helpful
Could have been YAML or Something with L or E
It was a fad, they are back to JSON :D
well, if you have a ton of binary data yeah, then maybe json is not that great of an idea, I wouldn't make a model format with json 😄
But for metadata, sure why not
look at GLTF
They have GLB, json + binary buffers
GLTF?
TBH I don't instantly see any use for it,
Yeah, that sure, but saving whole scenes is special about it
and I wonder what anyone would use it for
I'd just save like until now too, and then rebuild the scene
yeah, just an example of where I think they used json correctly. as metadata, and store all other information binary
ALTHOUGH base64 can be decoded pretty much instantly nowadays
Java's default multithreading is not bad, right?
I see it kinda encuraging bad code design too (Syncronise shouldn't exist imo) but it's fine, right?
It works, and if you know what you're doing, it's actually good
also synchronized is fine in cases, commited some code with synchronized last week
But yeah, in a new code base, there exist better things
Sure but why multithread if you need to synchronize a part anyways, it seems like an awful bottleneck.
In computer architecture, Amdahl's law (or Amdahl's argument) is a formula which gives the theoretical speedup in latency of the execution of a task at fixed workload that can be expected of a system whose resources are improved. It states that "the overall performance improvement gained by optimizing a single part of a system is limited by the ...
Depends on how much you can actually split off in a separate thread
When I multithread it's usually independent blocks that have nothing to do with each other, and of which I just want to synchronize on the actual results
in a new code base - That's how legends start :D
Like for example, downloading files in chunks, or rendering out png's, stuff like that
Jokes aside, what is there?
there's parallel streams, completablefutures, a whole lock system, mutexes, virtual threads, etc etc
I see! that is quite a bit to research! so I won't! I got other stuff to learn first :D
javas multithreading is good
it depends on what exactly ur looking at though
ideally u use the newer stuff
so the future api
and executor services
avoid manual thread management
and soon we will get virtual/green threads as well, in which case u can create millions of mini tasks with the future api without performance impact
"soon"
virtual threads work, spring boot now has first class support
yeah but there are still significant changes planned for them
And for more functionality you want structured concurrency from 22
Yeah, will look into that too :)
But first, I need to relearn the basics. I was a kid when I learnt Java, so I got some holes in my knowledge and then catch up to the newest version
That said I am keeping notes of stuff to look into later, if you think anything would be benefitial for me, feel free to tell me all the same :)
that's for way down the line
I know:)
I am not too sure about Json being just as bad. Again, error prone, you need to cherrypick data exported, check data imported, but doesn't have the same exploits, does it?
Watching the video right now, btw :)
- that was 4 years ago and there still is not anything done about it???
No
Like yeah, not optimal but not as dangerous.
yeah, so for json usually this gets done via reflection. Which is arguably a tiny bit safer than using serialization
But, there's tools, like immutables or kotlinx.serialization that can do compiletime code generation
These generate reflectionless deserialization code for you
Which is arguably a lot safer
No idea about kotlin or groovy :D
I want to get deep into java first, before I try any other flavors.
Except if I need some other language for a project.
Well no
deep reflection - meaning anything where you bypass a constructor or use setAccessible(true) - is just as unsafe as serialization
but normal reflection - meaning just magically calling methods you already have permission to - is a bit safer
Afaik unless you allow it just the regular constructors get called
For gson and Jackson
the private field thing? :D
Sure
public class Main {
public static void main(String[] args) throws Exception {
var thing = new Thing();
var field = Thing.class.getDeclaredField("value");
// Try commenting out this line
field.setAccessible(true);
field.set(thing, 5);
System.out.println(thing.getValue());
}
}
public class Thing {
private int value;
public Thing() {}
public int getValue() {
return this.value;
}
}
it will, if it can't do it another way, set private fields as acessible
and it will set them reflectively
which bypasses any checks you might have
like
The fact you can set private fields accessible at all... Is a scary fact to me
public class Thing {
private int value;
public Thing() {}
public int getValue() {
return this.value;
}
public void setValue(int value) {
if (value < 0) { throw new IllegalArgumentException(); }
this.value = value;
}
}
so gson could put a negative value in there
right, so thats what modules are for
if you have code in a module, other modules can't set private fields
What?
like you can no longer set private fields on java.lang.ArrayList
setAccessible won't work
Actually for the first time, I don't get something :D
I don't have to context to that :D
well see how i do this
var field = Thing.class.getDeclaredField("value");
// Try commenting out this line
field.setAccessible(true);
field.set(thing, 5);
you used to be able to do
Yes?
var field = ArrayList.class.getDeclaredField("size");
field.setAccessible(true);
field.set(list, -124);
which obviously, if you are the person who maintains Java is annoying
so they introduced a mechanism called modules
module java.base {
exports java.lang;
}
so all the classes in the java.lang package can't be "deeply reflected" on by classes outside the java.base module
module java.base {
exports java.lang;
opens java.lang to jdk.internal;
}
Modules, I did not read that at all, but still... I think you shouldn't be able to modify access state PERIOD
right, and yet they allowed it in the past
and java doesn't break backwards compatibility
Honestly, the most horrifying thing about java for me right now.
That just means you need to find a way to execute code in another module, it's not good.
Yeah, it would have to be an exploit, but I can totally see that being possible.
IMO access states should be permanent.
well what modules do is make it a local analysis
you just need to look through the code for the library
not the entire program
to make sure nothing is set strangely
I see
obviously if you have a big module thats not much of a benefit
but you also are guarenteed that none of your libraries (like gson) set private fields
which is where the real risk is - your supply chain
Yeah, totally. But once it is in the same module it could possible set every possible field public, read and redirect.
you can re-enable that capability if you need to
module my.project {
opens my.project.thing to com.google.gson;
}
To me it is a nightmare by design.
well, compare it to other languages
Python has zero protections against it
C# can set private fields too
Other languages having the same problem does not make me less worried about it xD
(idk if they have a module thing)
but in the scope of things, being able to prevent it is better than not being able to prevent it
True
the people in charge of java are more or less aware of all the parts that suck
the next big thing is going to be the ability to make your own primitive types
like NonZeroInt
which is going to include the ability to do stuff like
ArrayList<int> list = new ArrayList<>();
so if there isn't progress on something else you care about its probably because that is the focus
Alright :D
No, I don't think this will ever be focus tbh, it's just a security risk.
@crude mango Thank you for your time ^^
well people were pretty pissed with the module system because they decided to spend time on it before any of the stuff they are doing now
basically they are writing more of the JVM in java
and in that context invariants matter a lot
so features like virtual threads wouldn't exist without the module system
Yeah, the more I learn about what they do the more I think they are doing the right thing.
But yeah, Java is... a big Project, there will be parts to dislike.
Holy crap, I don't know absolute basics anymore.
Until now, basically I just looked at hello world xD
I am not joking, because I got the idea to look at all keywords because of it, which lead me down a few rabbitholes.
So, absolutely basic question.
System.out.println()
How do I structure my code like that? I can make Class.method, but the out in System.out.println() point at the line
"public static final PrintStream out = null;" which makes me ask myself a few questions.
Why null?
What is it exactly? an instance of PrintStream called out?
This is confusing for multiple reasons :D
"out" is also OutputStream which is basicly the super of PrintStream, so... ???
this one?
yes
System is a class out is a public field of type PrintStream in the System class and the PrintStream class has a method called println along with many other methods
so the code will be
public class System {
public static final PrintStream out = new PrintStream(...);
...
}
and u usually shouldn't do this
this is a bad design
System.out is an extremely wierd special case
public static final PrintStream out = null;
r u recompiling it from bytecode? maybe it is initialized somewhere else not directly in the decleration
there is even a setOut method even though it is a final field
don't look too close at the physics
Yeah :D
an instance of PrintStream called out?
yes it is exactly that nothing fancy
So
class BasicConceptTesting {
public static void main(String[] args) throws Exception {
thing.test.testprint();
}
}
public class thing {
public static final thing2 test = null;
}
public class thing2 {
public void testprint() {
System.out.println("done");
}
}
Would this be a common method way of structuring methods?
Detected code, here are some useful tools:
class BasicConceptTesting {
public static void main(String[] args) throws Exception {
thing.test.testprint();
}
}
If not, what is the common way of structuring methods?
and why is it = null?
@torpid tendon @crude mango If you don't want pings, tell me, but I'd like to get past hello world today xD
Even if I am doing a technical anaysis of it, I am still stuck on hello world xD
no
System.out is strange
Exactly why I don't move on yet xD
dont try to replicate System.out
if i dont want pings i'll delete my discord account
Okay, so. How would I do it? If I just want to structure many methods?
.
it will get initialized somewhere else in the code
for example
public class System {
public static final PrintStream out = null;
static {
out = new PrintStream();
}
}
Like this is very funny to me, because System.out is so elemental, yet I can learn things from it.
alright, that's cool!
yea thats true, its just more u notice more u learn
.
structure many methods? wdym?
public class TogetherJava {
public static doSomething() { ... }
public static doOtherThing() { ... }
}
like this?
yea this is how u do that
but when writing real code u'll just never need to do that is what we mean
Oh, alright then. But nah, I can see a reason to do it this way :D
What if I write something big? Let's say I make a game engine, I can see the Animation controller getting over 100 methods, what would you do to structure it?
idk i never saw any other instance of smth like that
Alright that's fair :D
I'll make a solo post about it, I find the question interesting
We are not talking about the same thing
Let's say you use Jackson
It's not error prone, wdym cherrypick data exported
Serialisation is literally black magic, it bypass every feature that you know in java, it bypas constructors, it bypass final, everything is wrong
And in order to implement it correctly, you have to use this extremelly convoluted boilerplate code which is very error prone, which ask you to duplicate code, which prevents you from using final, and there are so many ways it could go wrong
All of this is shown in the video
Yeah, I am on the fence about it.
I am unsure if it is as dangerous when It comes to exploits.
But having more details, yes, it is bad.
That said, with "Hello world" out of the way (Which I looked into soo deep I went into serialisation and multi-threading), I can kind of burn trough the rest, types, conversions, getter, setter, time ect... Not really much in there that I'll have questions about.
well getter and setter aren't really the thing anymore
what :D
you are pulling my leg, right?
well, for data aggregates
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
}
this is no longer popular
this is
public record Person(String name, int age) {}
which doesn't have setters
(there is a notion of a reconstruction protocol...but yeah)
record? 👀
but the age of just slapping getters and setters on a data aggregate is over
the age of immutable data is here
Oh yeah, people are all over it. Kind of a fad imo, give it 5-10 years.
That said, java 14? what year was that
2020, Oh I see.
Why do people prefer it? @crude mango
Lombok?!? :D
Does lombok not just autogenerate getter and setter?
I had to, less than a year ago. Was part of my training as a dev :D
well lombok works by using internal parts of the java compiler
the java team want to make people acknowledge that "risk"
and add a bunch of --add-opens jdk.compiler/java.internal.whatever=lombok flags when they run the compiler
which, if you remember, opens things to deep reflection
or --add-exports
which exports packages they didn't export
the risk is that they are going to act as if nobody relies on the details in those packages
so lombok can break in any java version
and absent effort from the lombok maintainer it will break any time they change internals
That's true.
ron pressler is on the java team
renier zswitserloot is the lombok maintainer
so lombok currently uses some loopholes in the module system so people dont need to add special flags
but back to this, why do people like records, rather than getter and setter?
and the jdk team thinks doesn't like that and will close the loopholes soon-ish
Well that comes down to immutability
immutable data is easier to reason about
which is a way larger topic
but people are going to prefer it because its way shorter
and as a consequence they accept the (better) semantics of immutable data
I see, well thank you :)
and the methods are no longer called .getThing() its just .thing()
But it is past 1 am, I will get back in a few days after reading a bit myself with a list of topics I got grasp of, and hope someone will jump in if some of it is too old :D
Convention 2.0
idk y ppl decided to call it get in the first place
(90s gui builders)
it always seemed so weird to me, but i didn't wanted to go against convention
records are special, they are named tuples, which implies many things
implies... what things :D
I don't mean to be annoying, just geuenly interested.
Their fields are parts of the record
So they must be accessible, so the record can be constructed and deconstructed from those, etc
Read a bit about it... Sure. If it is not changed then you can use it instead of getter and setter, the same would you cound have a class without setter, but if you need to change those while in memory, getter and setter are still the way to go, no?
records do have getters
I don't see how records replace getter and setter :D @crude mango
Yes.
public record Person(String name, int age) {}
well today this is not enough
Immutability is great
public record Person(String name, int age) {
public Person withName(String name) {
return new Person(name, this.age);
}
public Person withAge(int age) {
return new Person(this.name, age);
}
}
var p = new Person("bob", 40);
p = p.withAge(41);
wait for withers 👀
Honestly I might just be too tired, creeping closer to 2 am :D
Like I get the code, but I don't really get why it's better than getter/setter.
Sure, I'll see :D
Would like keeping this one for the basic questions tbh, once I am trough everything basic I will make a new one.
Lombok still has valid uses even with records
I use both 🤷♂️
If all you did with Lombok was Data and Value yeah records replace it
I try to avoid setters and give methods that change an objects internal state meaningful names. But those objects are usually quite rare in any new project I write
Good Morning! :) @cyan knoll @crude mango I don't get why records are better than getter setter. In gamedevelopment for example, the great thing about OOP is that you can change atributes of Objects on the fly. Sure for Webdev I can see usecases where you don't have a single setter, you get data from a database and write to it. But seems dependent on usecase.
Gamedev in general is quite different from regular java application design. "Don't allocate anything" is something I've heard when developing games
So yeah, you'd want to do mutable everything, but man that's code that I definitely do not want to write lol
Gamedev is defo code noone wants to write. And gamedevs are paid bottom of the barel.
But yeah, you can't say records are better, depending on the designpatterns you need, they could be.
Well, unless you REALLY want to minimize allocations (find me usecases), then immutable is always better
Well, as return values at least, what you do behind the scenes of an api, 🤷 , as long as you don't keep to much state on hand
See above :D If data is changed a lot, while having the same properties, but different values.
Yeah for webdev I can see this working, I can't even thing of a usecase I'd absolutely need setters in the backend.
You'd be surprised how little data is changed in general 🙂
Well, we can argue about usecases all we want, but the general gist is: immutable good, mutable state bad. So records are definitely a good add
Yeah, records good. But you can't replace every use of setters with them without making it wastly unreadable and inefficient.
well no, if you need to modify the data in place, you need to modify the data in place
But I've noticed, it's surprisingly rare
In a project I'm working on right now, I have exactly 100 records, and 99 classes
Even if data is edited 3 times, you could draw a line, and use 4 different records for example.
but for any type of non linear workflow it gets worse. create a new record for every change.
Yeah. Webdev, QA data science, all have no need for mutable data most of the time.
Oh? what do you mean?
Like, when I need to set a property at a different time
Can you give me a code example? I have not yet looked further into records.
public record StreamDbEntry(
long identity,
int offset16,
int length
) {
public static final int BYTES = 16;
public static StreamDbEntry read(BetterBuffer buffer) {
var identity = buffer.getLong();
var offset16 = buffer.getInt();
var length = buffer.getInt();
return new StreamDbEntry(identity, offset16, length);
}
public long offset() {
return offset16 * 16L;
}
}
For example
public record Mesh(
VertexBuffer faceBuffer,
Map<Semantic, VertexBuffer> vertexBuffers,
int materialIndex
) {
public Mesh {
Check.notNull(faceBuffer, "faceBuffer must not be null");
vertexBuffers = Map.copyOf(vertexBuffers);
}
public Optional<VertexBuffer> getBuffer(Semantic semantic) {
return Optional.ofNullable(vertexBuffers.get(semantic));
}
public Mesh withMaterialIndex(int materialIndex) {
return new Mesh(faceBuffer, vertexBuffers, materialIndex);
}
}
Detected code, here are some useful tools:
Everything I said is just from records being immutable. Which... yeah. The trend of immutability is kind of dubious to me.
This one has a .with
Yes, but as I said, those create a new record too, no?
yeah, so? 😄
Are the references to the old one updated and old entries garbage collected?
I map these in a stream
so I don't have the old references anymore
Don't make hierarchical records if you need to change the lowest level lol, that's pain
Sooo... no. Yeah then my point stands, in non linear workflows they have less use.
Fair :D