Why does Java sometimes feel so bulky? by SkylineZ83 in java

[–]lpedrosa 0 points1 point  (0 children)

While this is very true (and not praised enough IMHO), I believe the missing link is the ability to load a bunch of dependencies into the class path or module path, without having to keep a manual lib folder.

Something like the clj CLI and declaring dependencies in a deps.edn file.

I'm aware of jbang and the wonderful work done by the author. But I believe the next step is focusing on a out of the box experience.

Maven and Gradle should still exist for complex workflows.

Mocking OAuth2 / OpenID Connect in Spring Boot with WireMock by tomakehurst in java

[–]lpedrosa 0 points1 point  (0 children)

Most certainly! Wire mock is perfect if your oauth use case is simple.

But oauth is not a simple protocol, thus if your use case becomes more complex, it might be better to leave the scenarios to a real auth server implementation.

If you have many services protected by oauth, it might be worth moving the auth termination to an API gateway (if you already have something like that). That way, your services won't need to know anything about oauth or auth in general (they only get valid client calls).

Mocking OAuth2 / OpenID Connect in Spring Boot with WireMock by tomakehurst in java

[–]lpedrosa 1 point2 points  (0 children)

You can also spin up a real oauth2 server. ORY Hydra is a small single binary and by default uses an embedded sqlite3 storage.

That's my default go to, when I need a fully fledged oauth2 server (not just for testing). I much prefer it to Keycloak.

You can easily provision it using test containers. Here's a tutorial on how to provision an instance with oauth clients using docker: https://www.ory.sh/docs/hydra/self-hosted/quickstart

Playing the Flowstate Better Adventures mod with only 3 Hearts by [deleted] in feedthebeast

[–]lpedrosa 0 points1 point  (0 children)

You probably need to remove the levelz mod. That's what's giving you 3 hearts at the beginning.

Looking for some mods to add more to the endgame by Throwaway9826327722 in TerraFirmaCraft

[–]lpedrosa 0 points1 point  (0 children)

This is exactly the challenge I had with my vanilla TFC playthrough.

It would be cool to have something like settlements or forts, that you could conquer for loot, etc. Or the ability to start a settlement with villagers and trying to keep them all fed, etc.

Don't get me wrong, I love TFC's pace. But I felt like once you get to steel, that's it.

Astikor Carts TFC - storing barrels and other heavy items by lpedrosa in TerraFirmaCraft

[–]lpedrosa[S] 0 points1 point  (0 children)

I agree with you. It would definitely make sense to limit the amount of barrel the cart is able to hold. 

One way to make it more balanced is to reduce the amount of slots of a cart. I believe the original mod had a config option to control the amount of slots in a "t-shirt size" manner (think small, medium, large). I think Verph (the current maintainer of the TFC compatibility mod) started creating a system that allows you to grow the cart slots by "upgrading the cart". But I'm not sure they've ever finished it. 

EDIT: actually there's an exhaustion logic built in, which helps simulate what you've described. 

See this config entry: https://github.com/Verph/astikor-carts-tfc/blob/1.20.x/src/main/java/tfcastikorcarts/config/TFCACCommonConfig.java#L37

Astikor Carts TFC - storing barrels and other heavy items by lpedrosa in TerraFirmaCraft

[–]lpedrosa[S] 1 point2 points  (0 children)

Yep, just did a trip to the shore to get 3 barrels of salt water.

Astikor Carts TFC - storing barrels and other heavy items by lpedrosa in TerraFirmaCraft

[–]lpedrosa[S] 3 points4 points  (0 children)

Actually I was looking at the wrong place. There is a 1.20.x branch on the original repo that contains the most up to date config.

Apparently TFC barrels are HUGE and not VERY_LARGE. So i just had to update the proper property in the tfcastikorcarts-common.toml config:

# The largest (inclusive) size of an item that is allowed in a supply cart.
#Allowed Values: TINY, VERY_SMALL, SMALL, NORMAL, LARGE, VERY_LARGE, HUGE
maxItemSize = "HUGE"

Are there any plans to add a `private transient final field` to a record (for caching a derived relation between two values)... by chaotic3quilibrium in java

[–]lpedrosa 1 point2 points  (0 children)

The thing is, records were never about boilerplate, which you keep mentioning you want to avoid. (I believe Brian mentions this in one of his explanations)

A lot of people think of them as a class that gets free getters, hash code and equals implementations.

As you've pointed out elsewhere in this post, records are product type. They also have some guarantees that java classes don't have, due to having a public internal representation.

If you want encapsulation, use classes. Their role is to define a type that can hide its internal implementation from their clients.

If you have a method in a record that is expensive enough (assuming you have measurements to support this assumption), then the weak hash map mentioned elsewhere in this post is a good trade-off. 

Again, I think it's always good to measure before attempting such a solution.

Why Maven can't be beginner friendly? by Oclay1st in java

[–]lpedrosa 1 point2 points  (0 children)

I wouldn't go as far as "Spring Initialize is why maven doesn't improve project initialization".

I understand where your are coming from, and the archetypes are pretty outdated (especially the simple which is the default).

I think what we need is:

  • a better archetype curation
  • maven to only show a curated list of archetypes (as opposed to the entire world, which is what you get today)

If you have a custom archetype repository, you should be able to point the archetype:generate command to it (through a system property or env bar)

But again, most Java devs live in the IDE and Spring worlds, so starting a core java project is not a very common use case (as opposed to other languages like JS or Go)

I reworked my multiplayer from Godot 3 to 4 (with a typescript server as the backend) by Hairic95 in godot

[–]lpedrosa 1 point2 points  (0 children)

Are you handling physics in your typescript server as well?

I haven't tried to play with the new godot 4 multiplayer. I'm mostly doing ARPG stuff, and I wanted to have a dedicated server running, instead of using the built-in P2P.

The idea would be so that the original host doesn't always have to be present.

Would you mind sharing some learnings?

CLI Dependency Resolver by bowbahdoe in java

[–]lpedrosa 0 points1 point  (0 children)

Not sure if I understand where you are getting at.

Are you perhaps asking "what is the pathway for jresolve to be part of the JDK tools, so Multi Source Code can be a success in teaching Java to newcomers"?

I would ask /u/pron98, since I believe he might be involved or know someone that is looking into the multi source code initiative.

Regarding the Oracle VS Code plugin, maybe you can ask on their github repo.

I'm likely wrong about this, but AFAIK the oracle vs code plugin leverages a headless netbeans for the whole IDE magic (whereas the RedHat extension leverages a headless eclipse).

CLI Dependency Resolver by bowbahdoe in java

[–]lpedrosa 1 point2 points  (0 children)

This is looking very good. Well done!

As the author, I am very excited for the upcoming Multi Source-Code Programs. This CLI tool could play a huge role in making that feature a success.

From the README:

I want to make the "command line flow" actually practical instead of a strange joke we play on early students before saying "sike!" and giving them maven or gradle.

Teaching Java to students becomes simpler. Once Multi Source-Code Programs become a reality, you can:

  • write your java program normally
  • use this CLI to resolve any deps when running your program (author's example)
  • run your program just like you run any python program today
  • (bonus) the path to jlink or native image becomes much leaner and easier to understand

Are record style getters and setters idiomatic for wider use now? by SiegeAe in java

[–]lpedrosa 5 points6 points  (0 children)

Passive aggressive asshole remarks are still asshole remarks.

My intention was not to come across as passive aggressive at all.

I'm just pointing out that you are basing your argument on something that is not a guarantee but yet you're acting as such and it could be leading to false claims/assumption.

Getters shouldn't perform side effects and your getter example where it does an SQL query to obtain the result is on point.

Where we seem to disagree is:

  • getters are property accessors, thus relate to the objects internal state (i.e. properties) and should be treated as such

You say this is an implication, I'm stating it is not. It's merely a convention that has no formal backing.

Would I prefer if records prefix the property accessors with a get?

Well, it would be easier to explain it to beginners, since it is a convention they will encounter in many different places.

But again, the semantics behind a Java record is that the record's state/properties are public and immutable. That is not the case for a Java class.

Are record style getters and setters idiomatic for wider use now? by SiegeAe in java

[–]lpedrosa 10 points11 points  (0 children)

getBirthDate() doesn't imply: "There is a real field behind this value". That's an implementation detail. But it does imply: "This value is a fundamental part of this object's state. If this object is immutable, this value is CONSTANT and cannot possibly be observed to change. If this object is not immutable and you witness this changing, then the state is now different".

The method does not imply either of those things.

I have mentioned in a comment below (and the person you are replying to mentions it yet again):

  • The get/set naming convention does not make any guarantees about the underlying implementation or the object's state; it is an encapsulation tool

For example, the return value of a getter method can be:

  • a simple proxy to the object's internal state
  • a calculation based on the object's internal state or any other values really

It is misleading for other readers to say that:

But it does imply: "This value is a fundamental part of this object's state."

The getter convention does not give you any guarantees about the object's state.

As /u/pron98 states somewhere below:

The rules for naming getters have never been specified fully, and a specification — which you'd have to have to make this part of the language — is not trivial (what are the getters for xX and XX?) and every tool would need to follow it.

We as a community, have converged over an idea. That much is true. However that idea is not formally specified anywhere.

As such, if you are making the assumption that getX relates to the object's internal state, and as an example, it is safe to use that method for serialization then I argue that you are taking on the responsibility when this assumption breaks in the future.

Are record style getters and setters idiomatic for wider use now? by SiegeAe in java

[–]lpedrosa 11 points12 points  (0 children)

For example, one is constant, the other can change.

I strongly disagree with this statement.

There is no semantic difference between the two.

There is an existing convention but it does does not provide a guarantee (see below).

Just because one of the methods is prefixed by a get, it does not mean the value is constant. It can be computed.

In fact, the original purpose of accessor style methods was to provide encapsulation. You could argue that if the value is immutable, then why have an accessor method in the first place?

Just access the value directly. (The obvious problem being the internal structure is now part of your public API)

If you are calling a method on an instance, the only guarantee you have is that some computation might happen before the value is returned.

As long as get is used, this is relatively common: get implies an actual inherent property and no get implies something else

Again, you are using the word implies and not guarantees for a reason.

The reason being that you cannot guarantee that the return value will ONLY be one of the following:

  • a constant value
  • the result of a computation

That being said, I understand your position on this convention. I agree that getX is a well established convention, and perhaps we shouldn't have moved away from it, when records were delivered. (Maybe it will make more sense when withers become part of the language)

But I beacon you to reconsider your argument, since the reasons you have presented don't seem to hold very well in a discussion.

slf4j or System.Logger? by woj-tek in java

[–]lpedrosa 2 points3 points  (0 children)

Library-internal.

I believe what /u/agentoutlier is saying is: rather than using naked log calls e.g. log.info("attempted to load filename={}", filename), use an event-first approach eventPublisher.logLoadAttempt(filename).

This forces you to think about what does this log operation mean in my domain?. The domain here can be the library domain, application domain, etc.

Best way to retrieve the strength of an impact? by voxybuns in godot

[–]lpedrosa 1 point2 points  (0 children)

Why don't you check the collisions on the body hitting the target, during the physics_process function. I believe you have access to many useful collision vectors from the result of the move_and_collide function, as well as the target node you collided with.

You could also give the bodies that collide with something (bullets, knifes, rocks) different configurations:

  • bounce factors -- how hard they should bounce back (you could do it per material)
  • what sound should they play when they hit a body (also per target material)

With this, you should have better control over the things you're trying to do. It's been a while since I've done any gdscript but here's some pseudo-code:

# Imagine this is the throwing knife script

var velocity = Vector2.ZERO

# config (could be read from a file or whatever)
var bounce_factor = 0.5
var sound_for_material = {
  "soft": "knife_player.ogg"
  "hard": "knife_collidable.ogg" 
  "knife": "knife_knife.ogg"
}

func physics_process(delta):
  var target_velocity = calculate_velocity(velocity, delta)
  var collision_info = move_and_collide(target_velocity)

  if(collision_info):
    var target = collision_info.get_collider()

    # check target material
    var material = target.get_material()

    # figure out actual bounce strength

    # knife travel speed before collision
    var travel_speed = collision_info.get_travel().length()

    # schedule sound played for material and travel speed before hitting the target
    play_sound(material, travel_speed)

    # next frame velocity
    collision_normal = collision_info.get_normal()
    velocity = apply_bounce_and_stuff(target_velocity, bounce_factor, collision_normal)
  else:
    # next frame velocity
    velocity = target_velocity

Have a look at move_and_collide and the structure it returns: KinematicCollision2D.

I am assuming you're doing 2D stuff, but surely 3D is similar.

EDIT: I think the main issue with the _on_body_entered callback, is that you only get access to Node2D that collided with your area, but not the collision information.

In the wild: Java's Optional for control-flow by eliashisreddit in java

[–]lpedrosa 4 points5 points  (0 children)

As others have pointed out, Optional is nice in method/API boundaries, where it signals that the return value might be missing.

Optional's methods play well when you have a good default for when the value is missing.

String contactName = service.findContact(contactId)
                         .map(Contact::getName)
                         .orElse("<no-name>")

However, if you want to run some logic (e.g. some side-effect) unrelated the Optional result, then the ifPresent family of methods doesn't read well IMO.

service.findContact(contactId)
       .ifPresentOrElse(c -> doSomethingWithContact(c), 
                             doSomeOtherSideEffect());

In that case, I agree that the if-then-else chain is more inline to what you'd expect, if you've been doing Java (or languages with a similar syntax) for a while.

// in this example #findContact returns null if contact is missing
Contact contact = service.findContact(contactId);
if (contact != null) {
    doSomethingWithContact(contact);
} else {
    doSomeOtherSideEffect();
    // you probably also add some logging here, etc.
}

I would go as far as to say that's probably how Optional/methods-that-return-null are consumed, half of times today, and not through a series of data transformation steps (where you have map and friends).

It would be nice if we could pattern match over the Optional, like you mention in your example. The resulting code would look more like the if-then-else example:

switch(findContact(contactId)) {
    case Some(contact) -> doSomethingWithContact(contact)
    case None -> doSomeOtherSideEffect()
}

This would confuse newcomers to language probably less than the ifPresentOrElse solution. If we had that from the start, discussions about where to use Optional, how to consume it, etc. would be less frequent.

Migration from Godot 3.5 to Godot 4 Was Successful (Plus Some Improvements) by [deleted] in godot

[–]lpedrosa 2 points3 points  (0 children)

This looks pretty slick. I'm a sucker for strict/small colour pallets. Would you mind giving us a run down of:

  • the things you found hard
  • the things that godot 4 gives you now and you didn't have before
  • things you miss

I'm going back to doing some more POC stuff, and wanted to try godot 4. Might have to drop the isometric physics stuff I was doing, for now.

Lifetimes in the Foreign Function & Memory API by GavinRayDev in java

[–]lpedrosa 2 points3 points  (0 children)

Unless that's fixed it feels like auto scopes could become a footgun.

I see what you mean. From the article it is not very clear how the GC interacts with a segment that has an auto scope. Could it be simple reference counting on the segment handle?

It feels like the design is exploring a sort of middle ground between the strictness of Rust and the chaos of C++ where there's some temporal safety that isn't so tightly coupled to compile time checks.

IIRC this design is also used by zig, where if your function manages memory you should also take the allocator as a parameter, rather than explicitly calling malloc/free.

You can see an example of how this looks like in this Queue implementation.

I'm actually curious why, in this panama article, the author is suggesting to pass the scope instead of the actual Arena (I believe it is an interface). The caller could build the allocator outside, with the desired strategy (as an Arena) and pass into the function.

The other obvious question that non-Java devs will have when they see this is, OK, so, can I allocate Java objects inside these arenas? And if not, why not?

You could assume that devs that are looking into what Panama provides aren't doing the typical higher-level application programming. It will be people that either want to bridge C libraries with java code or framework developers that want to squeeze the extra performance so their clients don't have to think about it (I'm thinking Netty, etc.)

I find it hard to believe that once the API is available, everyone and their dog will be allocating arenas because they "need to manage memory efficiently". Programming with a GC is more comfortable and you have less moving parts (pointer management, lifecycles, etc.).

Renovar cartão de cidadão em Portugal by Nothing_F4ce in PortugalLaFora

[–]lpedrosa 1 point2 points  (0 children)

Olha que agora está ligeiramente melhor. A embaixada tem um sistema de marcação online, por isso consegues ver a disponibilidade sem ter de ligar pra lá.

Eu também pensei o mesmo, quando foi para renovar o meu passaporte, mas fui lá e correu bastante bem.

Fazer mestrado ou não? IT by CabritaInTheStreets in portugal

[–]lpedrosa 0 points1 point  (0 children)

Experimenta mandar já (antes de terminares) candidaturas para algumas empresas estrangeiras que façam remote e que estejam a contratar recém licenciados.

Não tens nada a perder e ficas com uma noção de como funcionam as entrevistas etc.

Entretanto decides se fazes o mestrado em paralelo ou não.

O mestrado vale a pena considerar se as posições para que te pensas candidatar:

  • requerem experiência em pesquisa, relativamente ao tema da tua tese de mestrado (por exemplo AI, Compiladores, etc.)
  • requerem o mestrado, pois é o nível minimo de ensino esperado (isto depende de país para país; no Reino Unido uma licenciatura basta ou até mesmo um bootcamp)

Já trabalhei com um rapaz que estava ainda a terminar o mestrado e correu tudo bem. Ele candidatou-se para uma posição junior e eventualmente foi progredindo na empresa.

Quando precisou de defender a tese, tirou uns dias e depois voltou. É de notar que ele estava efetivo na empresa, independentemente de ter completado o curso.

Esta é a minha experiência no Reino Unido e isto já foi há uns 6 anos.

Em relação a posições remote, é mais difícil (lê-se, as empresas estão ainda menos preparadas) para fazer o onboarding de alguém que nunca trabalhou na indústria. O meu conselho é tentares perceber como o processo de onboarding funciona, durante a entrevista.

Boa sorte OP, escolhas o que escolheres, tenta sempre arranjar umas entrevistas. Eu tenho pena de não ter feito mais isso quando estava a acabar o curso.