#Small questions while re-learning java

1 messages · Page 1 of 1 (latest)

fickle zephyr
#

About the keyword strictfp - If I encounter it in a project sub Java 17, I only have to define floats and doubles with it should I add any new ones, does not impact me otherwise, right?

valid mirageBOT
#

<@&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.

fickle zephyr
#

Small questions while re-learning java

formal relic
#

It can be applied to classes, non-abstract methods & interfaces

void walrus
#

ChatGPT is correct but you rarely even need to use strictfp

fickle zephyr
# formal relic I'm not sure what you mean?

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?

fickle zephyr
void walrus
#

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

fickle zephyr
#

and from Java 17, basically every float and double is strictfp anyways.

formal relic
#

Ah in that way, yes basically useless nowadays.

void walrus
#

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 ...

formal relic
void walrus
#

This is the "why" it was needed on legacy systems

#

Oh nice that jep references SSE2

fickle zephyr
#

jep ?

void walrus
#

The link that Simon sent

#

JEP = JDK Enhancement Proposal

formal relic
#

Basically what drives the language forward, that explains the strictfp changes in 17

fickle zephyr
#

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

fickle zephyr
#

"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.

formal relic
#

Throws was already around, that's exception related

#

for transient keep in mind from which package it is. There are 2 flavours.

fickle zephyr
formal relic
#

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

fickle zephyr
#

I will look into all that tomorrow

#

If you got something to type, please do :D

formal relic
#

Certainly, but I don't want to give an overload.

#

I do advice is: also appreciate the little things

fickle zephyr
#

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.

formal relic
#

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

...

fickle zephyr
#

Oh yeah! I got no idea anymore how collections work at all! :D
Onto the list it goes!

#

new Math clamp functions? like what?

formal relic
#

oh right, that's another enhancement: searchable javadoc

fickle zephyr
#

Neat! :D

ancient fossil
fickle zephyr
ancient fossil
ancient fossil
ancient fossil
formal relic
fickle zephyr
formal relic
#

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...

▶ Play video
ancient fossil
# fickle zephyr When?

It is currently in the process of getting replaced by it
And it will officially released next month

ancient fossil
#

@fickle zephyr note that most of what you said exist since the start of java

formal relic
#

And given you asked about floating points, also look at BigDecimal

fickle zephyr
# ancient fossil <@197845876478181376> note that most of what you said exist since the start of j...

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.

formal relic
#

you might also like

valid mirageBOT
#

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

formal relic
#

Oh right, since you said 2017 if you're still on SVN take a look at git

fickle zephyr
#

Sure, will look at that too.

#

What is SVN? :o

formal relic
#

subversion

fickle zephyr
#

Ah yeah subversion

#

no, never used it :D

fickle zephyr
valid mirageBOT
#

@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 👍

fickle zephyr
#

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?

ancient fossil
#

Final don't prevent transient to work

#

In fact, they have literally nothing in common

fickle zephyr
#

Behavior With final and Behavior With final String Using new Operator have their own sections

silent dew
#

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

fickle zephyr
#

So, the transient keyword has no effect on them?

silent dew
#
final String a = "a";
System.out.println(a + "b" == "ab"); // outputs true

// versus

String a = "a";
System.out.println(a + "b" == "ab"); // outputs false
fickle zephyr
silent dew
#

the transient keyword plays no role in this particular example

ancient fossil
fickle zephyr
#

@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.

fickle zephyr
#

That's why I am here :D

#

I mean exported without the values, but yeah

silent dew
#

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

fickle zephyr
#

I see, thank you :)

fickle zephyr
silent dew
#

there have been a few bigger incidents

#

with attacks

#

for example london substation was offline for a few days

fickle zephyr
#

yeah... understandable.

ancient fossil
# fickle zephyr So, now that I looked at it, it is time to ask why it is bad. Certainly error pr...

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...

▶ Play video
silent dew
#

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
fickle zephyr
#

oooooooh wow, okay that is much worse than I expected :D

silent dew
#

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

fickle zephyr
#

Okay, I guess I see why it is that way, but damn is it bad

silent dew
#

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

fickle zephyr
#

Yee, still, I did not think it did all that

fickle zephyr
#

Or just duplicate code and do the same checks :D

fickle zephyr
#

?

fickle zephyr
# ancient fossil 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.

silent dew
#

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

fickle zephyr
#

Absolutely, that all is incapsulated in "error prone" for me :D

silent dew
#

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

fickle zephyr
#

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.

silent dew
#

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

fickle zephyr
silent dew
#

but instead, only dogs method is called

fickle zephyr
#

so it is even worse??? :D

silent dew
#

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

fickle zephyr
#

So... what do you use instead? I'd just export and import as JSON, but that's just me.

silent dew
#

its just a clusterfuck of edge cases

#

yeah. json or similar formats

fickle zephyr
#

hmm, alright.

silent dew
#

xml, csv, bson, protobuf

#

paired with sth like jackson/gson as library and ur gucci

fickle zephyr
#

xml
fair
csv
jucky
bson, protobuf
the what?

fickle zephyr
silent dew
#

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

fickle zephyr
#

But thank you very much none the less :) @ancient fossil

fickle zephyr
ancient fossil
# fickle zephyr I might, not sure I'll have the time.

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...

▶ Play video
silent dew
#

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

fickle zephyr
#

Yeah, that's neat! :D

#

@silent dew Thank you for your time! I'll keep learning and asking stuff here if anything comes up :)

cyan knoll
cyan knoll
#

I use JSON just because it's readable. Esp in bigger projects this is immensely helpful

fickle zephyr
#

Could have been YAML or Something with L or E

#

It was a fad, they are back to JSON :D

cyan knoll
#

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

fickle zephyr
#

GLTF?

cyan knoll
#

Khronos scene format basically

fickle zephyr
#

TBH I don't instantly see any use for it,

cyan knoll
#

I use it as an export format for 3d models etc

#

blender has excellent support for it

fickle zephyr
#

Oh yeah, as that sure

#

But scenes?

cyan knoll
#

meh, maybe a stretch

#

but a whole bunch of static geo, sure

fickle zephyr
#

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

cyan knoll
#

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

fickle zephyr
#

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?

cyan knoll
#

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

fickle zephyr
cyan knoll
#

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

fickle zephyr
cyan knoll
#

Like for example, downloading files in chunks, or rendering out png's, stuff like that

fickle zephyr
#

Jokes aside, what is there?

cyan knoll
#

there's parallel streams, completablefutures, a whole lock system, mutexes, virtual threads, etc etc

fickle zephyr
#

I see! that is quite a bit to research! so I won't! I got other stuff to learn first :D

silent dew
#

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

silent dew
#

the api isnt fully finalized yet

#

but sure

cyan knoll
#

virtual threads work, spring boot now has first class support

silent dew
#

yeah but there are still significant changes planned for them

cyan knoll
#

Yeah, not to the core APIs

#

Just extra fluff around them

formal relic
#

And for more functionality you want structured concurrency from 22

fickle zephyr
#

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 :)

formal relic
#

that's for way down the line

fickle zephyr
#

I know:)

fickle zephyr
#

Watching the video right now, btw :)

#
  • that was 4 years ago and there still is not anything done about it???
fickle zephyr
#

Like yeah, not optimal but not as dangerous.

cyan knoll
#

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

fickle zephyr
#

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.

crude mango
#

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

cyan knoll
#

Afaik unless you allow it just the regular constructors get called

#

For gson and Jackson

crude mango
#

gson does the private field thing

fickle zephyr
#

the private field thing? :D

crude mango
#

yeah so

#

1 sec let me make an example

fickle zephyr
#

Sure

crude mango
#
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;
    }
}
fickle zephyr
#

Okay, what does gson do?

#

@crude mango

crude mango
#

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

fickle zephyr
#

The fact you can set private fields accessible at all... Is a scary fact to me

crude mango
#
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

crude mango
#

if you have code in a module, other modules can't set private fields

crude mango
#

like you can no longer set private fields on java.lang.ArrayList

#

setAccessible won't work

fickle zephyr
#

Actually for the first time, I don't get something :D

fickle zephyr
crude mango
#
        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

fickle zephyr
#

Yes?

crude mango
#
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

fickle zephyr
#

Okay, yeah?

#

I get all that

crude mango
#

so they introduced a mechanism called modules

fickle zephyr
#

AH SORRY

crude mango
#
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;
}
fickle zephyr
#

Modules, I did not read that at all, but still... I think you shouldn't be able to modify access state PERIOD

crude mango
#

right, and yet they allowed it in the past

#

and java doesn't break backwards compatibility

fickle zephyr
#

Honestly, the most horrifying thing about java for me right now.

crude mango
#

so modules are a way to add it in

#

you can't break encapsulation across modules

fickle zephyr
#

That just means you need to find a way to execute code in another module, it's not good.

crude mango
#

hm?

#

even if you pass a callback it will still respect stuff

fickle zephyr
#

Yeah, it would have to be an exploit, but I can totally see that being possible.
IMO access states should be permanent.

crude mango
#

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

fickle zephyr
#

I see

crude mango
#

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

fickle zephyr
#

Yeah, totally. But once it is in the same module it could possible set every possible field public, read and redirect.

crude mango
#

you can re-enable that capability if you need to

module my.project {
   opens my.project.thing to com.google.gson;
}
fickle zephyr
#

To me it is a nightmare by design.

crude mango
#

Python has zero protections against it

#

C# can set private fields too

fickle zephyr
crude mango
#

(idk if they have a module thing)

fickle zephyr
#

No idea, I used less C# than Java.

#

:D

crude mango
crude mango
#

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

fickle zephyr
#

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 ^^

crude mango
#

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

fickle zephyr
#

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.

fickle zephyr
#

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... ???

sweet parrot
#

this one?

fickle zephyr
#

yes

sweet parrot
#

i have no clue ngl

#

sry

torpid tendon
#

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

crude mango
torpid tendon
#

public static final PrintStream out = null;
r u recompiling it from bytecode? maybe it is initialized somewhere else not directly in the decleration

crude mango
#

there is even a setOut method even though it is a final field

#

don't look too close at the physics

fickle zephyr
torpid tendon
#

an instance of PrintStream called out?
yes it is exactly that nothing fancy

fickle zephyr
#

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?

valid mirageBOT
fickle zephyr
#

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

fickle zephyr
#

Exactly why I don't move on yet xD

torpid tendon
#

dont try to replicate System.out

torpid tendon
fickle zephyr
#

Okay, so. How would I do it? If I just want to structure many methods?

fickle zephyr
torpid tendon
#

for example

#
public class System {
  public static final PrintStream out = null;

  static {
    out = new PrintStream();
  }
}
fickle zephyr
#

Like this is very funny to me, because System.out is so elemental, yet I can learn things from it.

#

alright, that's cool!

torpid tendon
torpid tendon
fickle zephyr
#

Yes but like sys.out.pln, 3 layers

#

As I said, I can do Class.method :D

torpid tendon
#

but when writing real code u'll just never need to do that is what we mean

fickle zephyr
#

Oh, alright then. But nah, I can see a reason to do it this way :D

fickle zephyr
torpid tendon
fickle zephyr
#

Alright that's fair :D

#

I'll make a solo post about it, I find the question interesting

ancient fossil
# fickle zephyr Like yeah, not optimal but not as dangerous.

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

fickle zephyr
fickle zephyr
#

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.

crude mango
fickle zephyr
#

you are pulling my leg, right?

crude mango
#
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)

fickle zephyr
#

record? 👀

crude mango
#

but the age of just slapping getters and setters on a data aggregate is over

#

the age of immutable data is here

fickle zephyr
fickle zephyr
#

2020, Oh I see.

#

Why do people prefer it? @crude mango

#

Lombok?!? :D

crude mango
#

no

#

don't use that

fickle zephyr
#

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

crude mango
#

yeah...

#

go on r/java and watch ron pressler and renier zswitserloot fight over it

fickle zephyr
#

over what?

#

xD

crude mango
#

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

fickle zephyr
crude mango
#

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

fickle zephyr
crude mango
#

and the jdk team thinks doesn't like that and will close the loopholes soon-ish

crude mango
#

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

fickle zephyr
#

I see, well thank you :)

crude mango
#

and the methods are no longer called .getThing() its just .thing()

fickle zephyr
#

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

torpid tendon
#

idk y ppl decided to call it get in the first place

crude mango
#

(90s gui builders)

torpid tendon
#

it always seemed so weird to me, but i didn't wanted to go against convention

ancient fossil
fickle zephyr
#

implies... what things :D

fickle zephyr
ancient fossil
fickle zephyr
#

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?

ancient fossil
#

records do have getters

fickle zephyr
#

I don't see how records replace getter and setter :D @crude mango

fickle zephyr
crude mango
#

well today this is not enough

crude mango
#
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);
crude mango
#

but in a future version

#
var p = new Person("bob", 40);
p = p.with { age = 41; };
fickle zephyr
#

Like I get the code, but I don't really get why it's better than getter/setter.

crude mango
#

just sleep

#

let us know when its a normal time again

#

maybe make a new thread

fickle zephyr
#

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.

crude mango
#

nah just make a new one for each

#

its easier for us

fickle zephyr
#

Okay then, I will :)

#

Alright, good night everyone :)

cyan knoll
#

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

cyan knoll
fickle zephyr
#

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.

cyan knoll
#

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

fickle zephyr
#

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.

cyan knoll
#

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

fickle zephyr
fickle zephyr
cyan knoll
#

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

fickle zephyr
#

Yeah, records good. But you can't replace every use of setters with them without making it wastly unreadable and inefficient.

cyan knoll
#

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

fickle zephyr
#

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.

cyan knoll
#

In those 100 records I have 4 with methods

#

I just make them when I need them

fickle zephyr
fickle zephyr
cyan knoll
#

Like, when I need to set a property at a different time

fickle zephyr
#

Can you give me a code example? I have not yet looked further into records.

cyan knoll
#
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);
    }
}
valid mirageBOT
fickle zephyr
#

Everything I said is just from records being immutable. Which... yeah. The trend of immutability is kind of dubious to me.

cyan knoll
#

This one has a .with

fickle zephyr
fickle zephyr
#

Are the references to the old one updated and old entries garbage collected?

cyan knoll
#

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

fickle zephyr
cyan knoll
#

Also, mine as well. If you really NEED mutability, don't use records

#

simple as that

fickle zephyr
#

Fair :D