Is checking if something exists responsibility of a caller or an API?

by Konrad   Last Updated December 06, 2018 15:05 PM

Is it better for an API when it provides additional methods that check if something exists before adding?

For example:

if (!userManager.HasPermission(user, "somePermission")
   userManager.AddPermission(user, "somePermission");

versus

userManager.AddPermisionIfDoesntExist(user, "somePermission");

If you use this HasPermission in many places, wouldn't it be better to create method like AddPermisionIfDoesntExist ?

Or, if duplicates aren't allowed, should AddPermission check it instead?

So that would be similar to how Dictionary is designed, with methods like TryAddPermission and AddPermission that throws exception when permission already exist?

also, note that AddPermission and HasPermission are doing calls to the database



Answers 1


Its usually best if the API is written so that the check itself is internal, but it depends on what the behaviour you want from both the API and the caller.

  • Hide it all behind the API where caller shouldn't really care and its more of an internal implementation thing
    Permission has no other properties: addPermission(user, 'somePermission')
    And we are ok if this call just creates the permission entry (some sort of flexible admin schema)

  • throw an exception if the caller must have done something else first (eg, set permissions which shouldn't be under program control)
    Permission can't be added dynamically try {addPermission(user, 'somePermission') } catch e(){alert ("permission doesn't exist")}

  • Provide an override method if you want the caller to optionally ask the API to do the job on their behalf (and presuming this is practical for the API to do for them)
    addPermission(user, 'somePermission', addIfMissing=true)
    Again, we have to be ok if this call just creates the permission entry

  • If additional properties are required for the precursor then expose extra methods for the caller to create the thing.
    If you don't expose an existence check then the caller should implement a try/catch around the main method call just in case they need to make the precursor call. Better to expose the existence check as well so they can make it obvious in their code:

if(!permissionExists("somePermission")
{createPermission("somePermisson",newPermissionName)}
addUserPermission(user,"somePermission")

simon coleman
simon coleman
December 06, 2018 15:04 PM

Related Questions


Updated December 17, 2017 11:05 AM

Updated August 06, 2018 10:05 AM

Updated February 28, 2018 04:05 AM