Tuesday 19 April 2011

Restricted Access Containers (RACs) and the Strategy Pattern

Introduction

Stacks and queues are examples of containers with special insertion and removal behaviors and a special access behavior.

Stack
Insertion and removal in a stack must be carried out in such a way that the last data inserted is the first one to be removed.   One can only retrieve and remove a data element from a stack by way of special access point called the "top".   Traditionally, the insertion and removal methods for a stack are called push and pop, respectively.  push inserts a data element at the top of the stack.  pop removes and returns the data element at the top of the stack.  A stack is used to model systems that exhibit LIFO (Last In First Out) insert/removal behavior.

Queue
Data insertion and removal in a queue must be carried out in such a way that  the first one to be inserted is the first one to be removed.   One can only retrieve and remove a data element from a queue by way of special access point called the "front".  Traditionally, the insertion and removal methods for a queue are called enqueue and dequeue, respectively.  enqueue inserts a data element at the "end" of the queue.  dequeue removes and returns the data element at the front of the queue.  A queue is used to model systems that exhibit FIFO  (First In First Out) insertion/removal behavior.  For example, one can model a movie ticket line by a queue.

We abstract the behaviors of special containers such as stacks and queues into an interface called IRAContainer specified as follows. 

Restricted Access Containers 

package genRac;
import genListFW.*;
/**
* Defines the interface for a restricted access container.
*/

public interface IRAContainer<T> {
/**
* Empty the container.
* NOTE: This implies a state change.
* This behavior can be achieved by repeatedly removing elements from this IRAContainer.
* It is specified here as a convenience to the client.
*/

public void clear();

/**
* Return TRUE if the container is empty; otherwise, return
* FALSE.
* Question: do we really need this method?
*/

public boolean isEmpty();

/**
* Return TRUE if the container is full; otherwise, return
* FALSE.
*/

public boolean isFull();

/**
* Return an immutable list of all elements in the container.
* @param fact for manufacturing an IList.
*/

public IList<T> elements(IListFactory<T> fact);


/**
* Remove the next item from the container and return it.
* NOTE: This implies a state change.
* @throw an Exception if this IRAContainer is empty.
*/

public T get();

/**
* Add an item to the container.
* NOTE: This implies a state change.
* @param input the data to be added to this IRAContainer.
* @throw an Exception if this IRAContainer is full.
*/

public void put(T input);

/**
* Return the next element in this IRAContainer withour removing it.
* @throw an Exception if this IRAContainer is empty.
*/

public T peek();
}
  1. Restrict the users from seeing inside or working on the inside of the container.
  2. Have simple put(data) and get() methods. Note the lack of specification of how the data goes in or comes out of the container.
  3. However, a "policy" must exist that governs how data is added ("put") or removed ("get"). Examples:
    1. First in/First out (FIFO) ("Queue")
    2. Last in/First out (LIFO) ("Stack")
    3. Retrieve by ranking ("Priority Queue")
    4. Random retrieval
  4. The policy is variant behavior --> abstract it.
    1. The behavior of the RAC is independent of exactly what the policy does.
    2. The RAC delegates the actual adding ("put") work to the policy.
    3. The RAC is only dependent on the existence of the policy, not what it does.
    4. The policy is a "strategy" for adding data to the RAC. See the Strategy design pattern.
    5. Strategy pattern vs. State pattern -- so alike, yet so different!(here for difference)
The manufacturing of specific restricted access containers with specific insertion strategy will be done by concrete implementations of the following abstract factory interface.

IRACFactory.java
package genRac;
/**
* Abstract Factory to manufacture RACs.
*/

public interface IRACFactory<T> {
/**
* Returns an empty IRAContainer.
*/

public IRAContainer<T> makeRAC();
}
 

Examples

The following is an (abstract) implementation of IRACFactory using the generic LRStruct as the underlining data structure.  By varying the insertion strategy, which is an IAlgo on the internal LRStruct, we obtain different types of RAC: stack, queue, random, etc. 
NOTE: Due to the limitation of our UML tool, the UML class diagram shown below does not show the generic type of all the classes.


ALRSRACFactory.java
package genRac;
import genListFW.*;import genListFW.factory.*;import genLRS.*;
/**
* Implements a factory for restricted access containers. These
* restricted access containers are implemented using an generic LRStruct to
* hold the data objects.
* Click here for the public methods of the generic LRStruct and visitor.
*/

public abstract class ALRSRACFactory<T> implements IRACFactory<T> {

/**
* Implements a general-purpose restricted access container using
* a generic LRStruct. How?
*
* The next item to remove is always at the front of the list of
* contained objects. This is invariant!
*
* Insertion is, however, delegated to a strategy routine; and
* this strategy is provided to the container. This strategy
* varies to implement the desired kind of container, e.g., queue
* vs. stack.
*
* This nested static class is protected so that classes derived from its
* factory can reuse it to create other kinds of restricted access
* container.
*/

protected static class LRSRAContainer<T> implements IRAContainer<T> {
private IAlgo<T, Object, T> _insertStrategy;
private LRStruct<T> _lrs;

// anonymous inner class to check for emptiness!
private IAlgo<Object, Boolean, Object> _checkEmpty = new IAlgo<Object, Boolean, Object>() {

public Boolean emptyCase(LRStruct<? extends Object> host, Object... input) {
return Boolean.TRUE;
}

public Boolean nonEmptyCase(LRStruct<? extends Object> host, Object... input) {
return Boolean.FALSE;
}
};

public LRSRAContainer(IAlgo<T, Object, T> strategy) {
_insertStrategy = strategy;
_lrs =
new LRStruct<T>();
}

/**
* Empty the container.
*/

public void clear() {
_lrs =
new LRStruct<T>();
}

/**
* Return TRUE if the container is empty; otherwise, return
* FALSE.
*/

public boolean isEmpty() {
return _lrs.execute(_checkEmpty);
}

/**
* Return TRUE if the container is full; otherwise, return
* FALSE.
*
* This implementation can hold an arbitrary number of
* objects. Thus, always return false.
*/

public boolean isFull() {
return false;
}

/**
* Return an immutable list of all elements in the container.
*/

public IList<T> elements(final IListFactory<T> fact) {

return _lrs.execute (new IAlgo<T, IList<T>, Object>() {

public IList<T> emptyCase(LRStruct<? extends T> host, Object... nu) {
return fact.makeEmptyList();
}

public IList<T> nonEmptyCase(LRStruct<? extends T> host, Object... nu) {
return fact.makeNEList(host.getFirst(),
host.getRest().execute(
this));
}
});
}

/**
* Remove the next item from the container and return it.
*/

public T get() {
return _lrs.removeFront();
}

/**
* Add an item to the container.
*/

public void put(T input) {
_lrs.execute(_insertStrategy, input);
}

public T peek() {
return _lrs.getFirst();
}
}
}
 
LRSStackFactory.java
package genRac;
import genLRS.*;
public class LRSStackFactory<T> extends ALRSRACFactory<T> {
/**
* Create a ``last-in, first-out'' (LIFO) container.
*/

public IRAContainer<T> makeRAC() {

return new LRSRAContainer<T> (new IAlgo<T, Object, T>() {

public Object emptyCase(LRStruct<? extends T> host, T... input) {
return ((LRStruct<T>)host).insertFront(input[0]);
}

public Object nonEmptyCase(LRStruct<? extends T> host, T... input) {
return ((LRStruct<T>)host).insertFront(input[0]);
}
});
}
}

LRSQueueFactory.java
package genRac;
import genLRS.*;
public class LRSQueueFactory<T> extends ALRSRACFactory<T> {

/**
* Create a ``first-in, first-out'' (FIFO) container.
*/

public IRAContainer<T> makeRAC() {

return new LRSRAContainer<T> (new IAlgo<T, Object, T>() {

public Object emptyCase(LRStruct<? extends T> host, T... input) {
return ((LRStruct<T>)host).insertFront(input[0]);
}

public Object nonEmptyCase(LRStruct<? extends T> host, T... input) {
return ((LRStruct<T>)host).getRest().execute(this, input[0]);
}
});
}
}
RandomRACFactory.java
package genRac;
import genLRS.*;
/*
* Implements a factory for restricted access containers, including a
* container that returns a random item.
*/

public class RandomRACFactory<T> extends ALRSRACFactory<T> {
/**
* Create a container that returns a random item.
*/

public IRAContainer<T> makeRAC() {

return new LRSRAContainer<T> (new IAlgo<T, Object, T>() {

public Object emptyCase(LRStruct<? extends T> host, T... input) {
return ((LRStruct<T>)host).insertFront(input[0]);
}

public Object nonEmptyCase(LRStruct<? extends T> host, T... input) {
/*
* Math.Random returns a value between 0.0 and 1.0.
*/

if (0.75 > Math.random())
return ((LRStruct<T>)host).insertFront(input[0]);
else
return ((LRStruct<T>)host).getRest().execute(this, input[0]);
}
});
}
}

 





Monday 18 April 2011

What is BPM?

BPM stands for Business Process Management and is a discipline that aims to model, realize, manage, and even simulate business processes that involve both human and system tasks. These system steps might be automated via batch processes, on demand services, asynchronous processes. One key aspect of BPM is the focus on business metrics. Improving revenue, saving costs, improving customer experience, increasing productivity are what it aspires to achieve. Whether or not you explicitly model and manage business processes, they exist in your organization. BPM provides the technology infrastructure to better capture, streamline, and manage the realizations of business processes.
Typically, a visual tool is used to capture process flows which are decoupled from technology constraints and limitations. this rough technology-agnostic business flow can then be translated into an execution flow that will need to take technology choices, scalability, user preferences, integration with front end and back end services. BPM process flows can invoke data services, business services, perform human workflow tasks – delegation, escalation, routing – all within a stateful container.

Sunday 17 April 2011

Making your Java Code Privileged?

The java system code that is part of the JDK is considered God and has all the maximum privileges. For example it can read a system property by default. To easily understand it is better to consider java Applets. An Applet cannot read a system property by default because it belongs to different CodeSource and not in same domain as system code. Recall that the system code has all privileges.

Then what do you need to do for Applet to get that privilege? You need to explicitly grant those security privileges by creating a policy file. In that policy you specify what are all the privileges you are granting.

There is another option also. It is opposite of the above. You say that this code doesn’t require any security policy and it is privileged to do the same (anything) as system code. Do you smell something evil here? This is a risky thing to do. Giving away the security is OS dependent. “Privileged code + malicious user + hole in OS” will be a worst thing to tackle.

Therefore you need to keep the code block as minimum as possible, for which you are going to give privilege. You might require this in the following scenarios :


  • To read a file
  • To read a system property
  • To create a network connection to the local machine
  • To get direct access to files that contain fonts

Making you code privileged -
anyMethod() {
...other java code here...
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
// put the privileged code here, example:
System.loadLibrary("awt");
return null; // in our scenario nothing to return
}
});
...other code continues...
}

AccessController API explains more about java privileged code and examples.



Tuesday 12 April 2011

Null Object Pattern

Intent
The intent of a Null Object is to encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do nothing behavior.

How should it be used in already defined classes in java?

Joshua Bloch in his excellent book Effective Java (2nd Edition) gives advice that you should never return null collection/map/array from your code i.e. instead of such code:

public List<String> returnCollection() {  
//remainder omitted
if (/*some condition*/) {
return null;
} else {
// return collection
}
}

use this pattern:

public List<String> returnCollection() {  
//remainder omitted
if (/*some condition*/) {
return Collections.emptyList();
} else {
// return collection
}
}

So instead of returning the null collection, we are returning a empty list. Similar story goes for array or string. This basically prevents caller of your code to get NPE / Null Pointer Exception while trying to do things like this:
if (obj.returnCollection().size() > 0) {

When to use Null Object Pattern?
  • an object requires a collaborator. The Null Object pattern does not introduce this collaboration—it makes use of a collaboration that already exists
  • some collaborator instances should do nothing
  • you want to abstract the handling of null away from the client
As we saw from examples above, we have a clear idea, that it should be used to avoid NPEs.

Implementation
The participants classes in this pattern are:
AbstractClass - defines abstract primitive operations that concrete implementations have to define.
RealClass - a real implementation of the AbstractClass performing some real actions.
NullClass - a implementation which do nothing of the abstract class, in order to provide a non-null object to the client.
Client - the client gets an implementation of the abstract class and uses it. It doesn't really care if the implementation is a null object or an real object since both of them are used in the same way.

Example of Null Object Pattern
Here is the example - let's assume that you have an application that check whether the user is authenticated:

public class User {  
private String username;
private boolean authenticated;
// remainder omitted

public boolean isAuthenticated() {
return authenticated;
}
// remainder omitted
}

and the code that returns the reference to the User object looks like this:

public User getUser() {  
if (/*some condition*/) {
return user;
} else {
return null;
}
}

This way the code that checks whether our user is authenticated should look like the following snippet:
if (obj.getUser() != null && obj.getUser().isAuthenticated() {  
// allow
}
// remainder omitted

Checking whether the object is null is not only a boilerplate code but it can also give you a lot of bugs e.g. if you forget to check whether the object is null. Also this code doesn't looks clean as well, so we have to think - object is not null , if not it is authenticated. This hampers the business logic, because we have to just see that whether user is authenticated or not.

And here is the Null Object who can help you:

public class NullUser extends User {  

public static final NullUser INSTANCE = new NullUser();

public static NullUser getInstance() {
return INSTANCE;
}

@Override
public boolean isAuthenticated() {
return false;
}

private NullUser() {
}
}

Now the authentication function becomes -

public User getUser() {  
if (/*some condition*/) {
return user;
} else {
return NullUser.getInstance();
}
}

plus cleaner client code:

if (obj.getUser().isAuthenticated() {  
// allow
}
// remainder omitted

I find this pattern very useful and really helpful. With this pattern you can really save yourself a lot of NPEs.

Still the question is whether User should be a class or an interface and then whether NullUser should extend the base class or implement the user's interface. But I will leave this decision for your consideration. In this case we chose to extend the base class though.

Null Object Pattern and other patterns
Null Object and Factory
The Null Object design pattern is more likely to be used in conjunction with the Factory pattern. The reason for this is obvious: A Concrete Classes need to be instantiated and then to be served to the client. The client uses the concrete class. The concrete class can be a Real Object or a Null Object.
Null Object and Template Method
The Template method design pattern need to define an abstract class that define the template and each concrete class implements the steps for the template. If there are cases when sometimes template is called and sometimes not then, in order to avoid the checking a Null Object can be use to implement a Concrete Template that does nothing.
Removing old functionality
The Null Object can be used to remove old functionality by replacing it with null objects. The big advantage is that the existing code doesn't need to be touched.

Conclusion
The Null Object Pattern is used to avoid special if blocks for do nothing code, by putting the “do nothing” code in the Null Object which becomes responsible for doing nothing. The client is not aware anymore if the real object or the null object is called so the 'if' section is removed from client implementation.