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 is head of development at brands4friends. He 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.

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

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

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?

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

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?