r/java • u/javinpaul • Mar 23 '25
10 Coding Habits for Experienced Java Developers
https://javarevisited.substack.com/p/level-up-your-java-10-coding-habits[removed] — view removed post
5
u/RadiantAbility8854 Mar 23 '25
Idk, I feel like these are more of a newbie's habits. And even some of your "proper" examples don't feel like proper enough.
Don't use iterators directly unless you can't otherwise. Instead, use for(T item: iterable) or even streams to traverse a collection.
The closing streams example feels incomplete. But you can pretty much use try-with-resources instead of manually closing streams.
Not sure anyone should be implementing the clone method unless they are required by a library or something.
The same goes for using wait. You should be using java.util.concurrent instead.
2
u/Spare-Plum Mar 23 '25
Even if you wanted to do it the old fashioned way with object locks, the code given is very bad and will end up with deadlocks. Here's the "good" example they give
synchronized(queue) { while(queue.isFull()) { queue.wait() } }There's a dumb loop is hogging the lock resource and nothing else will be able to acquire it!
Here's a better way to do it
while(queue.isFull()) { queue.wait(); synchronized(queue) { if(queue.isFull()) continue; // otherwise do your queue operations } }Now you're only locking the queue for where it's relevant to use the queue resource instead of in an infinite loop
1
u/dc757848 Mar 23 '25
As I recall you are required to hold the lock when you call wait, and wait will release the lock for the duration of the wait.
I would expect this improvement to result in an IllegalMonitorStateException.
3
u/user_of_the_week Mar 23 '25
I hope the code rabbit thing you’re advertising here isn’t stuck in the past like most of these „habits“. Also, the last one just states a problem but the solution is missing, I guess you were going for a try-with-resources.
3
7
u/-vest- Mar 23 '25
I do usually have two questions:
Why do people write such articles again and again?
Why do people like reading them AGAIN AND AGAIN?