Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips on writing concise and elegant Java [closed]

Please share your tricks for making your Java code concise, still readable.

Coming from Python I'm suffering from "oh, this looks so verbose", it's sometimes hard to fit even in 100-character long lines. I understand Java is a bit more verbose and there's no way around it, but sure there must be small little things that can save some bloat here and there...

like image 985
Pēteris Caune Avatar asked Jan 08 '11 00:01

Pēteris Caune


3 Answers

Read Bob Martin's Clean Code. It's a book full of tips on exactly this subject: writing well-organised, very readable code, with Java as the example language.

like image 110
GaryF Avatar answered Sep 26 '22 13:09

GaryF


The Ternary Operator (shorthand for if-then-else statement) can be handy.

String value = {condition} ? "Was true" : "Was false";
like image 34
jzd Avatar answered Sep 26 '22 13:09

jzd


You can achieve this to some extent on different levels:

  • the language itself: use all features the language offers, e.g. the ternary operator (though some think it's not very readable) and Java7's elvis and diamond operator
  • how you implement: use all the libraries and their features! don't optimize prematurely!
  • the design: use design patterns and the suggestions in Josh Bloch's Effective Java. Precisely document your design decisions by referencing them (e.g. "Visitor" or "Bloch Item 7").
like image 39
DaveFar Avatar answered Sep 25 '22 13:09

DaveFar