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!
Top comments (0)