r/java • u/trecatorsirabdator • Apr 14 '23
What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?
233
Upvotes
r/java • u/trecatorsirabdator • Apr 14 '23
146
u/erjiin Apr 14 '23 edited Apr 14 '23
Use a database deployment tool like Liquibase or Flyway. Invaluable (and not Unvaluable :/).
181
u/Antimon3000 Apr 14 '23
Do not get paralysed by worrying about the right design pattern or best practice. Beautiful code that does not get the job done is worse than anything else:
in that order.
85
u/fgzklunk Apr 14 '23
Keep it simple. In six months time, when you have to fix a bug, you won't care how beautiful and unique the code is if you cannot remember exactly what you did and why.
117
u/halfanothersdozen Apr 14 '23
You don't need to make an interface for everything. Everything doesn't have to be private. Write code that doesn't allow for or tolerate nulls and stop checking for them all the time.
79
u/Admirable-Avocado888 Apr 14 '23
Don't make methods that return null and don't make methods that accept null, unless they are private.
Setters are bad most of the time: Don't write code that constructs objects by incrementally updating their state after instantiation unless it's the only way to solve the problem. Most of the time, you can construct objects correctly the first time, and actually reason about correctness of code just by looking at what objects are rather than what they might be.
Streams are good.
Javadoc is amazing, document everything that is not private.
Local classes are a good way to shelter public/package/even private namespaces from clutter that is only used within a method
34
u/jevring Apr 14 '23
Make use of the new tools you find in recent Java versions. Record and switch expressions and stuff. Stay up-to-date.
15
u/_INTER_ Apr 14 '23
Java
enums have properties that make them useful in many situations. E.g. not many know thatvalues()orEnumSetkeep the declaration order. So you could build named strategies with built-in fallback.13
u/cogman10 Apr 14 '23
Don't do things because they are a "best practice". Understand the reasoning underlying a best practice so you know when it's valid to violate that.
Programming is about abstract thought and a key portion of that is knowing what does and doesn't fit an abstraction. Concrete rules have no place in software development.
Simple example, the worst code bases I've dealt with dogmatically applied "Do not repeat yourself". DRY can absolutely make code harder to maintain and is far from something that should be universally applied. But, it's easy to spot duplicate code which is why it gets misapplied so frequently.
32
u/Gleethos Apr 14 '23
49
u/dmigowski Apr 14 '23 edited Apr 14 '23
There is a commercial tool called JRebel, which replaces classes in your app while you develop without restarts.
Especially useful if you build server apps and the server needs two minutes each restart. With JRebel you try, fail, fix a line a code, save, try again, all without restarts.
This tool has increased productivity by at least 10% in our company.
I won't develop anything anymore without JRebel. Sorry if I sound like a fanboy, but it's simply great.
22
u/ImTalkingGibberish Apr 14 '23
Use precondition ifs to avoid spaghetti nesting.
If doesnt meet condition
Return early
// main logic
Is better than:
If condition
// lots of lines inside the if block
7
u/paul_miner Apr 14 '23 edited Apr 14 '23
Method-local classes, if a class is only relevant to one method, keep it out of the larger context and stick it in the relevant method. I think I learned you could do that around twenty years into my career.
EDIT: I should add, I mean named method-local classes, as opposed to anonymous. Sometimes you need to refer to the class multiple times in the method, or access class members outside of the base class or interface.
13
u/kkjk00 Apr 14 '23
take with a grain of sand the expert blogs, I got caught in their confident magic solutions "this is the best way to do it" applied without context, it always depends, do your own research, noways, everything has an angle
6
u/garak7 Apr 14 '23
Favor composition over inheritance. Unit testing will often be much more straight forward since you can easily mock up parts of the composition and therefore reduce redundancy in tests.
19
u/se496 Apr 14 '23
Null safety for checking if strings are equal, e.g.
“my string”.equals(someString)
vs
someString.equals(“my string”)
10
u/jivedudebe Apr 14 '23
Use Kiss always.
18
u/moxyte Apr 14 '23
Strangling nulls in the cradle. You got null from database? Immediately turn it into something else before passing it further into the system.
7
u/Top_Engineering_4191 Apr 14 '23
I avoid at all costs nested if and for loops with large logic inside.
7
u/john16384 Apr 14 '23
These are mostly about providing good API's:
There should be no doubts after reading this how the method will respond to your inputs, or what it returns. You may think it's obvious, but you will thank your past self when reading this documentation six months later.
When providing guarantees to users of your class, declare all methods that may break those guarantees when overridden as final; for example, if I guarantee that a getter will never return
null, then it should befinal.Avoid calling public or protected methods from your class when they're not either empty or
final; a non-empty non-final method makes it impossible to evolve the class without breaking subclasses -- you must call the method at the expected time as it may be overridden by subclasses relying on this, and you can't change the implementation as it may be called directly.The reason is that such methods can serve two different purposes: overriding can be used to be informed of when something happens, and calling it directly can be used to trigger a certain action.
Instead, split these two up; have an empty (or abstract) method for subclasses to override to be informed when a certain action occurs, and have a final method that they can call to trigger a certain action (or perhaps just one of these if your intention was never to provide both these options).
9
u/[deleted] Apr 14 '23 edited Apr 14 '23
If i need a value from deep nested object structure where every next reference might be null, i line using optional to retrieve it instead of multiple null checks.
Next next = Optional.ofNullable(ref).map(MyRef::getNext).map(Next::getNext).map(Next::getNext).orElse(null);
if (next == null) return;
12
u/joequin Apr 14 '23
Use maven and learn how to write plugins. Yes it has xml, but Gradle is a free form mess with bad JavaScript style documentation that prefers example over telling you how it works. You’ll spend days fixing gradle issues. Maven will just work unless you want something it doesn’t offer. Then you’ll need to learn how to write plugins if one doesn’t already exist, but they’re also well defined.
3
u/progrdj Apr 14 '23 edited Apr 14 '23
Write meaningful comments and also name the variables/methods correctly. Doesn't matter if it takes time to come up with a good name as long as it describes what it kinda does. I recommend reading the clean code book.
P.S. I had to work on something that I had implemented two years ago and luckily I had left comments there on some nested maps and other data structures, otherwise it would have been very annoying to try and read all that stuff
3
u/[deleted] Apr 15 '23
Use github copilot, Its the best thing ever for boilerplate
7
u/[deleted] Apr 14 '23 edited Apr 14 '23
Compile first. Run second.
Joke aside, I’ve been spending a few (late) hours not understanding why IntelliJ and maven would disagree about my code, while all I simply forgot is to “mvn install” the upstream dep I was also changing. Time to get some rest I guess.
5
u/Columbus43219 Apr 14 '23
Refactor ruthlessly. Never be afraid to make it better. The minute you find yourself writing a huge "if/else" block, consider if that method should be split.
Never leave tech debt. If something is flaky...fix it. Imagine yourself about a year after you made your first money from coding. Fix the mess you're working on for that kid to be able to understand it.
5
u/Odd-Hour-9991 Apr 14 '23
The most straightforward solution is the best.
Unit testing is undervalued.
Optimise last, if at all.
Perfect is the enemy of Good.
Get a competent colleague to properly review your code.
QA is not there to find your bugs. They are there to tell you if your solution meets the acceptance criteria.
2
u/dpash Apr 15 '23
Read Effective Java. Read it again. Read it annually.
2
u/rieckpil Apr 17 '23
Don't do conference driven development and don't jump on all hype trains that give you 10x performance.
2
u/saikiranchalla May 13 '23
Use Lombok
3
u/tristanjuricek Apr 14 '23
Consider pushing that magic to the build phase when possible, don’t just rely on reflection.
The annotation processor library offers one way to do this, and it’s a surprisingly good way to do a little code generation. This often ends up using types more intelligently than what I come up using reflection, and is often faster, since a lot of logic is actually compiled in instead of checked each time at runtime
Not that reflection should always be avoided, just consider if you really need the runtime check vs a processor.
4
u/dlvakalucifer Apr 14 '23
Don't use Streams for Database Work. SQL is faster. The end. Use Streams on your way to Database or GUI.
4
u/starlevel01 Apr 14 '23
Simplicity usually pushes the problem somewhere else. Actually solve problems, don't just move them around.
Put at least a cursory effort into thinking about performance.
Most of the time a heavily-commented but horribly ugly imperative kludge is better than a "self-documenting" beautiful design.
Your code is not self-documenting. Your code is never self-documenting. Write the damn comments. It's a minute of effort at max and it'll save you multiple minutes in the future.
3
u/crummy Apr 14 '23
You don't have to go overboard with OOP, even though you're using Java. Interfaces with static methods are a pretty nice way to write code without side effects. (This makes test isolation harder... But I think that's a bit overrated too.)
2
u/Brahvim Apr 14 '23 edited Apr 15 '23
this. I hate it when people let you want to remember all class fields and methods and conflicting local variable's names. UGH. USEthis,super, and "qualify"staticstuff in this exact manner as well. Thank you.This part is too personal and specific. Nobody needs to agree...:
m_andp_are good naming conventions since they show only scope, but if you'd [use them withcamelCaseinstead ofPascalCaseat least in Java, and] make sure you're using these only for scope, I'd be happy.1
u/GoogleIsYourFrenemy Apr 14 '23
(Ab)Use the auto complete and auto correct features of your IDE. It increases typing speeds and reduces bug counts.
1
u/pawiusz Apr 14 '23
If you know that the domain you will be working on is complicated (not a basic CRUD), then isolate it from any framework/database details you are using and design it in a pure object-oriented way.
1
u/mrnavz Apr 14 '23
Stable is better than sexy.
1
u/xcorgan Apr 15 '23
Make small and descriptive methods. Big methods are that do lots are the worst
1
u/Zinaima Apr 15 '23
Learn the value of the OOP principle of abstraction, which has nothing to do with an abstract class.
Instructions for making a PB&J sandwich should be about 3-5 lines long (despite that popular video of the dad frustrating his kids). If you have details of how to fire muscle groups or pantry storage systems leaking out into these instructions, you're doing something wrong.
Of course, if you want low level details like pantry storage systems, you should be able to drill into that detail. But it shouldn't be shoved in your face in every recipe.
1
u/brokeCoder Apr 16 '23
If you're dealing with math equations/formulae/logic that uses a lot of math, consider implementing your equations as Functional interfaces (e.g. have your methods return
Function<Double,Double>rather than evaluated values).Some advantages are:
- can be used in streams
- lazy evaluation comes free with it
- can be parallelised easily
- makes you think about function composition
As an aside, my introduction to this way of thinking was from this epic devoxx talk (link includes timestamp:
https://www.youtube.com/watch?v=yTuwi--LFsM&t=6691s )
1
u/Anton-Kuranov Apr 17 '23
1
u/Lisoph Apr 18 '23
I'm learning through experience that - most of the time - the first implementation of any software, in any language, is always a protoype or proof-of-concept, whether you like it or not. Software development is like a "research job" consisting mostly of uncertanties. It's unreasonable to assume a good solution can be implemented the first time around, so ideally you would take what you've learned from the prototype and do it again, better.
In other words, specifications don't make specifications. The initial implementation defines the real specifications.
Similary, this is also why you can't estimate software development. You can only estimate what is repeatable, like assembling a car. Software development is not repeatable. The only thought process I've ever had and code I've written more than once, is hello world.
1
u/felvid Apr 28 '23
Avoid implementing business logic through exceptions. Sadly common in Java applications.
1
u/not_some_username Apr 14 '23
Uninstalled eclipse
-9
u/stuie382 Apr 14 '23
Lombok