Home » Software Development » It’s Too Noisy

About Ashley Frieze

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

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:

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:

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:

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.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Notify of

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

Inline Feedbacks
View all comments