DEV Community

ADEKOLA Abdwahab
ADEKOLA Abdwahab

Posted on

Always Return an Object - Why?

Look at this function:

function canShare(username){
....
Do some checks
...
return true
}

Code snippet 1

When we call canShare('uyut') we get true or false. There's no problem with this.

So you could call/use the function like this:

`if (!canShare) {
Do something else

alert('cannot share')
}`

code snippet 2

However when building API services, especially one consumed by third parties this kind of return could be a pain when the API grows.

With the snippet above the user only know they can't, there's no provision to let them know why they cannot or what action they need to take to resolve it.

To achieve this the function needs to return more than a Boolean but what...an object!

However with the initial type of return, couple of things would have to be changed to accommodate the change - and there'd be ripple effects.

We can edit the function to return an object of this structure:

function canShare(username){
...
return {success:Boolean, message: string, action: string}
}

Code snippet 3

If an object is now returned the code snippet 2 would have to change to

`if (!canShare.success) {
Do something else

alert('cannot share')
}`

Code snippet 4

This looks like a simple change, however imagine the function being used in multiple ways, in multiple places.

What do you think?

Are there instances you think returning object would not fit?

What's your experience with issues like this?

Share, I want to read from you!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more