r/java • u/trecatorsirabdator • Apr 14 '23
What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?
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:
Make it work
Make it right
Make it fast (- Kent Beck)
in that order.
21
u/mateusbandeiraa Apr 14 '23
The problem with this is that sometimes you make it work in such a bad way that in order to make it right you need to throw it all out and start over. You can’t make it right if you didn’t start with the right architecture in mind.
I think this advice is good for experienced developers, since they have a good general idea of what’s the right thing do to most of the time, but for new developers this advice can lead them to build poorly designed code that’s unfixable unless you rewrite everything from the start.
43
u/Gwaptiva Apr 14 '23
Premature optimization considered evil.
So many times you've been worrying about something being performant to find out that it's not ever used, or only used once a day and nobody cares, because they're waiting for something completely different to finish, that you never suspected.
61
u/nutrecht Apr 14 '23
Not a comment 'against' what you're saying so please don't read it as such but:
Premature optimization considered evil.
I dislike how this has been taken out of context to be used as an argument against optimization.
The original quote from Hoare is:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
What they are referring to as 'optimizations' are things like counting CPU cycles for instructions before you even know certain code paths are 'hot'.
I've seen developers use this in response for example where people told them that doing 2 SQL statements (select and insert or update) was not a good idea when you can just do one (upsert).
So, what people often read is:
Premature optimization considered evil.
While the intention of Hoare was:
Premature optimization considered evil.
This sentence has become as much of a dogma as "composition over inheritance" has become.
→ More replies (2)4
u/temculpaeu Apr 14 '23
I have never seen someone saying that optimization is evil, I have seen quite a bit of folks trying to push for "optimizations" without reason besides "it will make it faster", even your quote is out of context, the author says that you should optimize when either it is already affecting the performance or it is KNOWN that you will have a bottleneck, the issue of the premature part is that bottlenecks are hard to predict, of course, unless you are doing something dumb (ie: n^2 operations)
Sure there are cases where you can clean the code and make things faster at the same time, these are fine the issues are with "clever" more complex code that *might* saves nanoseconds in a endpoint that has queries that takes 100s of miliseconds to run
→ More replies (1)11
u/wildjokers Apr 14 '23
I really hate that this “premature optimization considered evil” is frequently quoted without any understanding of what they meant. These days programmers use it as an excuse to be lazy. If you want to know what was meant by that quote read this ACM article:
17
u/bootstrapf7 Apr 14 '23
I am not sure how true this that trope is, it seems that most code is designed for "test" size amounts of data. Not for the data seen in the real world.
It feels like this advice of premature optimisation is considered evil has lead to code so slow it's functionally a problem.
→ More replies (3)13
u/oparisy Apr 14 '23
I'd tend to agree. You shouldn't obsess over performance, but making a conscious choice of the appropriate data structure (good time complexity of typical operations you'll use on it) goes a long way wrt future proofing your code, and limiting the need to optimize it later.
8
u/i_post_things Apr 14 '23
I love optimizing code, but unless it's critical, it can be difficult to do it in a way that doesn't sacrifice readability or maintainability. Sometimes you run the numbers and realize it's cheaper just to spend an extra $100 a month to scale wider with more servers than spend days or weeks optimizing. Especially when you add in the opportunity cost of not delivering actual business value in those weeks spent.
1
u/UnGauchoCualquiera Apr 16 '23
I agree with you, the point being is you should strive to optimize for developer time first or more generally for productivity first as that is the usual bottleneck.
11
u/Ketroc21 Apr 14 '23 edited Apr 14 '23
How often is there opportunity or motivation to go back and "make it right" when it already "works"... especially in an environment where devs aren't in charge? In my experience, if poor design decisions are made early on, they will persist forever.
I think #1 and #2 must be done together. Too much emphasis on either is a bad thing.
6
u/rlcute Apr 14 '23
"Make it right" is part of the development. It's the sexy refactoring you get to do after you've solved the problems. It's not pushed to prod before it's actually ready, ie solid architecture and test coverage.
8
u/nutrecht Apr 14 '23
"What are you going to spend time on? It works? Chop chop! On to your next story!" - Many managers
Not saying I disagree with you at all, but a lot of devs stop at step 1 because there is very little incentive for them to also do step 2 and 3. I see 'bad' code a LOT more than people being paralysed on what design pattern to use. I see a lot more developers jumping into writing code too soon than I see devs waiting to write code for too long.
4
1
u/UnGauchoCualquiera Apr 16 '23
They are either consciously prioritizing time to market or simply bad managers and it's usually a symptom of a bad organization. Still truth is as much as it pains developers to deliever bad code it's usually not the one taking the call.
You can always contribute to OSS if you'd rather take the time to deliver quality software.
4
Apr 14 '23 edited Apr 14 '23
applauds furiously...Definitely going to print this one and put it up in the office!
Edit: Printed and on my desk :))
11
u/adamjwise1 Apr 14 '23
You're almost guaranteed to introduce security issues at step 1. The real risk is that in practice you'll likely not get to step 2, so there will be bugs, maintainability issues and general technical debt.
I've seen too many decent projects that had to be entirely abandoned due to unreadable code written hastily.
So yeah, don't prematurely optimize, don't over engineer, don't write a new framework for a solved problem, etc, etc ... But otherwise take the above with a grain of salt.
6
u/hippydipster Apr 14 '23
I like how basically every single time programming quality comes up, the same basic threads appear.
Do X-Y-Z!
But what if people only do X??? That's terrible advice.
or,
Don't do X!
But then people will do Y and Y is bad! That's terrible advice!!
Every time.
2
u/alex_tracer Apr 16 '23
Now imagine that you started to do a project this way and got a system that 1000x slower than what you need to have. And for a fast system you need a completely different design. And this issue happened only because "make it fast" was a separate task with lowest priority in the list. Who will be responsible for the lost time?
1
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.
21
u/alwaysoverneverunder Apr 14 '23
Which is why for me the so called "verbosity" of Java isn't that much of an issue because for me it is more readable after a long time not seeing my own code.
7
u/blacksuit Apr 15 '23
The dumbest guy on your team needs to be able to fix it when it breaks.
1
u/fgzklunk Apr 15 '23
This was me when I was working on a Scala project. I gave up on Scala because of the way it is written, not the language itself, I now work almost exclusively with Java.
26
u/moxyte Apr 14 '23
This is a pronounced issue with lambdas. I’ve fixed abhorrently “elegant” lambdas simply by rewriting them as boring ol’ loops.
33
u/hippydipster Apr 14 '23
Lambdas vs loops is mostly an issue of what a developer is used to, as opposed to one or the other being objectively easier to read or harder to read.
The main exception to that I'd say is when the lambdas are doing a bunch of side effects, and in that case, it's not something they're well suited for, IMO.
13
u/moxyte Apr 14 '23
Lambdas in lambdas passing values to each other. Never seen one that is bugfree and easily understandable.
28
u/stao123 Apr 14 '23
That is like the complete opposite of my experience with writing and reading lambdas. You cant make mistakes as easy like with for loops.if you use one liner lambdas with method references they are way easier to read and understand. I have to admit there is a steep learning curve. Dont give up and get more experience
5
u/plokman Apr 14 '23
Children can understand for loops, and even write pseudocode easily for many problems. I've never seen one whip out a chain of function applications.
→ More replies (1)55
1
u/danikov Apr 14 '23
I never use anonymous lamdas, making them into functions and then using a function reference feels so much more expressive, even if it’s more verbose, but as they say… make your code self-describing.
Also, I’m really adverse to calculus-style variables. About the only one I’ll tolerate is i in a for loop, but I’ll always be looking for a better iterator and named variable where possible.
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.
29
Apr 14 '23
java.util.Optional
23
u/RockleyBob Apr 15 '23
java.util.Optional
Yes, but please don't use
Optionalfor null checks alone. I see a ton of code at work like this:Optional<Customer> optionalCustomer = Optional.ofNullable(customerClient.findCustomer(customerId)); if (optionalCustomer.isPresent()) { return optionalCustomer.get(); } else { return customerClient.createCustomer(); }Doing this is worse than just doing a simple null check, because it's more verbose and you're new'ing up a wrapper object just to immediately unwrap it again. The
Optionalclass has a whole declarative api that you can safely code against, transforming the value within the pipeline and providing default values:return Optional.ofNullable(customerClient.findCustomer(customerId)) .orElseGet(() -> customerClient.createCustomer());4
u/dpash Apr 15 '23
I wouldn't create an Optional just for avoiding a null check. Ideally the findCustomer method would return an Optional rather than a null.
8
u/RockleyBob Apr 15 '23 edited Apr 15 '23
Yes, it's a really blatant example, but just to belabor the point, I'd go so far as to say if you're calling Optional.get() at all, you're probably doing it wrong.
You probably don't ever want to be referencing an Optional object in your calling method. In other words, you shouldn't really ever need to instantiate a variable of type Optional:
Optional<List<Customer>> optCustomers = // Stop here! Don't do this! customerApi.getAllCustomersByState("CA"); List<String> customerIds = new ArrayList(); if (optCustomers.isPresent()) { List<Customer> custList = optCustomers.get(); for (Customer cust : custList) { customerIds.add(cust.getId()); } } return customerIds;Not only is this forcing the declarative Optional api into an imperative pattern, it also ignores the declarative capabilities of the Collection api. Instead:
return customerApi.getAllCustomersByState("CA") // KEEP GOING! .orElse(Collections.emptyList()) .stream() .map(Customer::getId) .collect(Collectors.toList());There's almost always a way to do what you want to the returned value within the Optional api declaratively using operators, then work with the result. Not saying you don't already know all this, but elaborating for the sake of discussion.
→ More replies (2)→ More replies (1)3
6
u/Paulus_cz Apr 14 '23
Can someone explain to me why Optional is considered bad practice as method parameter? I mean, sure, ideally you should not use it this way, but sometimes, something just can be null, but different methods may want to handle it differently and Optional declared that possibility clearly and forces you to handle the case (or ignore it at your own peril).
Point is, I like Optional. It has legitimate uses as parameter.23
u/blackkkmamba Apr 14 '23
Optional as a parameter doesn't stop you from passing null. That's why it's a bad practice.
15
→ More replies (1)11
u/neckbeardfedoras Apr 14 '23
An Optional return parameter doesn't stop a third party lib from returning null either. Maybe they want to drive you crazy? 😁
8
Apr 14 '23 edited Apr 14 '23
i think optional as parameter is fine. You can also define another method which is not taking that param.
void startSystem(Display display, Optional<Config> optConfig)
or
startSystem(Display display) startSystem(Display display, Config config)
or
startSystemDefault(Display display) startSystem(Display display, Config config)
i think all 3 are fine
→ More replies (11)3
u/wildjokers Apr 14 '23
Because you can pass
nullin for the value of the Optional parameter. You have gained nothing.→ More replies (1)7
u/Fruloops Apr 14 '23
Not at all. You've gained hours of potential frustration. That should not be underestimated.
→ More replies (2)1
u/wildjokers Apr 14 '23
Write code that doesn't allow for or tolerate nulls
Not sure I agree with the "tolerate nulls" part of that. You should always be flexible with what you accept. In Java nulls can happen so in reality you need to be ready for them.
16
u/halfanothersdozen Apr 14 '23
I disagree. There are several tools to deal with this.
Javadoc indicating valid parameters
NotNull annotatons on parameters
Assertions on method parameters
Optionals
If someone calls a method that very clearly does not accept nulls with null values and exceptions happen that is on them.
→ More replies (2)7
u/AlmennDulnefni Apr 14 '23
Nullity is something of a lost cause, but you should strive to make invalid states unrepresentable in the first place and, failing that, should be explicit about your preconditions and fail ASAP if they're violated. Being excessively lenient in what you accept as input is a good way to build up a dodgy pile of inconsistent garbage.
→ More replies (11)
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
26
u/oparisy Apr 14 '23
With respect to your second point: yes! Immutability is a great feature to aim for whenever possible. In that regard, the "final" keyword helps tremendously.
13
u/mdaniel Apr 14 '23
Now that Java has
varI'd enjoy it if they'd includevalas thefinal varversion because littering the code withfinalis visually noisy if one chooses to strive for single assignment fromI can also imagine that they won't ever include it since it's just syntactic sugar for that two keyword form, plus the fact that they differ only by one letter
→ More replies (10)11
u/HecknChonker Apr 14 '23
kotlin has entered the chat.
8
u/mdaniel Apr 14 '23
Yeah, I specifically left that word out of my comment because of the downvote brigade the other mention of it got, but it for sure was the reason why I started to miss the succinctness of
valwhen I had to go back to JavaI also happen to personally like the "immutable by default" of ... the other language ... but team dynamics are what they are, so we have to use what the team agrees upon
15
Apr 14 '23
builder pattern
12
u/Admirable-Avocado888 Apr 14 '23
To clarify. I don't consider the builder pattern to violate the second principle. A builder is a helper that sets up the state for another object. Given a builder, to create the actual object requires only one constructor call.
What I'm saying is that if you are writing a class that is its own builder then you are writing code that is hard to reason with, because you are not deliberately separating the building step from the "doing step".
3
u/Trizzelnova Apr 14 '23
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.
Oh god thank you! I'm currently fighting a just crusade in my project because people didn't wirte constructors. Instead they either do it incrementally or worse: static factory methods INSIDE the class which they create an object of... I'm either missing the genious of this because >I< am to stupid or this is the most stupid thing I've seen in 15+ years.
39
u/Escaped_Escapement Apr 14 '23
Static factories are good when you need multiple ways to construct an object and overloading the constructor becomes too confusing or impossible. It is a legit pattern.
15
u/wildjokers Apr 14 '23
According to Bloch’s Effective Java you should prefer static factory methods over constructors. Your colleagues are doing it correctly.
2
u/CartmansEvilTwin Apr 15 '23
Honestly, for 80% of classes, it doesn't really matter.
I see the point for more complex classes, but the wide range between POJO/Record and "that one central class that handles 90% of the business" has a lot of cases where the constructor simply initializes a handful of members (any many don't even do that).
3
u/okreddit545 Apr 14 '23
any constructor is effectively also a “static factory method inside the class.” it just doesn’t permit any name other than
new.1
u/simoncox Apr 15 '23
In the absence of named parameters, static builders allow more expressive means of passing parameters at construction.
For example, if a constructor takes more than a handful of ints, then it's easy to confuse what each one is for. Default/min/max pool sizes, initial delay, repeat interval, timeout delay, etc.
Also, when the construction of an object may need to involve more complex logic it may be better to pass a builder around to store state needed to construct that object.
I'd still prefer a constructor generally, but there are occasions when a builder can be useful.
1
u/moxyte Apr 14 '23
Local classes tend to cause issues with hot reloading, other than that I have no beef with those
1
u/TenYearsOfLurking Apr 18 '23
an object should be able to preserve all its invariants and prevent invalid state.
if a setter is able to provide that functionality I see no problems. if not, 90% of the time properties grouped together into (immutable) components and offering a setter for that component solves the problem as well.
so I do not think setters are bad per se, but I get your point, they are commonly misused
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.
7
Apr 15 '23
[removed] — view removed comment
3
u/CartmansEvilTwin Apr 15 '23
Not only government. Plenty of corporations (large and small) only switch to the next Java versions if they can't even pay anyone to maintain it any longer.
15
u/_INTER_ Apr 14 '23
Java enums have properties that make them useful in many situations. E.g. not many know that values() or EnumSet keep the declaration order. So you could build named strategies with built-in fallback.
15
u/wildjokers Apr 14 '23
enum's are so powerful and so underused. My coworkers still create interfaces with String constants in them like it is still the dark ages of pre-java 1.5.
1
u/hsoj48 Apr 18 '23
I do this! Help me understand how enums are a better fit for constants please.
2
u/wildjokers Apr 19 '23
Type safety.
Google something like “enums vs magic strings” and you will find many discussions and resources on the topic.
1
Apr 15 '23
A bit of trivia but each call of
values()creates a new array.1
u/Radi-kale Apr 15 '23
Arrays are mutable: you can overwrite their elements. So it could lead to some very nasty bugs if it were the same array every time.
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.
3
u/sik0fewl Apr 15 '23
Concrete rules have no place in software development.
Follow the rules, understand the rules, break the rules. But only in that order.
32
u/Gleethos Apr 14 '23
Make as much field variables as possible final, and if you can't, make sure that the mutability is grouped and encapsulated properly!
Define boundaries between your groups of classes in the form of nice and robust APIs which reflect long term architectural concepts. Then write as much unit tests as possible against the stable APIs.
Always return Optional instead of null on public methods, especially for the APIs with the most usage (which should be the APIs you test against). Null safe APIs are extremely important in large Systems!!!!
Make sure you can instantiate your application with all of it's business logic completely without frontend (using MVVM, MVC). Otherwise you will not be able to write very useful unit tests...
9
5
u/Admirable-Avocado888 Apr 14 '23
These are good rules. Testability is so underrated. My experience is that not following 4. can slow down development to the point where you are almost coding blindly
6
Apr 14 '23
Always return Optional instead of null on public methods,
To be honest, I don't understand the "hype" around Optional.
In my opinion, it merely replacing a NullPointerException with an OptionalNotPresent exception at runtime for sloppy programmers.
It gives a tad better documentation about the fact that something might be null, but that's it. I personally can't see any other advantage.
11
u/Gleethos Apr 14 '23
I agree that sloppy programmers will fail writing null safe code either way, I did so when I started coding and first encountered Optional! I always simply called 'get()' all the time and did not really think further than that...
But as a non sloppy programmer with years of experience it is extremely useful to have Optional as return value because the compiler will actually remind you that you have not received the object you wanted! You cannot call 'getAddress().getPost()' because Optional does not have a 'getPost()' method.
This immediately triggers an important realisation: "Hey the thing I want to get might not be there! Why is that and what do I do in that case?"
This is something you ofte don't think about when calling a method which may return null instead of the thing you actually want...
...and don't get me started on documentation. I have seen plenty of production code and you wish devs would write even some bare minimum explanation of why a method even exists. So don't expect it to tell you that it returns null...
16
u/balrok Apr 14 '23
it also gives you:
- information that the return can be Optional (contrary to "null" which cannot be implied from the method signature)- nice methods on top of Optional: "orElse", "orElseThrow", "ifPresent", "map"
In my opinion somebody has to be way more sloppy to just directly call Optional.get without isPresent, than trying to access a null-value
6
u/mdaniel Apr 14 '23
which cannot be implied from the method signature
This may be considered pedantry but
@Nonnulland its@Nullablefriend exist, and I believe Spring has a set of such annos that tolerate being applied to thepackageif one wishes to make more global promisesObviously it won't help those who avoid using an intelligent IDE but is also not a runtime burden like Optional
→ More replies (9)4
u/john16384 Apr 14 '23
I would say, if you religiously document your methods in regards to how they handle
null, thatOptionalis not strictly needed. Unfortunately, getting developers to document their methods is often harder to achieve then telling them to useOptional.
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.
11
u/wildjokers Apr 14 '23
JRebel has evil licensing terms so I have been boycotting them for years. Besides I never got it work correctly with Spring. The application context has to be reloaded and as far as I can tell JRebel doesn’t do that. If I remember correctly they claim it works for Spring but it never worked for me. The only time it is was handy was when I did a lot of work with Swing.
13
u/thatbigblackblack Apr 14 '23
I believe that with intellij subscription, you get this feature too. But coming from languages and others IDE and languages, it bothers me so bad that I have to pay for this feature
24
u/MattiDragon Apr 14 '23
You can do hotswapping with the community edition of intellij. Just run in debug mode and hit build. For proper hotswapping you need to use a JDK with DCEVM support, like the one included with intellij and add
-XX:+AllowEnhancedClassRedefinitionto your vm args. It's a bit unstable in my setup (minecraft mods), but still really useful. Without DCEVM you can only change method bodies.6
u/mvthakar Apr 14 '23 edited Apr 15 '23
i also dabble in fabric modding. jbrsdk with dcevm has been working great for me. there are very few cases where it actually fails to reload classes.
Edit: grammar
→ More replies (1)4
u/thatbigblackblack Apr 14 '23
Oh, thanks for the trick ! A more detailed step by step if anyone else wants to implement it https://www.sentiatechblog.com/using-dcevm-hotswap-agent-in-java-development
5
Apr 14 '23
Eclipse does that for me out of the box
13
u/dmigowski Apr 14 '23 edited Apr 14 '23
No, it doesn't. Java itself has these features on paper, but in practice to have to restart anyway very often. JRebel does it right.
It even reloads Hibernate Configs, Property Files for Resources, etc.
EDIT: I just learned about -XX:+AllowEnhancedClassRedefinition, which was not there in JDK8. Should give it a try.
4
Apr 14 '23
Ok i thought its an eclipse feature. sorry. is it the hot swap feature of the jvm?
5
u/dmigowski Apr 14 '23
No, Hotswap is the shit that does work very limited, just function bodies IMHO. JRebel replaces functions, classes, variables, even static variables, and has integration with many frameworks that receive automatic reloading capabilities if the configs are edited at Runtime. It does everything except changing the parent class hierarchy (the only limit I know), but you don't do that very often. Very powerful tool!
Also TIL that Jetstream seems to have a similar solution integrated in Idea, but I don't know how these solutions compare.
3
u/neckbeardfedoras Apr 14 '23
I think the problem is hot swap doesn't support certain changes. I thought things like method signatures, new classes, or some range of things weren't supported. JRebel dun care.
JRebel has been around forever. I'm kind of surprised but not really because java is still popular and it's been that way also forever 😂
1
u/Majestic-Extension94 Apr 16 '23
JRebel
They have the most aggressive marketing ppl
1
u/dmigowski Apr 16 '23
Most IT guys lack these skills, which is why many IT companies go down after a short time.
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
1
1
1
u/_harro_ Apr 15 '23
Or extract the content of the if block to another method...
2
u/ImTalkingGibberish Apr 15 '23
Yes but then it gets harder to follow, with another navigation. Depends on the size of each scenario, if most scenarios are big, then yes it’s a better approach. If only the main scenario is big then I’d rather have multiple small early return small scenarios and keep everything in one method. Also easier to test.
2
u/_harro_ Apr 15 '23
Even then I usually split it up. Having a clear method name for that extracted logic will greatly improve readability too then.
Separating "flow" statement (like if, else,.. ) from your business logic can make your code easier to navigate.
1
u/wildjokers Apr 17 '23
I hate early return. I think having a single return per method is easier to follow, it is way too easy to miss an early return while you are reading the code.
On the rare occasion where not using early return results in crazy levels of nesting I will early return, but that almost never happens and I generally just have a single return.
2
u/Lisoph Apr 18 '23 edited Apr 18 '23
No way, Jose! Early return is a must, IMO. Human brains love lists, and early returns are essentially a checklist.
it is way too easy to miss an early return while you are reading the code.
I think it's just as easy to miss what conditions you're under, when working with highly nested code. Our codebase at work is very nested and it's a nightmare every time to keep track of things.
Early return objectively makes the code simpler, because it removes the ability "to go back" in state. You have either returned or you haven't, and you can't change that anymore, whereas with nested style, you can always flow out of the condition back to where you were before.
The exception where nesting is cleaner is when the depth is 1 and when the length is short too. Bascially, if it reads like a short and simple sentence, I prefer nesting. Otherwise, early return.
1
u/ImTalkingGibberish Apr 17 '23
I don’t disagree in theory but in practice people don’t use finals for return objects and keep resetting the returning variable across multiple ifs.
So general speaking, early returns are easier to read.
However in long methods I agree with you, but then also using a final variable as the returning variable is best.
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.
2
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”)
3
u/oua-de-crab Apr 18 '23
This one I'll never forget.
At my first job I needed to add a hotfix for one of our customers, so I had to call on a persistent state to check some flag that was unique to this tenant, and it returned a string.
The hotfix worked fine for the affected customer, but NPE crashed for all the others, because that method returned null.
When I saw the 20 support tickets within 10 minutes with "REPORTING MODULE BAD" I knew I fucked up.
Nobody was mad though, the senior dev just chuckled afterwards, and I've never male this mistake again.
6
2
u/__konrad Apr 14 '23
If a String can be null it's fine (e.g. System.getenv), otherwise it may silently hide all your null-String bugs...
10
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.
5
u/Arthurpmrs Apr 14 '23
Like what? (Genuine question, this aways bugs me)
Let's say I have a date column on my db. Some rows are null. To what should I transform them after querying the data? Like, 0000-00-00?
On the same note, if a method could return null, I must check for null upon function call. But if I don't use null, I may have to use exceptions. Wouldn't I need to catch them as well? Is it better to check for exceptions?
17
u/ParfaitMassive9169 Apr 14 '23
Convert to optional. This way you communicate that this may be missing and force the calling code to make a decision on how to deal with it
→ More replies (4)3
u/moxyte Apr 14 '23
Like ParfaitMassive said, or more generically you make sure nothing escapes method as null. Especially straightforward if you get a litany of strings you make sure none of the strings ending up in list to be returned are nulls.
→ More replies (1)3
u/rzwitserloot Apr 14 '23
A sentinel that has the semantic behaviour you desire. Sometimes such a sentinel is not available. Often
nullis right on such a case, but crucially that is because the desired behaviour is an exception.If some code goes: is date X between A and B? Do you want the code to eval to false (then use 0000-01-01), or throw because the question shouldn't have been asked? Then
null.Sloppy null is where you e.g. have a null stringref and treat it the same as you would an empty String.
If a method could return null then check for that right away, don't let the
nulllinger (not in a local var and definitely not in a field). When writing APIs, try to avoid the need. Example: map.getOrDefault. Or in dB models, don't write:
SELECT birthDate FROM ....
if (bd!= null && bd.isAfter(now minusYears (18)) ...Instead SELECT the expression directly with DATEDIFF in the SQL.
→ More replies (1)2
Apr 14 '23
You got null from database? Immediately turn it into something else before passing it further into the system.
So how do you represent a
NULLvalue from an integer column in the database in Java?→ More replies (1)4
u/john16384 Apr 14 '23
There is
OptionalInt. I myself however find returningIntegerinstead ofintsufficient to know whether or not something may benull.1
u/tistalone Apr 14 '23
Reminds me of the pattern to separate the data transfer objects from the internal domain objects used for the business/application logic.
1
u/rzwitserloot Apr 14 '23 edited Apr 14 '23
Yup. In fact, if you see
if (x == null || x.isEmpty()), unless it is cleaning up outside input (say,xis from a jackson-json created object), is bad.Whatever made
xevidently messed up: empty and null are (apparently, given that you wrote thatif) semantically equivalent, so why didn't it just return an empty object then? Fix the creating code.This is a far better solution than tossing the hard-to-compose and backwards incompatible
Optionaleverywhere.Also, to make that easy, write APIs that take this into account. An example:
java.util.Map'sgetOrDefault.
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:
Document your public and protected methods, and specify exactly what they do (not how) given various inputs and what they return as result, for example:
/**
* Sets the slot at the given index to the given element.
*
* @param instance a reference to the instance where the array is stored, cannot be {@code null}
* @param index an index to set, cannot be negative, or greater than or equal to the number of occupied slots
* @param element an element to set, can be {@code null}
* @returns the element that was previously at the given index, can be {@code null} if the element at the given index was {@code null}
* @throws NullPointerException when the given instance was {@code null}
* @throws IndexOutOfBoundsException when the given index was out of range
*/
E set(I instance, int index, E element);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
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;
4
u/HwanZike Apr 14 '23
If i need a value from deep nested object structure
This is a pretty bad smell usually!
1
Apr 14 '23 edited Apr 14 '23
Your classes have only strings and primitive fields? i imagine having data structures limited to only classes with primitive fields. i see 10000 maps trying to make simple relation between objects becauses classes are limited to have no nesting and cant be used for complex data structures anymore.
3
u/HwanZike Apr 14 '23
I don't see how the field data types are important here. It's a matter of encapsulation and coupling. See:
→ More replies (2)1
u/pronuntiator Apr 14 '23
My current project makes extensive use of this pattern. I hated it at first, but it grew on me. When encapsulated in a method it is pretty clean.
1
1
→ More replies (6)1
u/oua-de-crab Apr 18 '23
To anyone who's opposed to this approach: maybe you are lucky to have good structured entities and don't see the benefits of this approach.
I have to deal with some pretty nasty legacy crap, and this is absolutely better then having deeply nested ifs.
Say you have a maybe nullanle cistomer and want to
.getAddress().getZipCode().getNumber(). Mind you this is a pretty shallow example, and oftentimes the field names are in the good old enterprise style of being 20 chars long, those ifs get pretty unreadable pretty fast.
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.
5
u/BinaryRockStar Apr 14 '23
I am similarly all-in on Maven and understand it fairly deeply. Having said that, I really wonder why the designers didn't opt for XML attributes over elements in some cases. Having
<dependency groupId="org.apache.logging.log4j" artifactId="log4j-core" version="2.20.0" />Would be so much cleaner than what we have now. XML style formatting ends up with an element per line so each dependency takes up 4-5 lines (version is often specified in a parent
dependencyManagementsection) and makes even a relatively simple POM many pages long.As with everything Maven I assume this was extremely well argued out from both sides and the best option was picked. It would be interesting to know the reasoning though.
And as an IntelliJ user I suggest the "Laconic POM" plugin which folds Maven dependencies onto a single line and alleviates the issue entirely.
1
u/joequin Apr 14 '23
I also am not a huge fan of how verbose maven files are, but if you’re using an IDE, then it’s mostly a non issue. I can see how maven would be a problem for Java programmers who don’t use an IDE though. If any of those exist.
→ More replies (1)1
u/woj-tek Apr 20 '23
They are going to change that in maven 4 / pom-version-5 AFAIR (https://cwiki.apache.org/confluence/display/MAVEN/POM+Model+Version+5.0.0#POMModelVersion5.0.0-ElementsvsAttributes):
DECISION: The 5.0.0 POM will use XML attributes for data that cannot have child data. At a minimum the groupId/artifactId/platformId/version/classifier/type information of project/parent/dependencies/plugins/extensions will be defined using attributes.
→ More replies (2)5
u/tistalone Apr 14 '23
Man you describe Gradle so well. They give you ONE example of a happy path and if you have anything slightly different, it's stack overflow sleuthing and hiring private investigators to figure out what is happening under the hood to achieve the original objective.
0
u/wildjokers Apr 14 '23
What a strange rant against Gradle. Idiomatic gradle is declarative and just like maven you use plugins.
This build.gradle file will take a very long ways (just fill in your dependencies):
plugins { id 'application' } repositories { mavenCentral() } dependencies { } application { mainClass = 'com.example.App' }4
u/tistalone Apr 14 '23
Gradle works fine for simple/straightforward apps.
OTOH, If you want submodules that do specific builds differently, you are on your own. If you want to publish gradle plugins, you have to use Gradle's own plugin that is pretty poorly documented -- you are on your own for the trial errors. Got Kotlin AND Java files? You gotta do something different! Also, you need to figure out what other people did to solve this issue because Gradle's documentation doesn't provide a straightforward answer to us users!
3
u/wildjokers Apr 14 '23
For a mixed kotlin and java project all I needed to do was add the kotlin jvm plugin and application plugin:
plugins { id 'application' id "org.jetbrains.kotlin.jvm" version "1.3.72" }Nothing else was needed and it just works.
because Gradle's documentation doesn't provide a straightforward answer to us users!
This information is in the Gradle documentation:
https://docs.gradle.org/current/samples/sample_building_kotlin_applications.html
→ More replies (3)4
u/joequin Apr 14 '23 edited Apr 14 '23
In practice, that’s rarely sufficient for real production applications. If it was, then Gradle would be great.
→ More replies (2)2
u/wildjokers Apr 14 '23
I have several apps where the build.gradle isn't much more than that. Including some JavaFX apps that produce a platform specific executable with a bundled runtime. That build.gradle is about 25 lines long.
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
7
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.
→ More replies (10)
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/wildjokers Apr 14 '23
Refactor ruthlessly. Never be afraid to make it better.
Too much hassle getting refactors through code review. Why put myself through the stress?
This is why I sometimes think code review makes code quality worse.
3
u/john16384 Apr 14 '23
You may want to raise such points with your team. A team that isn't willing to improve for the good of the product is not worth working for.
And if not doing it already, keep refactors small, with multiple commits working to a goal, and don't mix in functional changes. This makes reviews much easier.
1
u/i8Nails4Breakfast Apr 15 '23
I struggle with this on my team as well. Reviewing new code is easier than reviewing refactoring
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.
1
u/lumpynose Apr 23 '23
An excellent companion, which unfortunately is out of print, is Kent Beck's Implementation Patterns.
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
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
Apr 14 '23
static methods make testing hard or impossible because of lack of inheritance and polymorphism
5
u/neckbeardfedoras Apr 14 '23
It certainly doesn't make testing impossible. You can even test the static method itself. It can't reference member vars and is pretty isolated. You can't override it, but if there are use cases for overriding it other than because you want to with a test, it shouldn't be static in the first place.
If the method does complex things that needs to be faked or stubbed, it's immediately not going to be static if it's my code base.
→ More replies (5)1
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. USE this, super, and "qualify" static stuff in this exact manner as well. Thank you.
This part is too personal and specific. Nobody needs to agree...:
m_ and p_ are good naming conventions since they show only scope, but if you'd [use them with camelCase instead of PascalCase at least in Java, and] make sure you're using these only for scope, I'd be happy.
3
u/wildjokers Apr 14 '23
this. I hate it when people let you want to remember all class fields and methods and conflicting local variable's names. UGH. USE this, super, and "qualify" static stuff in this exact manner as well. Thank you.
Place I am at now doesn't allow to use
this.for self calls and when I first started here (about 5 years ago) it was a huge adjustment to not use them because for the first 16 yrs of my career I was at a place that required it.I still miss it because I think it improves readability, it makes method calls consistent and let's me know exactly where the method is when I am reading the code.
1
u/Brahvim Apr 15 '23
Very sad. What about
m_?2
u/wildjokers Apr 15 '23
m_ and p_ are abominations :-) They are both hard to type and hard to read.
→ More replies (6)
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
1
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:
1
u/Anton-Kuranov Apr 17 '23
Can't code without Lombok.
Use @Nullable instead of Optional if not required explicitly.
Don't use checked exceptions, specially for resource faults (I/O). In most cases the calling code has no responsibility to handle them.
Java could run perfectly without Spring (or any other framework). To implement a simple DI you do not need them at all.
Constructor injection everywhere. Your classes should not able to be constructed with missing dependencies and should not rely to your framework.
Every line of code is not a value but a debt: one should maintain it later. So be reasonably critical with what you're doing and why.
1
u/felvid Apr 28 '23
It's good to see more people are supporting manual DI nowadays. It seems to be gaining some relevance.
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
-9
u/stuie382 Apr 14 '23
Lombok
→ More replies (7)1
u/jevring Apr 14 '23
But only for things bean stuff. Don't use @Delegate and other black magic stuff.
3
u/hippydipster Apr 14 '23
It all violates the principle of avoiding complexity. For massive complexity, you get irrelevant reduction in boilerplate.
146
u/erjiin Apr 14 '23 edited Apr 14 '23
Use a database deployment tool like Liquibase or Flyway. Invaluable (and not Unvaluable :/).