5

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...

Pēteris Caune
  • 43,578
  • 6
  • 59
  • 81

3 Answers3

5

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.

GaryF
  • 23,950
  • 10
  • 60
  • 73
  • 2
    +1 for that. Also remember (I don't think this merits an answer of its own) that you can break complicated expressions across lines - unlike python. –  Jan 08 '11 at 02:06
  • Started reading it, it indeed looks like a jumbo-pack of answers to my question. Thanks! – Pēteris Caune Jan 12 '11 at 13:00
  • Old thread but Python expressions can be broken with the '\' character if by 'lines' we mean lines of text. – Erik Reppen Aug 26 '11 at 15:50
  • Please read "Clean Code" with some skepticism. The ideas are great, but I find some examples too dogmatic. E.g. "extracting [methods] till you drop" will make your code less concise and (in my opinion, because of much more indirections and hidden dependencies) less readable. – DaveFar Aug 27 '11 at 23:14
2

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

String value = {condition} ? "Was true" : "Was false";
jzd
  • 23,473
  • 9
  • 54
  • 76
1

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").
DaveFar
  • 7,078
  • 4
  • 50
  • 90