Software Development

It’s Too Noisy

I want to look at a general case of noise in code. To do so, let’s look at how to instantiate a list in Java:

1
2
3
4
5
List<String> someList = new ArrayList<>();
someList.add("Snow White");
someList.add("Red Riding Hood");
someList.add("Evil Queen");
someList.add("Finbar Saunders");

It would be hard to argue that there’s an innate bug or flaw in the above… right?

Yet, when I’m looking at that code, I can’t help but find it repetitive and repetition is bad. Can’t we reduce that? All that someList.add stuff?

There’s a way to use inline initialization with an anonymous constructor:

1
2
3
4
5
6
List<String> someList = new ArrayList<>() {{
    add("Snow White");
    add("Red Riding Hood");
    add("Evil Queen");
    add("Finbar Saunders");
}};

Wow! That’s… erm… unconventional…

I’ve never seen an instance of the above that I haven’t refactored away!

So What’s Best?

Perhaps this is a question of preference, but let’s look at this:

1
2
3
4
5
List<String> someList = asList(
    "Snow White",
    "Red Riding Hood",
    "Evil Queen",
    "Finbar Saunders");

Clearly, that’s the least amount of code, at no cost in terms of readability.

Why is it Better?

And what’s the general case?

By using an existing library function, or by creating one, we’ve reduce the code at the call site to just the essentials of the request. Where the mechanism for achieving the request is peppered with boilerplate, the boilerplate distracts from what’s going on.

We wanted a list of some values, and seeing that list as a list is more important than seeing how lists are created.

When designing libraries, and when expressing our code, we should always be looking for our call sites to express their purpose, and not repeated details of HOW that purpose is achieved.

Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: It’s Too Noisy

Opinions expressed by Java Code Geeks contributors are their own.

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button