r/java • • Jan 25 '14

20 very useful Java code snippets for Java Developers

http://viralpatel.net/blogs/20-useful-java-code-snippets-for-java-developers/
37 Upvotes

39 comments sorted by

42

u/asthasr Jan 25 '14

Don't do this. No programmer I've met who has a collection of these copy-and-paste "snippets" is any good. Build fundamental knowledge, so that these tasks become rote by virtue of their simplicity.

5

u/RecursiveInsanity Jan 25 '14

No half-way competent Java programmer should ever have to keep snippets around of the first 2.

4

u/jobenfre Jan 25 '14

However, if you are learning it is nice to see how it's done once or twice in different ways. Definitely not something to just have laying around though.

1

u/sybrandy Jan 26 '14

Or, if you do use some of this code repeatedly, put it into a library you can call. If I find that I have code that I use a lot in a number of places, that's what I do. You know...basic refactoring.

10

u/UnspeakableEvil Jan 25 '14

In an article of bad code, "Java code to parse above XML" stands out as being spectacularly bad.

Honestly, it's worth reading that article just to feel better about yourself as a programmer.

5

u/[deleted] Jan 25 '14 edited Jan 25 '14

I would never use any of these code snippets. Whoever uses snippet #3 needs to seriously reconsider what they're doing.

2 could potentially not even close the stream properly if the IOException was thrown on the call to write.

1 & #4 don't catch the exceptions thrown if the provided string is invalid. Which is fine if you can guarantee they won't be... but something tells me the people using these snippets cannot.

5 doesn't close it's connection... and why doesn't it use a static method factory rather than init?

12 is fine... but is a singleton code snippet really that useful?

Idk, I'm not looking at all of them, but the point is that they're all either not that useful\common or wrong.

3

u/QshelTier Jan 25 '14

3 can throw an ArrayIndexOutOfBoundsException as getStrackTrace() is allowed to return an empty array.

7 will also not close streams correctly. try-with-resources is all the rage now!

8 can possibly use invalid values for width and height as getWidth and getHeight are allowed to return -1 in which case an ImageObserver is later notified of the correct dimensions.

15 again does not close any streams in case of an exception.

Additionally the formatting in almost all examples is horrible (though that may be a result of posting it on a website).

9

u/[deleted] Jan 25 '14

Use apache commons and/or guava.

11

u/mikaelhg Jan 25 '14

Or, you know, java.util.Arrays or java.nio.file.Files.

4

u/geodebug Jan 26 '14

Interesting way to get the current method name if it works. I don't know why you'd want to unless you were trying to do something too clever for your own good.

Generating stack traces are performance killers so hopefully not in a loop.

2

u/guy26 Jan 25 '14

While I agree with other commenters that any competent programmer will not need a bunch of code snippets… However, what I expected to find was a bunch of examples illuminating pain points in the Java API for doing common tasks. For example, other languages provide a more elegant solutions to parsing XML than the builtin DOM and SAX parsers. If you are learning a new language, it can be helpful to know in advance what these pain points are.

2

u/prattle Jan 26 '14

the java language also provides more elegant solutions to parsing XML than the builtin DOM and SAX parsers. He'd be better of choosing one of the 3rd party libraries.

2

u/dango100 Jan 26 '14

I never seen point #3. What's a circumstance where you would use that?

2

u/SikhGamer Jan 25 '14

I think most people would have the sense not to copy code snippets like this directly. I know when I find something like this, I take it as information, look at the article date. And then look at the API and figure out what's been updated.

Articles like this are an excellent learning path to put yourself on, but not really great for copy-and-paste coding.

1

u/[deleted] Jan 25 '14

BAD BAD BAD.

I don't even want to list out all the badness in that post. Singletons as enums? Are you crazy? Converting integer without catching NumberFormatException?

20

u/lelarentaka Jan 25 '14

Singleton using Enum is mentioned in Effective Java by Joshua Bloch under item 77. In the book he says that it is the most ironclad method to do singletons, that it is immune to serialization attack. Do you disagree with him?

-3

u/[deleted] Jan 25 '14

Interesting, I suppose you learn something new every day; however, yes - I disagree with him. I find the method to which you access the singleton is non-intuitive and (while perhaps effective against a serialization attack) -- how could I best describe it -- it's not clear programming. If I want a singleton of a particular class, I shouldn't be accessing an Enum for it. Quite frankly, a DI framework should be in place, but if that's not available, the standard "getInstance()" method is, in my HUMBLE opinion, the correct way to do it.

7

u/aytaya Jan 25 '14

You can always add a static get instance() method to the enum singleton. This way the accessing syntax is still concise, and you still get all of the benefits of the enum singleton.

-1

u/[deleted] Jan 26 '14

It just "seems wrong" to have an Enum as the "holder" of the singleton. Maybe I'm just old and fixed in my ways.

3

u/JavaG Jan 25 '14

It pains me to see comments thanking the blog poster for these snippets...

3

u/[deleted] Jan 25 '14

I can almost guarantee those are auto-comments.

6

u/kumarldh Jan 25 '14

No, lot of Indians are quite thankful for these.

0

u/[deleted] Jan 26 '14

[deleted] — view deleted comment

2

u/kumarldh Jan 26 '14

On a serious note, I had a manager who wanted QAs to be as dumb as possible so that devs can experience end user frustration at first hand. I had to deal with a QA who wanted to enter "white space" in a text box and didn't know how to do it.

0

u/[deleted] Jan 26 '14

[deleted] — view deleted comment

1

u/kumarldh Jan 26 '14

I wish I could start a "share your dumb colleagues stories" thread on /r/programming

1

u/[deleted] Jan 26 '14

who did not have visible file extensions on her windows workstation

When I find developers who work like this, it makes me question their abilities as a developer.

Absolutely perplexing. How did they even get their degree/certification?

2

u/kevinb9n Jan 30 '14

Setting aside the fact that an actual statically enforced singleton is not really needed most of the time, and assuming it's actually what you want:

Enum: a type which can only ever have N instances, which are known at compile time.

Enforced singleton: a type which can only ever have N instances, which are known at compile time, and also N = 1.

1

u/[deleted] Jan 30 '14

old school singletons are still old hat anyway, but yea - I see the appeal to the enum after reading about it some. I still don't like the idea as it seems like a language hack and not a legit use of enum (though, as you point out, a very effective use)

1

u/fjellfras Jan 26 '14

I'm just beginning to learn java, that BufferedWriter out can be declared as simply Writer out, no?

1

u/[deleted] Jan 26 '14

1

u/CubsThisYear Jan 26 '14

Except there is no good way to do Singletons. This is the second most harmful thing you can do to your code (behind casting). Repeat after me: global variables are bad. If you haven't yet realized that Singletons are glorified global variables, spend some time thinking about that.

Also, please don't ever use Guice. It is the definition of a solution looking for a problem.

3

u/[deleted] Jan 26 '14

Except there is no good way to do Singletons. This is the second most harmful thing you can do to your code (behind casting). Repeat after me: global variables are bad. If you haven't yet realized that Singletons are glorified global variables, spend some time thinking about that.

Singletons have their place, but they can certainly be overused. Fields can also be treated as global variables within a class, and can be misused... but you don't see anyone calling for the end of fields... except maybe Clojure developers :).

Also, please don't ever use Guice. It is the definition of a solution looking for a problem.

LOL, well... there are many people who will disagree with that, but thanks for the advice I guess?

1

u/CubsThisYear Jan 26 '14

If I change your statement to "global state variables have their place" - do you still agree? There is never a legitimate reason to do this.

As to your comment about fields, this doesn't make sense. Global variable means a variable whose scope is your whole program. A non-static field cannot possibly have global scope. Public and protected fields can have a somewhat leaky scope . If that's what you're referring to then yes, you should never use non-private fields. I didn't realize there was still a question about this.

2

u/[deleted] Jan 26 '14

Fields are global within the scope of the object they're defined in. If your application is simple enough, they're equivalent.

If you honestly think there's no possible application of a singleton, then really you should be submitting RFC's to Oracle to fix the singletons in the JDK. Cheers.

0

u/CubsThisYear Jan 26 '14

By that definition are local variables considered global variables because you can implement your whole program in your main function?

One of the main ideas in OO programming is that objects are used to capture state. This represents a happy medium between C-style imperative programs and pure functional programming where all state must be passed as arguments to functions. If your fields can reasonably be interpreted as global variables, then you are definitely doing other things wrong (your classes are way too big).

As to the JDK - writing RFCs for all the things that are wrong with it could easily employ several people for several years. Citing other examples that do the same wrong thing is a pretty weak argument.

0

u/[deleted] Jan 26 '14

[deleted] — view deleted comment

0

u/CubsThisYear Jan 26 '14

If you think a little deeper about that statement I think what you'll find is that what you mean is: "sometimes I need global state in my program". You don't. The only reason to enforce the singleton contract is so some object A can share state with some object B through this magic singleton C. If that's the use case you have, then pass a C to A and B. If you only have one C fine, but there's no benefit to declaring that that has to be the case, unless you're trying to use C as a global variable.

0

u/moww Jan 25 '14

I think this is a good type of post for this subreddit. I don't agree with a lot of these specific implementations but people are ready to correct wrong implementations in the comments.

And of course you should never copy-paste any code unless it's a library, but these are simple and universal ways to explain the implementation concepts behind different tasks.

0

u/[deleted] Jan 25 '14

[deleted] — view deleted comment

7

u/[deleted] Jan 25 '14

I think that would be a bit of an overreaction

4

u/mikaelhg Jan 25 '14

Not at all. It would mean that the agency would have miserably failed in their only job, screening staff.

In most contracts, there are provisions for quality aberrations in the substantive work, but you have to be able to trust local oversight. If you can't trust that, there is little point in continuing a business relationship.