Skip to content

Category: Java

Things I like about Java: Anonymous classes

Everybody that knows me in real life knows that my favourite jokes are always those about Java being slow and bloated. But still, in all fairness, Java has some good things.

One of them, rendered obsolete by Java 8’s Lambda Expressions, that I always liked and that I really wish was possible in Swift, is Anonymous classes.

The way I see it, an anonymous class is just a syntax shortcut to declare and instantiate, inline, an instance of a specific interface. It is a quick way to create lightweight objects at the moment they are going to be used, or passed to another object.

Anonymous classes have access to the members of its enclosing class, and local variables in its enclosing class marked as final, which makes them great candidates to be used, in particular, to declare callbacks in particular.

To me, their greatest advantage is that anonymous classes allow you to encapsulate behaviour in a way that you only declare implicit types when you expect to actually reuse them.

Still, Lambda Expressions, similar if not equal to what in Swift we know as closures, might make code more concise in some situations. So, as usual, it comes down to knowing your tools, and careful considering which tool is the best for the job.

Updated on Sept 24th.

Joe Fabisevich points out that something similar to what the sample code does could be achieved in Swift by typealias-ing a closure, and typing AThing’s doAThing parameter as said typealias.

Which is quite similar to a solution based on Java lambdas.

If we need to declare more than one method in the Command interface, though, this approach would fall sort.

Joe also suggests another option in Swift:

This still requires making a type, but it is (or can be) private to the Main class, which in a way achieves the same goal as an anonymous class. It would be a concrete type, yes, but known only to the type enclosing it.


Leave a Comment

Elegant Swift: Default Parameters vs The Builder Pattern

I was re-reading Effective Java (it is a rainy Sunday afternoon in Vancouver, and if you are stuck at home, and you happen to be European, and therefore you don’t really care about what Americans call “football”, re-reading Effective Java is not as bad as it sounds) when I soon stumbled upon an example that I think highlights the elegance of Swift (and, to be completely fair, also Kotlin’s).

Effective Java’s Item #2 says: Consider a builder when faced with many constructor parameters. Which makes total sense, if you ask me.

I am not going to discuss or justify the Builder Pattern now, but let’s just assume that it is more than justified.

The canonical implementation of the pattern, and I am going to take the liberty of using the code sample used in Effective Java without any modification, would read like the following (servings and servingSize are the only mandatory parameters, the rest are all optional)

If we follow the pattern to the letter, it translates into Swift like this:

Which is a lot of boilerplate, no matter how you look at it.

We have discussed Swift’s Default Parameters before in this blog, but in the context of Dependency Injection, in particular when focusing on testability.

But the thing is that Default Parameters, like many other Swift artifacts (or constructs, or whatever is the right word to refer to “stuff that Swift provides and makes your life easier”) can make code much more concise, readable and easier to understand and reason about while removing some of the bloating that certain languages (I’m looking at you, Java) are known for.

Because when providing default values to all the optional parameters, this is how our NutritionFacts look.

Much better, eh?

Leave a Comment

Primitive obsession

If you have been following this blog (hi, mom!) you might have noticed a recurrent obsession of mine: stop looking at the wrong abstraction.

There is one case when looking at the wrong abstraction can be particularly dangerous: dealing with primitives.

Primitive what!?

Martin Fowler (bow) already explained this, better that me obviously, in Refactoring. “Replace Data Value with Object”, Mr Fowler wrote. “Apply this refactoring when you have a data item that needs additional data or behaviour”.

But what does than mean? Let’s see it with an example.

Often times, primitives (strings and numbers in particular) have special meaning. Phone numbers, addresses, email addresses, usernames… all of those are either numbers of strings, but those are numbers or strings with some associated “behaviour”, specially in terms of how they are represented or validated.

For example, consider a class that models a User. The proper way of modelling an User using a POJO would be something like this:

That class would pass 99% of code reviews without a single comment. It is immutable, it encapsulates the user data properly, and it does not expose anything it should not expose.

Now, let’s say we create a User like this:

And now, let’s say we create it like this.

Boom. Name and surname are swapped, and the user has an invalid email address.

Promoting primitives to objects

I have already discussed a similar approach to the one I am going to suggest now. However, there are some subtle differences.

Let’s discuss first the email address. An email address can be represented as a string, but there is some behaviour associated to it, because not all strings are valid email addresses. Email addresses need to be validated!

So, representing an email address as a string means that it will need to be validated every time it is going to be used.

However, if we have an EmailAddress class, we can either guarantee that instances of that class will only be created when they are provided a valid email address (as a string) or declare a method that validates the address.

If we did that, the previous constructor could be rewritten as:

Now, what about the name and surname? Well, we might want to add some behaviour to them as well, but I think the most compelling reason to promote them to objects would be type safety. Check this out:

Now, it is impossible to mess up the order of the arguments. The compiler will complain loudly as soon as you do not pass the right thing at the right place.

Isn’t that unnecessary complexity?

I wouldn’t say so. I would say that it is proper object orientation. A first name is not a string, although it is usually represented as a string, the same way an email address is not a string, but something with semantic value that, yes, can be represented as a string.

Now, obviously, this means more classes and most likely more objects living within the application cycle. True.

But software engineering is all about considering and balancing the trade-offs. And in this case, an extra class is a price I’m willing to pay in exchange for safer, more robust, and more cohesive code.

Leave a Comment

Sometimes nothing is something. Or the null object pattern with a touch of the decorator pattern

Or why if clauses should die in a fire.

This post has been lingering, locked up in my drafts folder (which is not an actual folder, but all the cool kids say that, so bear with me on this) for some time.

Yesterday, I stumbled upon this talk by Sandi Metz, because, yes, sometimes I search Youtube looking for recordings of talks about OOD. I am a big fun on Sandi’s talks, and this one did not disappoint me, as usual. And it also gave me the push needed to publish this post

If clauses breed, and sometimes, nothing is something

I am not a big fan of if clauses. I know they are necessary, but I try to avoid them as much as possible, specially when they are type checks.

Type checks are bad

Period. There is always someone that will tell you that type checks might be necessary sometimes, but truth is they are one of the biggest and stinkiest code smells.

“What is a type check?” you might ask. Fair enough; this is a type check:

This is the quintessential example of why type checks are wrong, and you will find a thousand slightly different variations of it on the interwebs.

What’s wrong with that? Simple

Type checks are a sign of bad design

The previous code sample is the perfect example of how a type check is a symptom of a bad abstraction. A Fish and a Spider are both animals, so they both should implement an interface declaring a move() method. Clients of Fishes and Spiders would only be aware of that abstraction and call the move() method. Period.

There is a particularly bad type of the check

And that is the one that does not look like one. It is usually in disguise, pretending to be a null check.

Here is an elaborate example. Consider a Car class:

And a CarWarehouse class:

Now, clients of the CarWarehouse want to checkout cars by name:

The forEach method will crash, because it is trying to call getName on something that is null.

Fine, you might think, I will just filter the stream to remove the objects that are null:

But that’s just bad.

Type checks breed

Once you need to start filtering your results, once a client of a class A needs to start performing a type check on the values returned to it by that class, you are going to need to repeat those checks every single time you want to use that class A.

Why? Because you expect the values returned by A to be of at least two different types: null and whatever it should actually be returning.

So, how what can I avoid those type checks?

Making your classes meet the expectations they set. Simple as that.

Which, of course, happens to be not that simple. But seriously, if clients of your class are expecting a collection of entities that respond to a particular message (note the Smalltalk-speak), make sure that all the entities your class returns respond to that message. Again, simple as that.

In the previous example, what do I want exactly? I want all the objects returned by CarWarehouse to respond to getName. Then all I have to do is return a collection of objects that respond to getName. And if there is no object to return, then I will return something else that still responds to that message.

The Decorator pattern. Sort of.

Here come the big guns! Design patterns to the rescue! Not too long ago, I ranted about how design patterns are abused.

In this particular case, I m going to adapt one of the patterns in the catalog, the Decorator Pattern, to wrap my Car objects:

Notice how SafeCar extends Car. That allows me to do the following:

Which, as you can see, is basically creating a null object, sort of. Again, I am taking the liberty of adapting the pattern to my needs.

And now, clients of my CarWarehouse can conduct their business merrily:


What matters are not the tools you have, but how you use them. Over-abstraction is bad. Over-engineering is bad. Knowing the tools in your belt, knowing how to adapt them and how to let them work together to solve your needs is what matters.

Oh, and sometimes, you need something to help you deal with nothing.

Leave a Comment

Principle of least surprise

Another Principle! I am on a roll! Although, to be honest, this is not an actual principle.

If you work for a serious company, you would most likely have one of these printed out and hanging from one of your office’s walls. If you don’t have it, now you have something to do today.


When it comes to source code, this principle can be summarised as:

Don’t try to be a smartass. Write code that is easy to understand.

Oh, noes! Is this another rant about semantic code?

Actually, no, it is not, thanks for asking. I would not say it is a rant, I would say it is a more like unwanted advice, but about something else.

The offending code.

This code, slightly edited to protect the innocent, was extracted from an actual codebase my team has to maintain.

There are plenty of WTFs here. But the one that stands out the most is on smartMethod: why on earth would I loop all the entries in a Map only to act upon those that match a set of constant, immutable, known keys?

Isn’t our life complicated enough, as it is? Why do we want to make our code more difficult to read and understand, for the shake of a flexibility that may or might not be necessary? A flexibility that, at least in this example, is not even flexibility at all?

Do the simple thing first.

Instead of looping the map keys looking for something we already know is there… why not just ask for it?


Now, if you look at that code carefully, if you look at any piece of simple, dumb code, carefully, you will instantly hear it screaming at you, shouting everything is wrong with itself.

In this example, the smartMethod has an expectation on which keys in a Map it will need to use. That tells you that a Map is not the right type for that parameter: maybe two strings would do?


Keep it simple. Do not try to impress anyone. Seriously, your skills as developer are not directly proportional to how obscure your code is.

Leave a Comment