r/java • u/ruskeeblue • Apr 18 '17
30 Java Programming Tips and Best Practices
http://www.edumobile.org/java/30-java-programming-tips-and-best-practices/18
u/__konrad Apr 18 '17
30 Java 1.4 Programming Tips
6
u/dododge Apr 19 '17
Yeah when it mentioned
VectorandHashtableas typical collections at the end I double-checked the date on it.
7
Apr 18 '17
These are interesting, but premature optimisation is a problem for quite a lot of these examples. In the vast majority of cases, readability and maintainability > minor performance gains. CPU is cheap; developers are not.
For example, in 6:
public boolean oddOrNot(int num) {
return (num & 1) != 0;
}Performant, yes. But sticking bitwise operators in your code is a surefire way to lose clarity.
5
u/ebrythil Apr 18 '17
Call the method isOddNumber, make it static and put it in util are more relevant than bitwise blackmagic, as long as that is in a well named function and not littered over the code
4
u/dpash Apr 18 '17
You can easily solve the problem with their code by inverting the condition.
public boolean oddOrNot(int num) { return num % 2 != 0; }0
u/hex6ng Apr 19 '17
For a one-liner function such as this, the name of the function makes it clear what it does. Using bitwise or not doesn't take anything away.
2
5
u/JustMy42Cents Apr 18 '17
Some examples don't even compile, most do not follow clean code principles or do not use generics. Yeah, sure, "best practices". This one is my favorite:
public class getLocationName {
return (null==cityName ? "": cityName);
}3
u/dpash Apr 18 '17 edited Apr 18 '17
It would be far better to just annotate the function as
@Nullableand let your IDE warn you if you don't check in the calling code. An alternative is to return anOptionaland force the caller to check, but that's possible an overkill for this example of a simple String.But, yeah, not even going to compile.
Also, for #14, it's probably more readable to use something like Guava's
Preconditions.checkNotNull()method. Also annotate the parameter with@NotNulltoo. And don't forget the javadocs :)2
3
u/dododge Apr 19 '17
Static analyzers such as checkstyle, pmd, and error-prone will catch a lot of the stuff being warned about, such as #1 and #2. They'll also scream bloody murder about the raw List in #3.
The wording in #13 is very odd. I assume it's just trying to say that while ^ is used for exponentiation in some other languages, it means something completely unrelated in Java and will not work to compute powers.
18: In Java 8, the NIO Files.list(Path) is probably a better solution for listing a directory. If nothing else, it gives you Path objects that know what directory they belong to instead of just the bare filenames.
19: This should use try-with-resources so it doesn't have to manually close the streams. Also under NIO you'd use Files.newInputStream(Path) to open the streams.
21: DO NOT USE REGEXES TO VALIDATE EMAIL ADDRESSES. Don't even do this in some little throwaway example program, because the folks you're teaching might get the idea that this is a reasonable thing to do in a real program. Just at a glance those regexes will reject plenty of valid gmail addresses. Also the website has amusingly clobbered the sample strings as an anti-spam measure, so if you bother to run it it won't validate any of them anyway.
29: There's no struggle here, the answer is don't use FileWriter. FileWriter will always use the default encoding which means things like environment variables can randomly screw up your I/O. The "error-prone" analyzer will complain about this and many other uses of the default encoding, such as that other call to new OutputStreamWriter that doesn't specify an encoding.
2
u/AnEmortalKid Apr 19 '17
Wow.... The null pointer exception code where he ends up throwing a npe.... Wtf. Most of these were poorly written and shitty.
1
u/jbu311 Apr 19 '17
2. Use Strings carefully
Regarding concat, Not a problem in java 8 anymore i thought?
1
u/big_dick_bridges Apr 19 '17
I haven't heard anything along those lines regarding the "+" operator to do concat. I believe Java 8 did add a StringJoiner class, but that just uses a StringBuilder under the hood
1
u/dpash Apr 19 '17
There's no issue with using + with Strings in a non-loop situation in any version of Java.
From the javadoc:
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification
In a loop it's better to use your own StringBuilder to save object creation.
0
Apr 18 '17
[deleted]
1
u/Kernel_Internal Apr 19 '17
Apparently so is mywot.com https://safeweb.norton.com/reviews?url=mywot.com
I clicked your link and immediately got prompted to download an updated version of chrome...
0
u/blobjim Apr 19 '17
what? web of trust is a completely safe site.
2
u/Kernel_Internal Apr 19 '17
I don't know if you're being sarcastic and I don't know how reliable the search results are, but a quick search for "is mywot.com safe" yields the following links with postings that seem to challenge your assertion:
https://productforums.google.com/forum/#!topic/websearch/JjgmtMoF2UI
https://www.quora.com/Is-the-WOT-Web-of-Trust-extension-reliable
To be fair some of the negative stuff seems to me to have a conspiratorial tone, which is always suspect.
2
u/blobjim Apr 19 '17
RIP. I just went to the site on my desktop computer and it did the same chrome auto-download thing. Guess I'll be uninstalling. Such a shame since it was a good tool, but like many products like it, the massive amount of power the developers have with such a large user base often leads to corruption. Of course, it is hard to tell if any of the claims are valid like you said, other than the chrome download scam.
24
u/dpash Apr 18 '17
#1 talks about returning and empty
Collection, but instead gives aStringexample. Also it usesclasskeyword instead of the return type.#3 uses a non-generic collection and capitalises the member, which probably clashes with the class name.
#4 ArrayList is fast because it uses an array underneath. The only time it's slow is when the underlying array needs to grow, in which case it creates a new copy that's 1.5* times larger than the old array. If you know the maximum size ahead of time, you can specify this at the beginning. I'd say that 99% of the time, an ArrayList is better than an array. The code generated is often more readable, and an ArrayList is more featureful.
You also appear to be missing some words in this section.
* It's actually
(oldSize * 3) / 2 + 1#10
-XX::PermSizewas removed in Java 8.0Half of these aren't tips and best practices, they're just random snippets of code.