the blog for developers

Go Ahead: Next Generation Java Programming Style

Many companies and developers move away from Java to new languages: Ruby, Python, Groovy, Erlang, Scala. You might be trapped with Java.

Even if you’ve trapped, you can change your programming style and reap some of the benefits of those new languages. In the last 15 years Java programming style has changed significantly:

  1. Final is your new love: More and more Java developers in the teams I’ve worked with, started to use final. Making variables final prevents changing those values. Most often, if you reasign a value, it’s a bug or you should use a new variable. Final prevents bugs and makes code easier to read and understand. Make everything immutable.
    final Foo bar = new Foo();
    

    I’ve written more about this topic in “All variables in Java must be final”.

  2. No setters. Many Java developers automatically – sometimes with the evil help of an IDE – write setters for all fields in their classes. You should not use setters. Think about each setter you want to write, are they really necessary for your fields? Better create new copies of your objects if values change. And try to write code without getters either. Tell, don’t ask tells you more about the concept.
  3. Do not use loops for list operations. Learning from functional languages, looping isn’t the best way to work on collections. Suppose we want to filter a list of persons to those who can drink beer. The loop versions looks like:
    List<Person> beerDrinkers = new ArrayList<Person>();
    for (Person p: persons) {
        if (p.getAge() > 16) {
    	    beerDrinkers.add(p);
        }
    }
    

    This can – even in Java – be rewritten to a more a functional programming style. For example using Google collections filter:

    Predicate<HasAge> canDrinkBeer = new Predicate<HasAge>() {
        public boolean apply(HasAge hasAge) {
            return hasAge.getAge() > 16;
        }
    };
    
    List<Person> beerDrinkers = filter(persons, canDrinkBeer);
    

    As remarked by Dave Jarvis, I should have dropped the getter, and he’s right ;-)

    Predicate canDrinkBeer = new Predicate() {
         public boolean apply(HasAge hasAge) {
             return hasAge.isOlderThan( 16 );
        }
    };
    

    which would lead to better code down the road:

    Predicate canDrinkBeer = new Predicate() {
        public boolean apply( HasAge hasAge, HasAge otherAge ) {
            return hasAge.isOlderThan( otherAge );
        }
    }
    

    The predicate version is slightly larger, but consists of two parts. Each one is easier to understand. While the loop version gets unreadable fast with new requirements, the functional version can easily be combined,

    List beerDrinkers = filter(filter(persons, canDrinkBeer), isMale);
    

    More on this at the Metaphysical Developer.

  4. Use one liners: Write concise code. Java is a noisy language. But don’t make it noiser as it needs to be. Instead of
    public int add(int a, int b)
    {
      int result = a + b;
      return result;
    }
    

    write

    public int add(int a, int b) { return a + b; }
    

    IDEA and possibly other IDEs can keep oneliners formatted as oneliners, if you tell them so.

  5. Use many, many objects with many interfaces. Domain driven design currently makes a big splash. A class should be splitted into many roles, implementing many interfaces. This way the class is reusable.
    public class Person implements Nameable, Hireable, LivesAt {
       ...
    }
    
    public interface Nameable {
      String getName();
    }
    

    Methods should be written to only work on roles, not classes. This way methods can work on more objects. Another benefit is lower coupling.

    public void print(Nameable name) {
      System.out.println(name.getName());
    }
    

    I’ve written more about that in “Never, never, never use String in Java “.

  6. Use Erlang-Style Concurrency. The Java concurrency primitives like locks and synchronized have been proven to be too low level and often to hard to use. There are better ways to write concurrent code. Erlang Style concurrency is one of them – in Java there are many ways to achive this in Java – I’ve written about them here. Newer ones are Akka and Actorom. You can also use Join/Fork or the myriad of data structures in java.util.concurrent.
  7. Use Fluent Interfaces. Fluent interfaces can make your code much more readable and shorter. A very good example is the MapMaker API in Google Collections:
     ConcurrentMap graphs = new MapMaker()
           .concurrencyLevel(32)
           .softKeys()
           .weakValues()
           .expiration(30, TimeUnit.MINUTES)
           .makeComputingMap(
               new Function() {
                 public Graph apply(Key key) {
                   return createExpensiveGraph(key);
                 }
               });
  8. Data Transfer Objects without setters and getters. If you have simple data holders or data transfer objects, don’t write boiler plate code with getters and setters. I know this is heresy in Java, but just use public fields. Instead of

    public class Point {
       private int x;
       private int y;
    
       pulic Point(int x, int y) {
          this.x = x;
          this.y = y;
       }
       public int setX(int newX) {
          x = newX;
       }
       public int getX() {
         return x;
       }
       ...
    }
    ...
    int x = p.getX();
    int y= p.getY();
    

    write

    public class Point {
       public final int x;
       public final int y;
    
       pulic Point(int x, int y) {
          this.x = x;
          this.y = y;
       }
    }
    ...
    int x = p.x;
    int y = p.y;
    

    Refactoring is easy, should you need it. If you do not control all the code and it’s usage, you might need to be more careful though.

This tips lead to better Java code. Try them in your next Java class. What do you think? I’d like to hear how your Java coding style has changed in the last 10 years.

Uodate: Some thoughts to Cedrics thoughts.

As the author of the post, your thoughts are appreciated, some of mine:

“Besides, it’s convenient to be able to mutate object if you want to use pools.”

No setters doesn’t mean you can’t mutate objects, it’s just that plain setters are not object oriented thinking. How about stop() vs. setStop(true);

“I think the first example is more readable than the second one that uses Predicates.”

I think your assumptions are wrong. Loops are procedural code, while Predicates are, encapsulated, reusable, understandable objects. Nothing to do with functional programming, plain OO – it’s only ursurped by functional programming, therefor I refer to it as FP.

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.

1 Comment 1 Comment 129 Tweets 79 Comments 22 Other Comments

Leave a reply.

Comments

Great post. I think you managed to capture a trend that is alive and kicking and helps programmers be productive despite the fact that it is not emphasized (yet) in the text books, university courses, etc.

On top of this list, I think there is also “the next generation patterns/designs”. This list includes topics such as: DSLs, Dependency Injection, and the Properties Pattern (http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html).

Also, this reminds me of Jeff Bay’s “Object Calisthenics” essay (summarized here:
http://binstock.blogspot.com/2008/04/perfecting-oos-small-classes-and-short.html).

Hi Stephan,

I agree with all points but #3 and #4.

More specifically, I agree with #3, only use with care: I’d prefer not to introduce additional dependencies (as Google Collections) if I only have a bunch of (ugly) loops.

Regarding #4, I find one-line methods almost unreadable, and I still prefer to break them.

Other than that, I’d sum up your most important advices as follows: think by interfaces, and always keep concurrency and side-effect-free in mind :)

Cheers,

Sergio B.

Antti Mattila

Is there some reason why example DTO in #8 has non final fields?

>Make everything immutable.

Final does not make your entities immutable.

> Another benefit is lower coupling
So you are for low coupling …

> This way the class is reusable
And reusability …

> Data Transfer Objects without setters and getters

But not for encapsulation?

I think you need to get your software engineering goals straightened out.

Great post, thanks!

stephan

@Mike: No, final does not make everything immutable. You need to have immutable containers and deep immutability.

No, for simple data holder, paramter objects and data transfer objects, encapsulation is not needed and the generated boiler code in Java is doing harm (if you need to look through 3 pages of source just to detect, it does nothing more than hold data). If encapsulation is needed later, refactor (Think DRY and premature optimization)

stephan

@Antti: No, my error, changed, thanks :-)

Tetsuo

What is interesting is that you don’t eat your own dog food. None of the code samples, besides #1 follows rule #1. Maybe because if you fill your declarations with ‘final’ they will become less readable?

It would be great if Java had ‘final’ enabled by default, or if it had a shorter way to declare it.

It would be greatest if the semantics of ‘final’ were complete immutability, not just local variable immutability.

But Java isn’t like that, and forcing things may be useful sometimes, but most of the time they will just add noise to the code.

stephan

@Tetsuo: Noise with final is an issue, I’ve seen that in many code reviews. As you say, I’d wish it was default, and another modifier would make it not-final.

Concerning the examples: There is a difference between example code that does want to show something, and real live code. The balance is fragile, between example code that is too simple and example code that is complex but doesn’t show the things it should show.

Thanks – it’s great to see all these excellent memes in one place. And I appreciate the links!

Sorry, but I do not agree with some of these points:

#1 “final makes code easier to read”: Final is yet another word that has to be processed by the reader. If the point is avoiding bugs, I would recommend FindBugs instead.

#2 You are using Tell Don’t Ask as the holy grail. For me, creating an isOlderThan() method goes against The Simplest Thing that Could Possibly Work and DRY (next: isYoungerThan, isOlderOrEqualsThan, etc). Sure, you can create a Domain method for every possible operation but then your domain classes will not scale too well, and it goes a bit against OO 101.

#3 Closures are one thing, but here you are changing one idiom with another. There is no gain in number of lines of code, readability and (certainly not) performance.

#4 one-liners does not improve readability, but save space, which is not the same thing. Breaking the expected vertical rythm makes code harder to read in most cases.

#5 implies that “many interfaces” == “better reusability”. This depends on the environment (the “forces” if you are talking about patterns), and cannot be applied as a general rule of thumb. I have seen plenty of idiotic interfaces out there, solving problems that proper encapsulation and inheritance would do much better.

#8 only applies if there is nobody else using your code. As soon as your library is used by third parties, refactoring would break things.

As a side comment, injecting the Twitter feeds into the comments section really lowers the S/N ratio of this thread.

#1 through #7 is saying to adopt a more functional style of programming, which I’m a fan of:

http://enfranchisedmind.com/blog/posts/this-is-your-brain-this-is-your-brain-on-ocaml/
http://enfranchisedmind.com/blog/posts/object-burn-is-your-friend/
http://enfranchisedmind.com/blog/posts/some-final-patterns/

Java really screws you with #8. Unlike C# and Groovy, refactoring a public field is *not* trivial in the user code. So you’re pretty much toast if the object is ever going to be maintained moving forward. And if you’re going to making things fragile with malice of foresight, you should probably make the class final, too, just so you don’t take other people down with you. I’d actually suggest implementing #8 by writing that code in Groovy, even if you’re calling it from Java: you’ll get the implicit getters and setters for free, along with the code readability.

Sorry Stephan, but I disagree with most of your suggestions :-)

More detailed response on my blog:

http://beust.com/weblog/archives/000517.html

Ray

The list seems to be a feature set of Scala. You get all of those items in idiomatic Scala as opposed to trying to improve Java via the use of a rather non-idiomatic style.

Scala is Java done correctly. And more.

I liked ‘Final is your new love’, ‘No setters’, and ‘Use many, many objects with many interfaces’. ‘Do not use loops for list operations’ was interesting too – I’ve never used Google collection filter before.

Now, I wouldn’t agree ‘Use one liners’ is that good. I like one liners but still instead of
public int add(int a, int b) { return a + b; }

I would use
public int add(int a, int b)
{
return a + b;
}

Anyway, everybody has their own style.

Cheers,
Jarek

John Smith

Why don’t we leave Java alone and you come up with your own new language you can use yourself. Your list is like saying “Let’s talk in English with all Spanish words”.

Java is fine the way it is. It works and it isn’t hard to teach and use. Add all this stuff and it will be difficult to use.

erich

Hi,

New to your blog, and not trying to flame at all, but just my opinion on one in particular. I have a real aversion to suggestion #4. One-liners are awful things. Why should the number of characters in a method determine its formatting? This opens the door for any number of conditionals just to determine how your whitespace looks. The trivial example of the “add” method works, but this needs a giant EULA-style rulebook to avoid something like this trivial example:

public long fibonacci(int n){return n<=1?n:fibonacci(n-1)+fibonacci(n-2);}

It would be better suited to conditionals that the compiler would optimize anyway. Introduce a 55 char per line convention (unrealistic, but for example), maybe I should just call the method “fib” so it “fits on one line”.

[...] Schmidt started it with his third point: Do not use loops for list operations. Learning from functional languages, [...]

Frank

“Final is your new love” – if you write your software properly then this doesn’t happen. I can’t really think of a single scenario in the last 10 years where this would have helped me find or prevent a bug. It is just additional noise.

“No setters” – debatable. I am a believer in consistency and it should then be either the one or the other. However, I can think of way more scenarios for using setters than not using them. Therefore I think this shouldn’t be done. Generating setters is cheap in the IDE so just use them.

“Do not use loops for list operations” – that is IMHO by far the stupidest suggestion and an even more stupid justification: “easier to understand”. This is just preference and this whole thing on closures and predicates is nice but it looks like the hammer-nail pattern. Way too much noise there.

“Use one liners” – again preference. I would choose a third option:

public int add(int a, int b) {
return a+b;
}

“Use many, many objects with many interfaces” – again preference. Using interfaces doesn’t solve any problem and when using interfaces you can’t access the properties directly hence access through getter and setter methods and a direct contradiction to “No setters”.

“Use Erlang-Style Concurrency” – don’t know enough about this to have an opinion

“Use Fluent Interfaces” – again preference. This is the new JavaScript programming style but I don’t like it. The biggest downside is debugging as you cannot set a breakpoint on a specific method call as this is all one big line.

“Data Transfer Objects without setters and getters” – again preference although I can see some benefit of immutable objects. However, this should be available through the langugage which it isn’t. Java is not Erlang. Refactoring is easy with well designed objects, properly managed code and a good IDE. This has more to do with the quality of the programmer and the tools than the programming style.

Frank

Scott C

I agree that most of the reduction of programming errors by using Functional languages (Scala,etc) could be accomplished using similar methods to reduce state in Java. Many of these suggestions are similar to those in the “Effective Java/Joshua Block” book.

My only problem with passing everything in immutible chunks is that it requires so many helper classes to be defined and makes handling the program in the eclipse ide a lot more cumbersome. For a single boolean true/false flag to be added to a transaction requires a lot more work than just having a getter/setter.

Also the main concept of the Scala actors model can be easily accomplished using a BlockQueue with immutible messages in java. This would not scale to ultra high volumes however due to the context switching. I understand the ‘react’ command in Scala allows the next actor to stay on the same thread.

Mario Fusco

Great post, really.

About #3 there is in my opinion also a better solution. Give a look to the lambdaj library:

http://code.google.com/p/lambdaj/

and you will discover that your example could be rewritten without loops or anonymous inner classes as it follows:

List beerDrinkers = select(persons, having(on(Person.class).getAge(), greaterThan(16)));

Cheers
Mario

stephan

@Mario: Nice, I will take a look. Thanks.

rgz

Ignacio Coloma nails it for me, however it’s nice to see people fighting to revitalize Java style.

dyu

#2 and #8 most definitely agree.
I partially agree with #1 but not on local variables as it tends to be clutter.

One question, for #8, if the code is to be used as a library (opensource)… would you still lean on removing the getters?

Normal java developers who consume your code tend to look for public getters all the time.

All-in-all, very intersting points!

@dyu: I think if it’s part of an API, I would not remove getters. If there are clients you do not control, public fields might be troublesome.

For deeper considerations about public APIs, I suggest reading the most excellent:

“Practical API Design: Confessions of a Java Framework Architect (Hardcover)”

http://www.amazon.com/Practical-API-Design-Confessions-Framework/dp/1430209739

Georgi

Point #3 was particularly interesting but I don’t agree so much with point #4 as I find that to be unreadable.
Interesting post overall :)

[...] posts like Stephan Schmidt’s Go Ahead: Next Generation Java Programming Style and the response from Cedric Otaku really should make any professional software engineer concerned [...]

Interesting coding style. I am a java developer myself. I am quite concern to hear that people are moving out from java to other languages. Java is a great language, yes it can be too noisy and over bloated to many people. But they have a strong presence in enterprises and a strong open source community backing them. I hope to see more improvement in the future for java.

[...] Was kann man tun, um den ‘altbackenen’ Programmierstil in Java zu verbessern? Ein paar Ideen und Kommentare aus einem [...]

I agree that most of the reduction of programming errors by using Functional languages (Scala,etc) could be accomplished using similar methods to reduce state in Java. Many of these suggestions are similar to those in the “Effective Java/Joshua Block” book.

Great post! For us at Mysema new Java programming style is also very much about type-safety. To promote type-safety with database queries we offer our own LGPL licensed query layer : http://source.mysema.com/display/querydsl/Querydsl

Querydsl supports JPA, JDO, SQL, Lucene, Java collections and RDF.

So instead of inline strings you can use fluent type-safe Java calls.

Det

@Jaroslaw Dobrzanski – August 12th, 2009
“Now, I wouldn’t agree ‘Use one liners’ is that good. I like one liners but still instead of
public int add(int a, int b) { return a + b; }

I would use
public int add(int a, int b)
{
return a + b;
}”

AND

@ Ignacio Coloma – August 11th, 2009
“#4 one-liners does not improve readability, but save space, which is not the same thing. Breaking the expected vertical rythm makes code harder to read in most cases.”

The problem here is the “expected” vertical rhythm. In the western world, we write from left to right. Even mathematical formulas are from left to right. You would not find a mathematician writing

y =
f(x)

f(x)
=
x**2
+
2x
+
5

Therefore, the overdone vertical writing style is already “unnatural”, but conditioned over a long time of simply doing it, and perhaps a relict of the assembler times, where code was read in columns.

At the time you get used to grok such one-liners as “expressions”, like a formula in math, it feels uncomfortable to have such simple expressions artificially split. This splitting of even the simplest expressions is again an artefact of the verbosity of Java.

See:
public int add(int a, int b) { return a + b; }

as:

int add(int a, int b) = { a + b}

or even:

add(a, b) = a + b

The problem is, that all the boilerplate makes it hard to find the elementary things, so you “emphasize” them by putting each on an own line.

NB:
Another old generation style is, to write all attributes at the beginning of a class and getter and setter below, sometimes sorted in all getters and all setters apart.

This style feels like the very old Cobol days with its different sections.

A NG style I sometimes use is, to group the property parts together:

private String name;
public String getName() { return name; }
public void setName(String pName) { name = pName }

[...] source: Go Ahead: Next Generation Java Programming Style [...]

Great post. Music to our ears here at kaChing ;)

I do not agree with you that predicates is OO. Rather they are the natural way to express a function T -> bool in an OO language. If you think of how closures work (i.e. closed functions with stack plus code) they are essentially an object passed around. In that sense, they are very close to what a predicate does.

Pascal-Louis Perez
CTO – kaChing

@Pascal-Louis Perez: Wow, kaChing, you’re my heros, I hope we can move to your devops style and to continuous deployments.

I might think that predicats are just that, predicates. And expresses as functions in FP languages and objects in OO languages. But even in FP languages they are manifestations, not functions per se.

Stephan
Vice CTO – brands4friends

Great post, and it seems like I’m already doing most of this stuff. And for me also, working in Scala has changed my Java programming style (for the better! :))

Nice post, clear explanations and argumentation.

@Rick: Thx

@Jan Wilem: Scala has changed me too, although my Java was very functional, pragmatic and non-mainstream already.

[...] setter for collections, make the getter return an immutable list and added an addSomething method (all following further good practices that were also on Code Monkeyism). Project development went on then we hit the point in where we needed to develop our entity search [...]

Great post. A couple of comments:

1) you’re going to have a loop somewhere one way or another (e.g. inside the filter method), but I absolutely agree that the closer you can get to a functional style, the better.

2) One liners… use with caution. Even trivial things can be easier to step through in a debugger if you have the calculation separated out line by line. Also, you’re not going to gain much efficiency by compressing something like your example add method.

Leave a Reply

What people wrote somewhere else:

New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style http://bit.ly/CfW3

This comment was originally posted on Twitter

RT @bjartek: RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP – good post!!

This comment was originally posted on Twitter

Great post. I think you managed to capture a trend that is alive and kicking and helps programmers be productive despite the fact that it is not emphasized (yet) in the text books, university courses, etc.

On top of this list, I think there is also “the next generation patterns/designs”. This list includes topics such as: DSLs, Dependency Injection, and the Properties Pattern (http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html).

This comment was originally posted on Code Monkeyism

Really good article! RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

Also, this reminds me of Jeff Bay’s “Object Calisthenics” essay (summarized here:
http://binstock.blogspot.com/2008/04/perfecting-oos-small-classes-and-short.html).

This comment was originally posted on Code Monkeyism

RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT – great points, agree with most of them! – @codemonkeyism Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

Hi Stephan,

I agree with all points but #3 and #4.

More specifically, I agree with #3, only use with care: I’d prefer not to introduce additional dependencies (as Google Collections) if I only have a bunch of (ugly) loops.

Regarding #4, I find one-line methods almost unreadable, and I still prefer to break them.

Other than that, I’d sum up your most important advices as follows: think by interfaces, and always keep concurrency and side-effect-free in mind :)

Cheers,

Sergio B.

This comment was originally posted on Code Monkeyism

@sbtourist I agree with most of them as well.nothing new in there, just very clear statements :-) http://is.gd/2aj80

This comment was originally posted on Twitter

RT: @neotyk: RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT @codemonkeyism (via @ovstetun) Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

stuck with java? very good post by @codemonkeyism : Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

Agreed. Do this. RT @codemonkeyism: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT: @sbtourist: great points, agree with most of them! – @codemonkeyism Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

Antti Mattila

Is there some reason why example DTO in #8 has non final fields?

This comment was originally posted on Code Monkeyism

Just do it RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

this is great! RT @codemonkeyism New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

>Make everything immutable.

Final does not make your entities immutable.

This comment was originally posted on Code Monkeyism

> Another benefit is lower coupling
So you are for low coupling …

> This way the class is reusable
And reusability …

> Data Transfer Objects without setters and getters

But not for encapsulation?

I think you need to get your software engineering goals straightened out.

This comment was originally posted on Code Monkeyism

Great post, thanks!

This comment was originally posted on Code Monkeyism

RT @codemonkeyism Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT @codemonkeyism Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

stephan

@Mike: No, final does not make everything immutable. You need to have immutable containers and deep immutability.

No, for simple data holder, paramter objects and data transfer objects, encapsulation is not needed and the generated boiler code in Java is doing harm (if you need to look through 3 pages of source just to detect, it does nothing more than hold data). If encapsulation is needed later, refactor (Think DRY and premature optimization)

This comment was originally posted on Code Monkeyism

stephan

@Antti: No, my error, changed, thanks :-)

This comment was originally posted on Code Monkeyism

RT @codemonkeyism Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

zef

New generation Java programming style: http://bit.ly/z5FiH

This comment was originally posted on Twitter

Articulo interesante acerca de programar en ehm java
http://bit.ly/z5FiH

This comment was originally posted on Twitter

Next-gen Java Programming Style… http://bit.ly/z5FiH

This comment was originally posted on Twitter

Out of habit going to #HackerNews, my article is at the top! “Next-gen Java Programming Style” http://bit.ly/CfW3

This comment was originally posted on Twitter

Tetsuo

What is interesting is that you don’t eat your own dog food. None of the code samples, besides #1 follows rule #1. Maybe because if you fill your declarations with ‘final’ they will become less readable?

It would be great if Java had ‘final’ enabled by default, or if it had a shorter way to declare it.

It would be greatest if the semantics of ‘final’ were complete immutability, not just local variable immutability.

But Java isn’t like that, and forcing things may be useful sometimes, but most of the time they will just add noise to the code.

This comment was originally posted on Code Monkeyism

RT @newsycombinator: Next-gen Java Programming Style http://bit.ly/ebTyC

This comment was originally posted on Twitter

Next-gen Java Programming Style? http://bit.ly/41wTSK

This comment was originally posted on Twitter

RT @justinvincent: Next-gen Java Programming Style? http://bit.ly/41wTSK #java #programming #style

This comment was originally posted on Twitter

that’s nice… or just use another language!! RT @justinvincent: Next-gen Java Programming Style? http://bit.ly/41wTSK

This comment was originally posted on Twitter

Some very intertesting ideas / tips RT @justinvincent: Next-gen Java Programming Style? http://bit.ly/41wTSK

This comment was originally posted on Twitter

stephan

@Tetsuo: Noise with final is an issue, I’ve seen that in many code reviews. As you say, I’d wish it was default, and another modifier would make it not-final.

Concerning the examples: There is a difference between example code that does want to show something, and real live code. The balance is fragile, between example code that is too simple and example code that is complex but doesn’t show the things it should show.

This comment was originally posted on Code Monkeyism

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://is.gd/2aCZ7

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style http://icio.us/flj0os

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style http://ff.im/-6pi93

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6piJa

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6piJo

This comment was originally posted on Twitter

Nice one RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

interessant artikel over “next-gen” java programmeren : http://bit.ly/z5FiH

This comment was originally posted on Twitter

RT: @jboner: Nice one RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

Great post on a more modern/concise/readable Java programming style by @codemonkeyism. http://bit.ly/DybGI.

This comment was originally posted on Twitter

Awesome article: Next Generation Java Programming Style from @codemonkeyism http://bit.ly/5229W

This comment was originally posted on Twitter

Wouldnt call it next-gen, just OO. Good advice nevertheless. Next-gen Java Programming Style? http://bit.ly/41wTSK (via @justinvincent)

This comment was originally posted on Twitter

Thanks – it’s great to see all these excellent memes in one place. And I appreciate the links!

This comment was originally posted on Code Monkeyism

RT @jboner: Nice one RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

The problem I found with java is the idiot horde who would and will argue against this kind of excellent advice: http://tinyurl.com/ksexeh

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6pBpp

This comment was originally posted on Twitter

Next Generation Java Programming Style: http://bit.ly/z5FiH

This comment was originally posted on Twitter

Some great Java advice here http://bit.ly/CfW3 My own advice is still “stay away from it”,but these tips can make it less unbearable@rbanffy

This comment was originally posted on Twitter

Next Generation Java Programming Style: http://icio.us/flj0os

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/IVViJ #design

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/bzUIM

This comment was originally posted on Twitter

interesting RT @codemonkeyism Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

…or switch to Groovy :oP http://icio.us/flj0os

This comment was originally posted on Twitter

What do you think of coding in Java in a more next gen fashion – http://bit.ly/CfW3

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/1fHKM software programming development java design tips

This comment was originally posted on Twitter

Next Generation Java Programming Style: http://bit.ly/z5FiH

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style http://bit.ly/tAWS2

This comment was originally posted on Twitter

Like it! : RT: @davecheong: What do you think of coding in Java in a more next gen fashion – http://bit.ly/CfW3

This comment was originally posted on Twitter

RT @sarbogast: …or switch to Groovy :oP http://icio.us/flj0os

This comment was originally posted on Twitter

RT @sarbogast: …or switch to Groovy :oP http://icio.us/flj0os

This comment was originally posted on Twitter

Next generation Java programming style – excellent read! http://bit.ly/CfW3

This comment was originally posted on Twitter

this Java programming style is interesting to read: http://bit.ly/z5FiH

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/1aJ4EV

This comment was originally posted on Twitter

delicious: Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/KoyOn

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/KoyOn

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6qosq

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6qoss

This comment was originally posted on Twitter

この人すごいOO厨だ!!(via marsのメモ) http://bit.ly/z5FiH

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ow.ly/15KxRy

This comment was originally posted on Twitter

@codemonkeyism: Got some crap on this “Next Generation Java” article – e.g. rule 3 antagonizing rule 4’s conciseness: http://bit.ly/CfW3

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style http://bit.ly/hEoN

This comment was originally posted on Twitter

dev: Go Ahead: Next Generation Java Programming Style | Code Monkeyism : http://bit.ly/z5FiH

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style – http://budurl.com/q6zd

This comment was originally posted on Twitter

Next gen java programming style http://bit.ly/z5FiH

This comment was originally posted on Twitter

Next Generation Java Programming Style. http://bit.ly/12h0h9
realized that programming language is a powerful tool, but just a tool.

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6qXz0

This comment was originally posted on Twitter

nice http://bit.ly/z5FiH

This comment was originally posted on Twitter

こうして読んでいると隔世の感があるなぁ Next Generation Java Programming Style http://bit.ly/z5FiH

This comment was originally posted on Twitter

some nice “next generation” java programming guidelines http://bit.ly/DybGI

This comment was originally posted on Twitter

RT @jbrownlee: some nice “next generation” java programming guidelines http://bit.ly/DybGI

This comment was originally posted on Twitter

@jboner Nice one RT @codemonkeyism: New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP

This comment was originally posted on Twitter

What is next gen Java coding? http://bit.ly/9tPHn

This comment was originally posted on Twitter

New blog post: Go Ahead: Next Generation Java Programming Style http://bit.ly/ht8HP (via @bjartek, @codemonkeyism)

This comment was originally posted on Twitter

Really nice reading: Next Generation Java Programming Style http://bit.ly/21xyfA (via @jarannilsen, @bjartek, @codemonkeyism)

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style http://bit.ly/DybGI some good points

This comment was originally posted on Twitter

The Next Generation Java Programming style looks more like 30 year old Functional Programming style http://bit.ly/CfW3

This comment was originally posted on Twitter

fav: Go Ahead: Next Generation Java Programming Style | Code Monkeyism : http://bit.ly/z5FiH

This comment was originally posted on Twitter

CODE MONKEY: Next-gen Java Programming Style http://bit.ly/9tPHn (via @featureBlend) #phmodev

This comment was originally posted on Twitter

RT @codemonkeyism Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT: @filjedi: CODE MONKEY: Next-gen Java Programming Style http://bit.ly/9tPHn (via @featureBlend) #phmodev

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6rk5W

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style: http://bit.ly/WG8U6 #programming

This comment was originally posted on Twitter

Sorry, but I do not agree with some of these points:

#1 “final makes code easier to read”: Final is yet another word that has to be processed by the reader. If the point is avoiding bugs, I would recommend FindBugs instead.

#2 You are using Tell Don’t Ask as the holy grail. For me, creating an isOlderThan() method goes against The Simplest Thing that Could Possibly Work and DRY (next: isYoungerThan, isOlderOrEqualsThan, etc). Sure, you can create a Domain method for every possible operation but then your domain classes will not scale too well, and it goes a bit against OO 101.

#3 Closures are one thing, but here you are changing one idiom with another. There is no gain in number of lines of code, readability and (certainly not) performance.

#4 one-liners does not improve readability, but save space, which is not the same thing. Breaking the expected vertical rythm makes code harder to read in most cases.

#5 implies that “many interfaces” == “better reusability”. This depends on the environment (the “forces” if you are talking about patterns), and cannot be applied as a general rule of thumb. I have seen plenty of idiotic interfaces out there, solving problems that proper encapsulation and inheritance would do much better.

#8 only applies if there is nobody else using your code. As soon as your library is used by third parties, refactoring would break things.

As a side comment, injecting the Twitter feeds into the comments section really lowers the S/N ratio of this thread.

This comment was originally posted on Code Monkeyism

Next Generation Java Programming Style http://is.gd/2bMLZ

This comment was originally posted on Twitter

RT @codemonkeyism Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT @codemonkeyism Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

#1 through #7 is saying to adopt a more functional style of programming, which I’m a fan of:

http://enfranchisedmind.com/blog/posts/this-is-your-brain-this-is-your-brain-on-ocaml/
http://enfranchisedmind.com/blog/posts/object-burn-is-your-friend/
http://enfranchisedmind.com/blog/posts/some-final-patterns/

Java really screws you with #8. Unlike C# and Groovy, refactoring a public field is *not* trivial in the user code. So you’re pretty much toast if the object is ever going to be maintained moving forward. And if you’re going to making things fragile with malice of foresight, you should probably make the class final, too, just so you don’t take other people down with you. I’d actually suggest implementing #8 by writing that code in Groovy, even if you’re calling it from Java: you’ll get the implicit getters and setters for free, along with the code readability.

This comment was originally posted on Code Monkeyism

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/cvSDm 実におもしろい。
Javaの昔の常識は今の非常識になりつつあるのか。

This comment was originally posted on Twitter

Next Generation #Java Programming Style http://bit.ly/Zf4NT (RT @darcia)

This comment was originally posted on Twitter

re:http://is.gd/2bZm2 by @codemonkeyism is it possible to have a scala2java (subset of scala which can code generate 2 java)? #thinkingaloud

This comment was originally posted on Twitter

Sorry Stephan, but I disagree with most of your suggestions :-)

More detailed response on my blog:

http://beust.com/weblog/archives/000517.html

This comment was originally posted on Code Monkeyism

Interesting Article on Java Programming Styles http://bit.ly/z5FiH

This comment was originally posted on Twitter

interesting article on code monkeyism (although i don’t agree with points 4 and 8) http://tr.im/wdba #java #coding

This comment was originally posted on Twitter

Stephan Schmidt’s (@codemonkeyism) Java style tips (http://bit.ly/DybGI, http://bit.ly/wCcRT) are all just reasons to use Scala

This comment was originally posted on Twitter

Ray

The list seems to be a feature set of Scala. You get all of those items in idiomatic Scala as opposed to trying to improve Java via the use of a rather non-idiomatic style.

Scala is Java done correctly. And more.

This comment was originally posted on Code Monkeyism

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6sULU

This comment was originally posted on Twitter

Next Generation Java Programming Style http://bit.ly/5Cq99

This comment was originally posted on Twitter

@cbeust Added my comments to your comments about #Java programming style http://bit.ly/CfW3

This comment was originally posted on Twitter

I liked ‘Final is your new love’, ‘No setters’, and ‘Use many, many objects with many interfaces’. ‘Do not use loops for list operations’ was interesting too – I’ve never used Google collection filter before.

Now, I wouldn’t agree ‘Use one liners’ is that good. I like one liners but still instead of
public int add(int a, int b) { return a + b; }

I would use
public int add(int a, int b)
{
return a + b;
}

Anyway, everybody has their own style.

Cheers,
Jarek

This comment was originally posted on Code Monkeyism

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/2urbCH

This comment was originally posted on Twitter

The new Java http://bit.ly/z5FiH

This comment was originally posted on Twitter

http://bit.ly/C1Y7b @codemonkeyism post about the new #Java coding style is getting some interesting feedback.

This comment was originally posted on Twitter

Next Gen Java Programming (Article worth reading) : http://bit.ly/z5FiH

This comment was originally posted on Twitter

RT @codemonkeyism Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/ht8HP

This comment was originally posted on Twitter

RT @QBurst: Next Gen Java Programming (Article worth reading) : http://bit.ly/z5FiH

This comment was originally posted on Twitter

@brianstarke This article has some nice suggestions for Java coding that would ease the transition from scripting langs http://bit.ly/CfW3

This comment was originally posted on Twitter

Java attempting to look cool http://bit.ly/z5FiH
#troll

This comment was originally posted on Twitter

interesting Java practices: http://bit.ly/z5FiH

This comment was originally posted on Twitter

http://bit.ly/z5FiH
google-collectionsは使いたい

This comment was originally posted on Twitter

Evolution des pratiques de codage en Java http://bit.ly/4uR7u

This comment was originally posted on Twitter

Fluent Interfacestってしっくり来ないな。この手の例だと、結局setterだし、無駄にmutableだし、設定漏れ弾けないし。 http://bit.ly/z5FiH

This comment was originally posted on Twitter

やっぱFluent InterfaceはDSLっぽい特殊な場合専用とした方が良い気がする。一般的なstyleというより。http://bit.ly/z5FiH

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-6C71p

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style – http://budurl.com/q6zd

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style — http://bit.ly/z5FiH
— Stephans Blog

This comment was originally posted on Twitter

Go Ahead Next Generation Java Programming Style | Code Monkeyism: What can a Java developer learn from other lan.. http://bit.ly/KoyOn

This comment was originally posted on Twitter

Stephan Schmidt:Go Ahead: Next Generation Java Programming Style //http://codemonkeyism.com/generation-java-programming-style/

This comment was originally posted on Twitter

[Bookmark] Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://bit.ly/KoyOn

This comment was originally posted on Twitter

Not convinced but: Changing your Java programming style (closer to new prog. languages) http://bit.ly/CfW3 #Java #programming

This comment was originally posted on Twitter

My post “Next Generation Java Programming Style” http://bit.ly/ht8HP had 14K views + 256 delicious bookmarks, postrank more useful than GA!

This comment was originally posted on Twitter

RT @codemonkeyism: My post “Next Generation Java Programming Style” http://bit.ly/ht8HP had 14K views + 256 delicious bookmarks #yam

This comment was originally posted on Twitter

“Java variables must be final”. Pfft. Sure, make it more opaque! How many times have you assigned to a var by mistake? http://bit.ly/9tPHn

This comment was originally posted on Twitter

Excellently said. You might also look at Functional Java. I think this is my first ever non-argumentative blog comment.

This comment was originally posted on a little madness

Hi Ricky,

Thanks for the comment, although it sounds like I’ll need to be more controversial next time . I have seen Functional Java which looks interesting. I am somewhat wary of the reimplementation of basic collections — have you found this an issue when working with other Java libraries? I’d have to actually try it before I could pass any meaningful judgement.

I actually do really need to look into the alternatives as Pulse currently uses a home-grown library. It was born before there was a decent alternative (particularly one which made use of generics), but I’m sure we’d be better off switching to something more complete now.

This comment was originally posted on a little madness

Yes a good post indeed. I already tried to express that recently, after 4 years of doing just that in our team.

You do emphasize what’s important: over time a growing set of functors can be reused and composed together (boolean operations etc) as a plumbing kit. We used Apache Commons Collections Predicate, Closure and Transformer a lot (with Java 1.4) and very quickly all the team loved it, without even knowing for a long time that this was called functional style. And the benefits talked for themselves: much higher reuse, less LOC, no side effect, trivial unit testing, flexibility to configure the application at assembly time…

Whenever I mention functional style everybody immediately speaks about Scala, F# or another sexy language, whereas what’s really important is the style in itself (paradigm), not the syntactic sugar.

This comment was originally posted on a little madness

Excellent java programming tips. http://icio.us/flj0os

This comment was originally posted on Twitter

Cool coding java techniques http://icio.us/flj0os

This comment was originally posted on Twitter

next Java programming style http://bit.ly/z5FiH

This comment was originally posted on Twitter

Go Ahead: Next Generation Java Programming Style | Code Monkeyism http://ff.im/-75iDs

This comment was originally posted on Twitter

It looks like Google engineers haven’t reached consensus about a functional style in Java. Josh Bloch http://gafter.blogspot.com/2007/12/what-flavor-of-closures.html?showComment=1197631980000#c8863950537789037629 and Cedric Beust http://beust.com/weblog/archives/000517.html are against the functional style in Java, while the authors of Google Collections http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Iterables.html promote and support it.

This comment was originally posted on a little madness

Frank

It really is just a matter of personal preference and not of better readability. The simple fact that the code contains a lot of class and function definition keywords like new, return, public, boolean plus additional parentheses makes this harder to read IMHO. I am sure that there are useful applications of this but stating that the one is “better” than the other is nothing more than an opinion.

Frank

This comment was originally posted on a little madness

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?