You Lying Get!

Consider the following code:

public Foo getFoo() {
return new Foo();

What’s wrong with it?

It’s a lying get. That’s what’s wrong. What a lying get. A get function implies retrieving something that’s already there. This function creates a new object every invocation.

What’s in a name?

Naming functions is pretty hard. It shouldn’t be. However, it seems there are two dreadful extremes to avoid:

  • The vague/abstract and wishy washy – where you get a sense that something might do something, but you’re not sure what – e.g. object()
  • The precise and implementation heavy – e.g. createNewObjectOfTypeFooAndReturnIt

Clearly both of these extremes are worth avoiding. But what’s right?

Name your function after its purpose, not how it achieves it.

So is a lying get bad? It returns a thing doesn’t it?

Pretty much all functions that return values could be considered to get stuff. In fact if you use more functional style programming, like Java’s Supplier you use the get word a lot. But when you define your own function, it’s important to give it a name that describes it enough that there are no surprises when you look inside the function.


public Foo create() {
return new Foo();

It’s simpler.

Other examples

I’ve seen a few things kicking around:

  • A function to send a message called handle
  • A routine to check if a page was loaded called pageLoaded
  • A function to read a file called getFile

A few rules may help avoid the vague or the horribly specific:

  • Functions with side effects should have a verb named after their main side effect
  • Functions generally should have a verb showing what they do/what they’re for
  • Functions that validate by throwing an exception or writing a validation state, should have an imperative in their name like verifyInput or checkStatus
  • Functions that find something out, should be named after the question the user has
  • Boolean functions should always be named after a question – ideally one in the positive, not negative
  • Things that retrieve existing data should be called get unless they’re searching, in which case find is clearer.
  • Never name a function with an abstract concept – e.g. messageProcessing

Final thoughts

Every poorly chosen, or misleading name is friction to the developer using your code.

Writing good tests up front can show you how your function names sit in context and will guide you towards renaming them to make their purpose clearer.

One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s