Privileged API

From APIDesign

Revision as of 17:00, 25 May 2009 by JaroslavTulach (Talk | contribs)
Jump to: navigation, search

When designing a library and its API, you often do not talk only to one audience of users, but to multiple groups. For example one group shall be allowed to create objects, other group shall just query their state. In some sense the first group has more privileges, just like a server administrator can change content of a website, while regular uses can only view its HTML pages.

This topic has been deeply discussed in section Give the Creator of an Object More Rights in Chapter 5. You can also listen to API Design Tips podcast dedicated to Privileged API: , download.

Use Constructor or Factory Methods

The basic trick to achieve privileged mode is to force initialization of certain attributes of an object only during its creation and prevent changing them later. As an example consider a simple lock implementation:

does not exists: mutex.api

The readAccess method takes a Runnable which ensures that everyone who acquires the lock also releases it. This is more suitable method for public consumption in Cluelessness mode then pair of lock/unlock methods. One just cannot forget to unlock:

does not exists: mutex.use

However (and we found that in NetBeans APIs), when used frequently there may be too many temporary Runnable objects being created. This may hurt performance and as such one may want the lock/unlock pair of methods to be available to those who can be trusted to use it correctly. This can be done with following addition to the API:

does not exists: mutex.privileged.api

The Privileged class then serves as a handle which the creator of the Mutex instance may keep reference to:

does not exists: mutex.init

and use it for privileged access, while everyone else keeps access to the safe Mutex method. So creator can call:

does not exists: mutex.privileged

Regular users have to rely on old good readAccess. This is one way to create API for privileged use. There are other as discussed in Chapter 5.

<comments/>

Personal tools
buy