Hacker News new | past | comments | ask | show | jobs | submit login

We already have that, it's called the Builder pattern.



Up until recently, I've enjoyed the builder pattern. It becomes a pain in the ass though when your objects are deeply nested.

For example, with protocol buffers you end up doing things like.

AlbumCollection collection = user.getPreferences().getFavorites().getAlbums().toBuilder().addAlbum(album).build();

Favorites favorites = user.getPrefernces().getFavorties().toBuilder().setAlbumCollection(collection).build();

Preferences preferences = user.getPreferences().toBuilder().setFavorites(favorites).build();

and then you have to work your way up the chain of builders. Such a pain in the ass for something that could be much simpler with getters and setters.


This seems like a perfect example of a pattern applied in the wrong way. The builder pattern is supposed to be used to construct new instances (in other languages named parameters make it pretty redundant). I could perhaps understand allowing people to batch up changes but when you're forced to switch to a builder and back again to make a change to one field you've definitely got a poor design. The example seems particularly egregious because you're also forced to walk the ___domain where really you should just be able to do:

    user.addFavourite(album);


His example is creating new instances. It just happens to be creating them from existing instances. Basically a clone and change kind of operation.

You are right that normally you'd want the addFavourite method but in his example he is dealing with generated code which has a tendency towards verbosity.

You could add the method if Java allowed extension methods...


If you used the generated builder methods provided by protobufs, would it really be that bad?

  user.getPreferencesBuilder()
      .getFavoritesBuilder()
      .getAlbumsBuilder().addAlbum(album).build()


> Up until recently, I've enjoyed the builder pattern. It becomes a pain in the ass though when your objects are deeply nested.

That and good luck adding a new required field in your "constructor", because you just gave up on statically checking the parameters of the "constructor".


Can't say I understand the downvotes on this one. If you add a parameter in a traditional constructor but don't update the site calls, your code won't compile. If you add a builder method, your code will still happily compile, you'll have to wait until runtime to get an exception, if you added a check in the build() method. That's something to think about, just like you give up safety for convenience when you move to a DI framework.


So for every class in Java, we just create a corresponding builder class, because we lack certain features in the language?

This is not a solution, this is a workaround.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: