the blog for developers

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

From the category “Bending Java near it’s Breaking Point” or “What a stupid but interesting idea”. I like to explore ideas in Java that are inside the language spec but outside of common usage or style guides. I think Java has a lot more to give than what people did the last ten years. Before dumping Java perhaps we should reconsider some of the “common wisdoms” about how to do things in Java.

My last post on beautiful Java, and why to never use String ;-) got me flamed like I haven’t been flamed since alt.amiga.advocacy times. The idea was to provide wrappers around String like Name to achieve several things: Have better typed method signatures, have a fluent interface and to better convey meaning.

Customer customer = new Customer( name("Stephan") );
...
Customer(Name name) {
...
}
...
public Name name(String value) {
...
}

The flames were mostly about creating lots of small objects, which people claimed are unnecessary and unmaintainable.

An alternative implementation would be:

Customer customer = new Customer( name("Stephan") );
...
Customer(String name) {
...
}
...
public String name(String value) {
 return value;
}

This implementation doesn’t achieve the same things as the solution before, but there is no new object necessary, only a new method.

But still the line Customer customer = new Customer( name("Stephan") ); is more readable than Customer customer = new Customer( "stephan" );. The Hotspot JIT should optimize the method calls away so there is no performance penalty.

A better idea? Or still too repulsive.

Thanks for listening.

As ever, please do share your thoughts and additional tips in the comments below, or on your own blog (I have trackbacks enabled). This line is shamelessly take from Daniel Tenner, who writes a really excellent blog.

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.
Leave a reply.

Comments

ted stockwell

Don’t listen to the critics, I think your first approach was exactly right…

new Customer(new FirstName(“Stephan”), new Name(“Schmidt”));

Another benefit of this approach is that is ’semantic’.
That is, it has the benefits of being able to precisely defining the semantics of each and every property, like in RDF.

I suppose that guy that thinks that modelling is doing more with less would be happiest with no model at all :-).

——————–

BTW, I really like your posts on Java syntax, modeling, etc. Keep them coming please…

nice idea, but depends whether you want to make the code verbose to improve readability.

Isn’t name() kind of just a way of getting around the absence of named parameters?

I can’t imagine doing that for every class that calls constructors, but maybe as statically imported methods from a utility class? Like:

NamedParameterUtils.name()
NamedParameterUtils.country()
NamedParameterUtils.age()

raveman

i dont like that idea, how about only non-arg contructors and builder pattern ?
Customer customer = new Customer().setName(“Stephan”);

i think it looks better

jan

Having classes like Name, PhoneNumber… can really become maintainability nightmare. But I also like to increase readability of the code. My favorite would be:

Customer customer = Customer.name(“Stephan”).phoneNumber(“12345″)

or

Customer customer = Customer.withName(“Stephan”).withPhoneNumber(“12345″)

Points for originality but…. that’s about it. How about we get object initializes, like in C#?

Customer customer = new Customer(){ name=”Stephan”, salary=65.000};

…then again, a little easier to do in C# than Java since it has native properties rather than mundane manual set/get mechanics.

Nick Westgate

While it’s always good to try new ways of improving readability, there are “better” (at least less controversial) existing solutions to the trivial example you provide – e.g. raveman’s above.

Here’s another traditional solution that doesn’t need methods:

String name = “Stephan”;
Customer customer = new Customer(name);

Some parameters might be deserving of an object type, like the OrderId in your previous post on this topic, but you should carefully consider how methods will look _when they are actually used_.

For instance, the following is common, and makes the method signature less relevant since context is provided in other ways.

Customer customer = new Customer(htmlForm.name);

Cheers,
Nick.

Uri

I dig your intent but I don’t really like the solutions (for all obvious reasons that were already mentioned). I think the problem lies in Java itself in the lack of named arguments for methods. how about having the following more generic solution (I’m still not a big fan of it though…)

class Utils {
$(“name”, name)
public static T $(String name, T value) {
return value;
}
}

then:

Customer c = new Customer($(“name”, “Stephan”));

I guess it’s the closest you can get to: new Customer (name: “Stephan”);

cheers,
Uri

Ammmm The naming convention is very similar to how Groovy would do – named arguments.

def cust = new Customer(name:”James”)

stephan

@Jan, raveman: Yes, see my post about fluent interface builders

@James: Yes, I like named parmeters

@Nick: Yes, this does work for small parameter lists, but breaks down for longer ones. It also doesn’t help with larger code bases where developers start to rename parameters. The difference between renaming String name and name() is that the first renaming is only local, the second is global and does therefor scale much better.

@Uri: Hmm, need to try that.

@Casper: Looks nice too.

I was using names parameters the first time during the 80 I guess with a programming language called E on the Amiga (or was it the 90s?). I like the idea since then, but Java regretfully doesn’t have them.

I don’t see the convenience of introducing methods (that should be maintained later) to achieve something that can be already achieved using the standard documentation tool of every language: comments.

Customer c = new Customer( “John” /*firstname*/,
“Smith” /*lastname*/,
87 /*age*/);

Introducing a method called firstname() or lastname() is so necessary?
When the type or the name of a property change you have to change also the method.

And what about the method name resolution? Using your method technique you have to import static all the methods do use it.

However I see a good thing of this idea. It can stimulate thinking about Java syntax and possible improvements to it.

stephan

@Andrea: As written before, the comments don’t work with refactorings (yes I know some IDEs do refactor comments but this is very error prone). Changing the methods when changing the types probably is a good idea, because changing one information without the other makes code unreadable over time.

I like Nick’s solution, I don’t think that renaming is that big of a deal in practice, even if it looks bad in theory.

I couldn’t help but wonder whether Java 5 annotations would work for this somehow.

JXInsight’s OpenCore API uses a Name interface in both Probes and Metrics which wraps around a String but it also supports composite names (delimited by dot) which allows us to reduce String working memory because Names are effectively interned within both our metering and metric models. This has also allowed us to augment such strings with meta-data (labels).

William

I prefer your original approach, with the Name class, but I would not pass it through some method first – just new up a Name.

J.B. Rainsberger and Corey Haines talk about Primitive Obsession in this video: http://blog.thecodewhisperer.com/post/424488983/corey-haines-interviewed-me-at-the-golden-tulip

The thing about having a Name class is, that functionality that is specific only to Names now have a natural place to live. If Name just ends up wrapping a final reference to a String, then that is also fine because that is now publicly tagged with a type from the problem domain.

That’s the short of it. Corey and Joe go into a lot more detail in the video.

@William: Good to know I’m not alone

@Chris: Thanks for the video link, I’ll take a look

@Andrea Francis & Stephan

Neither comments nor the named, do-nothing methods seem a good solution to named parameters, in my opinion.

In effect, the result is the variables/arguments having annotations (with a small ‘a’) that add semantics that the compiler knows nothing about. You are essentially creating a custom language outside Java and therefore outside the scope of most IDEs.

Inevitably (over time) comments will become stale or separated from what they annotate and methods that simply return a given value will be misused (e.g. using address(“Steve”) for a name argument would be perfectly valid syntactically but completely misleading semantically)

I think any implementation of semantic candy should make use of Java’s type safety in order be useful and maintainable.

Bend too far and things break.

E

P.S. Another great article Stephan, thanks.

@Elwyn: What would be your solution to this? (beside Parameter-Objects and refactoring of methods with more than one parameter) Would be interested.

@Stephan

I had a go at this (love a challenge) and couldn’t come up with a solution I would be happy with. My approach involved a (G)eneric builder that would allow the population of the properties in-line upon creation of a new object. However, this approach would use use reflection and proxies and therefore would suffer in terms of runtime performance.

I like the approach LambdaJ and JMock’s DSL (2.x) take to the syntax of these sorts of problems. However, with Java, sometimes I guess you just have to accept verbosity (and imperfection in general) as being part of the deal.

@Elwyn: I wrote something about – my take – on builders in Java here:

http://codemonkeyism.com/the-best-markup-builder-i-could-build-in-java/

I don’t care much for Java (or static typing in general) anymore, but your original approach is totally consistent IMO. It reminds me of Object Calisthenics (warning: RTF).

Gerolf Seitz

Regarding maintainability nightmare and having to create all those methods: Since the methods can be derived from the available fields, the task of declaring/defining the methods can be done by a tool, eg APT, plugin for IDEs, etc…
Project Lombok comes to mind.

Leave a Reply

What people wrote somewhere else:

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?