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!

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Billboard image

Try REST API Generation for MS SQL Server.

DreamFactory generates live REST APIs from database schemas with standardized endpoints for tables, views, and procedures in OpenAPI format. We support on-prem deployment with firewall security and include RBAC for secure, granular security controls.

See more!

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay