Wednesday, February 24, 2016

Funtastic Birthday with Haskell

Hey, it's my birthday today so I think it's good time for something less serious and just fun. Couple of folks asked me about my age today and since I anticipated the question I decided to answer with a small mathematical puzzle: my age is the smallest integer that is divisible by 11 and is a successor of a prime number. By successor of a number s I mean s+1.

I was curious though as to what is the next number that satisfies the above condition. So I decided to write a program in Haskell - my favorite functional language - to generate the sequence:

I won't dissect it too much - after all I promised this would be fun - so let me just point out one little fact about Haskell that I always find fascinating: it lets you define and use infinite sequences like the birthday numbers above. In fact, if you try to evaluate this sequence your machine will start producing the numbers but it would never stop - that is if it had unlimited amount of memory.

The beautiful trick is that once you have an infinite sequence, you can extract portions of it to get answers to finite questions, like my tiny age puzzle - which can be answered by taking the first element of the sequence:
So how optimistic would it be to hope to experience another birthday that satisfies the condition? According to wikipedia the highest verified age ever attained is 122 - so we can just check for "birthday" numbers up to this age:
*Fun> takeWhile (<=122) birthdayNumbers
[44,110]
As you can see, the answer is 'very optimistic' :-)
If you just simply want to see the first 10 numbers of the sequence you can do:
*Fun> take 10 birthdayNumbers
[44,110,132,198,242,264,308,374,440,462]
You may also be wondering, why not make the program even shorter by dropping the isqrt function and instead checking the divisors up to k-1? The reason is obvious: performance. I leave it to the inquiring reader to see the difference for themselves. This is how you can turn on the built-in profiling in the Haskell interpreter and calculate the gap between the consecutive birthday numbers:
*Fun> :set +s
*Fun> take 10 (zipWith (-) (tail birthdayNumbers) birthdayNumbers)
[66,22,66,44,22,44,66,66,22,110]
(0.02 secs, 3042172 bytes)
One final thought: there are actually two ways to solve the puzzle I've given to the curious inquirers:

  1. exact: verify the predecessor primality for all multiples of 11 until you find the solution
  2. heuristic: since I was giving the puzzle in a face-to-face talk it was much easier to estimate my age then compare it with the nearest multiples of 11 and rule out 33 and 55 as being too low / too high respectively.
Now which is the best way? It really depends - do you need to get the correct answer 100% of the time? Or do you need to be really fast while you can tolerate an occasional mistake? In computing, as in life, it's up to you to make your choices :-)

Sunday, February 8, 2015

Color Bash Prompt for Git on Linux/Mac

If you use a bash prompt often then it really helps to highlight the information that matters for you most. For my professional git usage I care about these pieces of information:
  • the current working directory
  • the name of the git branch (if the current directory is a git working copy)
  • whether or not there are uncommitted changes

The above prompt is produced with this one-liner:

Prompt Contents

Let's first dissect the parts of the prompt that define what it actually shows:
  • \w - this is the bash shortcut for current working directory. Simple.
  • $(git status -s 2>/dev/null | head -1 | sed 's/.*/ */') - this will print an asterisk if the current working directory is a git working copy and if it has uncommitted changes (this can be also achiewed with __git_ps1 and
    GIT_PS1_SHOWDIRTYSTATE but I prefer to highlight the asterisk with different color)
  • $(git rev-parse --abbrev-ref HEAD 2>/dev/null | sed 's/.*/ &/') - this will print the branch name with a space in front of it

Prompt Colors

The prompt uses ANSI escape sequences to change the colors. I decided to use tput to generate the sequence instead of putting it in directly. It is simply more readable with explicit capability names. Here setaf sets the foreground color and sgr0 resets all attributes. You can check the man page terminfo(5) if you need for more details.
Finally, it is necessary to mark the ANSI escape sequences as non-printable in order for bash to correctly figure out the actual length of the prompt. This is done by adding \[ and \] around the control characters.

Monday, September 22, 2014

Create a Flickr Application hosted on the Google App Engine

How I got here

At the start of the last NHL season I got myself an AppleTV to watch the games via my Gamecenter subscription. However, the AppleTV turned out to be much more versatile. Now I am using it also to stream videos from an iPad to the TV, listen to the iTunes Radio and also to watch a slideshow of our family photo library, a feature the whole family loves.

The photos are hosted on Flickr and due to the Flickr API restriction you can have at most 500 photos in the slideshow. This didn't make me happy as our photo library has several thousand pics. I did not find any satisfactory solution on the net so I decided to:
  • create an application to periodically generate a random Flickr photo set
  • host the application in the cloud to avoid dependency on the home IT infrastructure
In the following I'll describe how I got this done and share the project that contains the working code.

Connecting to Flickr

If you want to get an application work with Flickr (if you only came here because you are interested in the Google App Engine you may jump right to the next section) you have to follow these steps:
  1. Register your application in the Flickr App Garden. This will get you an API key and a shared secret that you will need later to make the REST API calls.
  2. If your application needs authentication then you also need to obtain authorization from a Flickr account owner. Whether you need authentication depends on what the application is doing. Some Flickr API calls require no authentication - for instance the method flickr.people.getPublicPhotos. The app described herein needs authentication since it creates a photo set in my Flickr account. See Authentication How-To for more information.
  3. Make REST API calls to the Flickr API. You will need to sign the requests as described in the above Authentication How-To. You can see the example implementation in the method FlickrService.addSignedParams.
That's it! The application will talk to Flickr and create the desired photo set when the main servlet (PhotosetServlet.java) is invoked.

Hosting the Application on the Google App Engine

Choosing the hosting provider was a no-brainer since the Google App Engine comes with a free plan which is fully sufficient for this Flickr application. It is worth noting that the Google App Engine is a PaaS offering which means it provides the platform that your application runs on. Besides Java, which I chose for this Flickr application, the platform also supports Python, PHP and Go. The platform also supports couple of options for storing data (a proprietary data store, a cloud MySQL database and a large object storage).

If you require a specific infrastructure, like for instance a specific database server, then you should be probably looking at an IaaS offering instead.

To create a Java application for the Google App Engine you simply follow the steps from the Getting Started Guide. Here's a quick overview with links into the corresponding guide sections:
  1. Sign up for a Google account (unless you already have one).
  2. Create a project from the maven archetype appengine-skeleton-archetype — see Creating the Project.
    Tip: you can also create a project ID later, just before the first deployment to the Google App Engine (see step 5 below).
  3. Add the code for your application — see Adding Application Code and UI.
  4. Test the application locally using mvn appengine:devserver — see Building and testing the app
  5. Deploy your application to the Google App Engine — see Uploading your Application
These are also the steps that I followed to create the photo set application. To enable scheduling I added the cron.xml file and I thought I was done.

Final Hurdle

Soon after the deployment to the Google App Engine I noticed I'm actually not done yet. The app was working fine locally but an attempt to create the same 500 picture photo set on the Google App Engine resulted in a Malformed URL exception. The problem is that the GET request receives the list of the photo IDs in the URL which gets truncated if the list is too long.

I wasn't able to find a solution until I went to Bucharest where I met my friend and former colleague Octavian. He hinted to use a different HTTP client which ultimately solved the issue. Ironically I've just found out while writing this post that according to the Flickr API documentation I should have used a POST request instead!

Conclusion

I hope this post was helpful for you if you are either developing a Flickr application or working with the Google App Engine. Both topics are actually quite big to be covered in a single post. Nonetheless, with the help of the code example and the provided documentation it should be relatively easy to get going - have fun!

Saturday, March 1, 2014

Unit Testing Java EE Application with CDI

Java Enterprise Edition has undergone the much needed weight loss treatment in 2006 when Java EE 5 was introduced and it has continued evolving ever since. Today, developing of Java enterprise applications is easier than ever before. However, the rising popularity of Test Driven Development creates new challenges even for the revamped Java EE platform.

Things have improved, of course. Prior to EJB 3.0, there was virtually no other way of testing enterprise beans than actually deploying them in the container and testing them there.

The EJB 3.0 returned back to the roots by turning the enterprise beans into Plain old Java objects (POJOs). This revolutionary idea brings many advantages, one of them is making EJBs readily available to unit testing. You only have to mock the dependencies to the container.

The question arises though, how do you unit tests those parts that directly depend on the container, like the Data Access Objects (DAOs) which use container provided persistence services?

In this post, I will show on an example of a RESTful Web Service project with database persistence how it can be tested end-to-end without ever hitting the application server.

The Project
The example project contains the following RESTful Web Service and DAO to put under (unit) test:
 @Path("/employees")  
 public class EmployeeResource {  
     @EJB  
     private EmployeeDao employeeDao;  
   
     @GET  
     @Path("/{param}")  
     @Produces(MediaType.APPLICATION_JSON)  
     public Employee get(@PathParam("param") long id) {  
         return employeeDao.find(id);  
     }  
     @GET  
     @Produces(MediaType.APPLICATION_JSON)  
     public List<Employee> findAll() {  
         return employeeDao.findAll();  
     }  
     @POST  
     @Consumes(MediaType.APPLICATION_JSON)  
     @Produces(MediaType.APPLICATION_JSON)  
     public Map<String, Long> add(Employee employee) {  
         Map<String, Long> response = new HashMap<>();  
         response.put("employeeId", employeeDao.create(employee));  
         return response;  
     }  
 }  
 @Stateless  
 public class EmployeeDao {  
     @PersistenceContext  
     private EntityManager em;  
   
     public Employee find(long id) {  
         return em.find(Employee.class, id);  
     }  
     public List<Employee> findAll() {  
         return em.createNamedQuery(Employee.FIND_ALL).getResultList();  
     }  
     public long create(Employee employee) {  
         em.persist(employee);  
         return employee.getEmployeeId();  
     }  
 }  
Injecting Dependencies
The above classes are richly annotated. A naive attempt to test the classes with JUnit will succeed to compile but it will fail at runtime with a NullPointerException due to unresolved dependencies to EmployeeDao and EntityManager. So is there a way to resolve these dependencies outside of the application server?
Enter CDI — context and dependency injection. CDI was added in Java EE 6 as a general dependency injection mechanism. With CDI it is possible to annotate references to EJBs with @Inject instead of @EJB:
 public class EmployeeResource {  
     @Inject  
     private EmployeeDao employeeDao;  
 ...  
This solves the DAO dependency nicely. However, the reference to the DAO will still be null because JUnit tests run with Java SE which does not support CDI. By now you can probably guess the central idea of the approach described in this post — to run the tests inside a CDI container instead of an application server. In the example project I use the JBoss Weld CDI container with Apache DeltaSpike which provides an abstraction layer to bootstrapping the container. You can inspect the project's Maven pom.xml file to see the actual library dependencies.
How about the dependency to the EntityManager though? It is defined as a private field in the DAO class and it has to be set outside of the application server. Is there some way to do it, short of breaking the encapsulation?
Actually, the solution is simple if you think of the famous aphorism by David Wheeler:

All problems in computer science can be solved by another level of indirection.

The indirection is implemented, of course, with CDI. The DAO uses an @Inject annotation instead of @PersistenceContext:
 public class EmployeeDao {  
     @Inject  
     private EntityManager em;  
 ...  
The definition of the entity manager in production/application server environment moves to a resource class which defines a CDI producer:
 public class Resources {  
     @PersistenceContext  
     @Produces  
     private EntityManager em;  
 }  
In the test environment an alternative resource class is used:
 @Alternative  
 public class TestResources {  
     @Produces  
     @Singleton  
     private EntityManager createEntityManager() {  
         EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr_test");  
         return emf.createEntityManager();  
     }  
 }  
There are two things to notice about the above class:
  1. It is annotated with @Alternative. The alternative needs to be activated by specifying an <alternatives> tag in the beans.xml file. There are two beans.xml files in the example project — one in the production source code base (without <alternatives> tag so the persistence context is resolved using the Resources class) and another one in the test source code base.
  2. The above class creates an entity manager factory for the persistence unit hr_test. Alike beans.xml, there are also two persistence.xml files, for production and test respectively, in the example project.
Writing Test Classes
The test classes also use CDI to resolve the references to the classes being tested:
 @RunWith(CdiTestRunner.class)  
 public class EmployeeResourceTest {  
     @Inject  
     private EmployeeResource employeeResource;  
   
     @Test  
     public void testFindAll() {  
         List<Employee> employees = employeeResource.findAll();  
         assertThat(employees.size()).isGreaterThan(25);  
     }  
 }  
Bootstrapping the Container
Since the test classes are managed by CDI they need a custom JUnit test runner (specified with @RunWith) that has two responsibilities:
  1. Bootstrap the CDI container.
  2. Create instances of test classes using the CDI container.
 public class CdiTestRunner extends BlockJUnit4ClassRunner {  
     static {  
         CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();  
         cdiContainer.boot();  
     }  
     public CdiTestRunner(Class<?> clazz) throws InitializationError {  
         super(clazz);  
     }  
     @Override  
     protected Object createTest() throws Exception {  
         return BeanProvider.getContextualReference(getTestClass().getJavaClass());  
     }  
 }  
Adding Transaction Support
Transaction service is another service typically provided by the application server. In the standalone CDI test environment it is easy to add transaction support using an interceptor. The test methods are annotated with @Transactional and they can also specify whether the transaction should commit or rollback when the test finishes:
 @Test  
 @Transactional  
 public void testCreate() {  
     final long employeeId = 401L;  
     Employee employee = new Employee(employeeId, "PKANE", "PR_REP", "Kane", new Date());  
     assertThat(employeeDao.create(employee)).isEqualTo(employeeId);  
 }  
   
 @Test  
 @Transactional(defaultRollback = false)  
 public void testCreateCommit() {  
     final long employeeId = 402L;  
     Employee employee = new Employee(employeeId, "JTOEWS", "PR_REP", "Toews", new Date());  
     assertThat(employeeDao.create(employee)).isEqualTo(employeeId);  
 }  
 @InterceptorBinding  
 @Target({ElementType.METHOD, ElementType.TYPE})  
 @Retention(RetentionPolicy.RUNTIME)  
 public @interface Transactional {  
     boolean defaultRollback() default true;  
 }  
 @Interceptor  
 @Transactional  
 public class TransactionalRollbackInterceptor {  
     @Inject  
     private EntityManager em;  
   
     @AroundInvoke  
     public Object manageTransaction(InvocationContext ctx) throws Exception {  
         try {  
             em.getTransaction().begin();  
             return ctx.proceed();  
         } finally {  
             em.getTransaction().rollback();  
         }  
     }  
 }  
 @Interceptor  
 @Transactional(defaultRollback = false)  
 public class TransactionalCommitInterceptor {  
     @Inject  
     private EntityManager em;  
   
     @AroundInvoke  
     public Object manageTransaction(InvocationContext ctx) throws Exception {  
         em.getTransaction().begin();  
         Object result = ctx.proceed();  
         em.getTransaction().commit();  
         return result;  
     }  
 }  
Conclusion
That's it. If you want to check the entire example project's source code, you can find it in Subversion or download it as a zip archive.

Bonus Picture
As I was taking a break while writing the example project, our cat leapt on the table and took a sharp look on the source code, as if she was reviewing it. I was lucky enough to have my camera at my fingertips and I captured the moment:
Links

Thursday, February 20, 2014

Display Busy Mouse Cursor with PrimeFaces during Ajax Requests

Today, I want to share a solution for displaying a busy cursor while an Ajax request is active in a PrimeFaces application. The solution is strikingly simple once all the pieces click in, but it took me some good amount of research and try and error, so I decided it is worthwhile to post it here.

The journey starts with a simple CSS which defines the busy cursor:

 // <web-app-root>/resources/css/progress.css
 html.progress, html.progress * {  
  cursor: progress !important;  
 }  

The above is based on this forum post - you may want to check it out for more details or if you wish to use the original solution. The solution I went for is slightly different - it uses JavaScript with the following self-explanatory functions:

 // <web-app-root>/resources/js/progress.js
 var handle = {}  
   
 function on_start() {  
     handle = setTimeout(function() {  
         $('html').addClass('progress')  
     }, 250)  
 }  
   
 function on_complete() {  
     clearTimeout(handle)  
     $('html').removeClass('progress')  
 }  

Note that the progress class is not set immediately when the request starts. I found it very distracting when the cursor "flashes" on short Ajax requests and I decided to change the cursor after a delay of 250 ms only. Of course, you may modify the delay as you see fit (or maybe make it an argument of the on_start function). The clearTimeout call is needed to cancel the delayed cursor change when the Ajax request is completed before the delay expires.

Now to activate the solution you only need to include the following in your JSF page:

 <h:outputStylesheet library="css" name="progress.css" />  
 <h:outputScript name="js/progress.js" target="head"/>  
 <p:ajaxStatus onstart="on_start()" oncomplete="on_complete()"/>  

Final note: for the above inclusion to work you must also have an <h:head/> tag on your JSF page.

Monday, November 11, 2013

Using JPA in SCA Spring Beans


When using  Oracle SOA Suite 11g SCA Spring Bean components you will likely be facing a decision about how to interact with your database from within the Spring Beans. The answer will ultimately depend on your overall system architecture. For instance you may wire a Spring Bean directly to a DB adapter, or you can encapsulate the data access inside a web service or an EJB session bean. In my last project we have decided to access the data directly from the Spring Beans, taking advantage of the flexibility provided by Spring's JDBC abstraction framework. In fact Spring makes JDBC access so simple that it is easy to miss other alternatives, one of them being especially noteworthy - the Java Persistence API.

Java Persistence API has greatly simplified the object-relational mapping in Java. Let's have a look at how JPA can be incorporated into an SCA application.

The Service
We will create a simple service inspired by my other passion, motorcycles. The service will provide these operations:
  • createBike - creates an entity for a motorcycle with the specified manufacturer and model name and returns the entity's ID.
  • getBikeDescription - retrieves the description of a motorcycle with the specified ID.

The Project
We start with an empty composite project and add a Spring Bean, following the code-first approach:
  1. Create a Java interface for our SCA service: MotoService.java
  2. Create a dummy implementation of the above interface MotoServiceImpl.java.
  3. Create a Spring Context which uses the classes created in the above steps.


  1. Wire the Spring Context to the Exposed Services lane - this step will generate MotoService.wsdl.

That's all we need for now, the next step is to add JPA artifacts to the project.

JPA Artifacts
To enable our SCA project for JPA, we follow these steps:
  1. Add two predefined JDeveloper libraries to the project dependencies: EJB 3.0 and TopLink.
  1. Create the entity class: Bike.java. Note that the class is not Serializable - it does not need to be (more on the topic here). The DDL to the create the SQL objects for the Bike entity is in create_tables.sql.
  2. Create the DAO class: BikeDao.java. Note that the EntityManager field does not have the usual @PersistenceContext annotation. This is because we will use Spring Bean wiring to inject the property (see section Configure the Entity Manager below).
  3. Create the JPA persistence definition: persistence.xml. If you plan on running the example project in your environment you will need to modify the jta-data-source property to match a JNDI data source configured in your WebLogic server instance.

Wire the Spring Bean to JPA
Now we can wire the JPA classes to the service Spring Bean:
  1. Change the MotoServiceImpl.java implementation to use the DAO.
  2. Add the BikeDao property to MotoSB.xml:
Configure the Entity Manager
Now we need to configure the entity manager by explicitly injecting it to the DAO class:
We use LocalContainerEntityManagerFactoryBean to obtain the entity manager factory. The factory's persistenceUnitName  property refers to the persistence unit defined in persistence.xml.
Since we need to inject an entity manager to the DAO class, we use a SharedEntityManagerBean to create an entity manager from the entity manager factory. If you try to create the entity manager programmatically - by calling the factory's createEntityManager method, as I did :-) - the entity manager will not bind itself to the transaction and as a result, the database changes will not be committed.
For more information on integrating Spring with JPA see the Spring documentation.

Configure Transactions
Finally, we will declaratively enhance the service Spring Bean with the transaction behavior - by using a
TransactionProxyFactoryBean wrapper:
Note that the above approach gives you full control over the transaction behavior of the Spring Bean component. This is much more flexible than the transaction semantics of BPEL and Mediator components.

Deploy and Test
That's it. The project is now ready to deploy and test. I tested with soapUI (project available here) by creating an entry for my favorite motorcycle (KTM Enduro 690R) and retrieving its description afterwards.
Conclusion
In the above I have shown how to integrate JPA with SCA Spring Beans. The ability to use JPA makes Spring Beans a great alternative to another SCA components which are limited to data access via a DB Adapter or an encapsulated service. As a matter of fact, you can add pure data access Spring Beans to your toolbox and use them to facilitate data access from another SCA components. Choosing the right SCA component type is a topic in itself and it has been addressed in this excellent blog of my former colleague Alex Suchier.


If you want to try the Spring Bean JPA integration for yourself, you can get the project fromSubversion or download it as a 7-zip archive.

Saturday, September 14, 2013

Oracle Business Rules 11g - Best Practices for Decision Tables

Oracle Business Rules is a lightweight and powerful rules engine that is part of the Oracle SOA Suite. It supports two fundamental ways of entering the rules:
  • an IF/THEN form which is the intrinsic form of rules in any production rule system
  • a decision table - a spreadsheet-like form that will appeal a business savvy user

While Oracle does a pretty good job on documenting the decision table features - Working with Decision Tables - there is much less information available on how to actually design the decision tables.

In this post, I want to share my experience with the decision tables and describe what I consider the best practices in using them. I am looking forward to your feedback in the comments section.
  
Have a Case
The first and foremost question you should be asking yourself before you create a decision table is, "is the decision table the right vehicle for this job?". Sometimes this may be a no-brainer - like when your customer gives you a spreadsheet that neatly translates into a decision table. Other times the choice may not be that obvious.

Let's have a look at an example. Imagine a company that grants a company car to an employee if any of the following applies:
  • The employee's job level is expert and the employee has been at least 3 years with the company
  • The employee's yearly salary is at least 65,000 USD and the employee was hired before Nov 1, 2008
  • The employee's job title is Sales Rep

It is questionable though whether a decision table is a good fit here. While it is still appealing thanks to its visually comprehensive layout, a solution with IF/THEN rules is going to be simpler and cleaner, especially if the number of rules increases in the future.
Now lets take a look at another imaginary company car policy:
  • All employees in the Sales department are entitled to a company car.
  • Employees in the Executive department are entitled to a company car if their job level is intermediate or expert.
  • Employees in the IT department are entitled to a company car if their job title is Architect and their job level is expert.

Even though this policy has the same number of  conditions as the first one, it yields much more concise and coherent decision table. Why is that? The first policy uses disconnected conditions which do not blend very well into a decision table. The second policy has conditions shared by most of the rules which differ only by the condition input values.

My advice is to consider the structure and size of your to-be-implemented rule set, then take a mental picture of the decision table solutions and compare it to the IF/THEN rule solution.

Only use a decision table if it gives you an advantage compared to an IF/THEN rule solution.

Be Accurate
I mentioned above that you may get a spreadsheet from your customer that translates neatly into a decision table. In reality though, it's rarely that simple. More often than not, the specification will contain a few stumbling blocks. I once received a spreadsheet from the customer that contained two overlapping conditions which were supposed to yield opposite results. The good news is, if you accurately translate your specification into a decision table, the logical flaws in the specification will pop up as conflicts or gaps. This way the implementation can actually help improve the specification - isn't it amazing? On top of that, the more your decision table resembles the specification, the easier it will be to implement any future specification changes. For all above reasons:

Make your decision table match your specification as closely as possible.

Be Complete
When you look at either of the above decision tables, you will notice that they capture only the cases when the company car privilege is granted to the employee. I did it on purpose to keep the tables as simple as possible. In my experience the real world specification also tends to come that way - as an enumeration of cases when something happens or applies - rather than as a full list of all eventualities. Yet it pays off to consider all possible cases - and there is a nifty tool built in the Rules Designer that does exactly that - the Gap Analysis.

  
The above picture shows the gap analysis for the decision table implementing the second company car policy. I like to see it as an inverse version of the original decision table - as it is covering all the cases when the company car is not granted. It is very useful to examine the gaps to verify the completeness of a decision table. For instance, the fact that the Finance department is missing from the rules in our example may be a hint that the specification is incomplete (unless the company really hates their finance folks).

You may also choose to have the gaps automatically filled in - this is how I created the following gapless decision table from the original one:


Even when I choose to allow gaps in a decision table, I still employ the Gap Analysis to check that no eventuality has been overlooked.

Gap Analysis is your friend - seek its advice whenever you create or change a decision table.

Divide and Conquer
I bet you've seen this before - a source code method or function in your favorite programming language that spans across hundreds of lines. This is the infamous Taller Than Me anti-pattern. Unfortunately, decision tables are not immune to a similar anti-pattern. It is created by the same evil code-supersizing forces, but as a decision table tends to grow wide as more rules are added into it, let me dub it "Wider Than The Sky".

If you have to scroll horizontally to see all of your decision table, it's probably a good idea to split the table into several smaller partitions. To illustrate this, let's imagine that our fictitious company determines salary raises for its employees based solely on their job title and the last performance rating:


Huh? You can't see a thing? That's right - the table has grown too wide! Arguably the best refactoring  in this case is to have a dedicated table for every job title - here are two examples (check out the project from Subversion if you want to see more):



 Avoid creating decision tables that are Wider Than The Sky.

Be Consistent
The bucketsets used in decision tables can be defined either locally or globally. It may be tempting to quickly hack a local bucketset with just few values that you need (for example if a condition needs to check for two specific departments only), however in my experience you are almost always better off with a global bucketset that contains a complete list of values. The reasons are threefold:
  • Gap Analysis is less reliable with partial bucketsets.
  • It is very confusing when multiple local bucketsets with different sets of values are defined for the same entity.
  • If you create a local bucketset, you will face rework if you need to add another condition for the same entity later.

 Avoid local bucketsets unless you have a really good reason to use them.

Control the Conflicts
If a decision table has overlapping rules that yield different results it will be marked as a conflict. Note that the decision table from the very first example has overlapping rules but there is no conflict as the corresponding actions do not differ.

This is the reason why you should avoid unnecessary stuff in your decision table actions. For many years I believed that it is a good practice to add a print action to debug which rule was actually fired. Now I don't think much about it as it is:
  • Creating unnecessary conflicts
  • Obscuring the business meaning of the rules
  • Completely redundant - the rules that fired can always be tracked by other means (the server audit trail, test rule  function or explicitly by calling RL.watch.rules) 

If you do have a genuine conflict though, it's time to check your specification. If you modeled the rules closely to the specification, as I advocated in the Be Accurate section, then actually the specification itself must have a conflict. Your next course of action then depends on how the specification is fixed:
  • A business user may fix the rules in the specification which in turn means a refactoring of the decision table.
  • A business user may prioritize the conflicting rules - which is best implemented as manual conflict resolution.
    • As a special case, a business user may implicitly assume that a more specific rule has higher priority than a less specific one. That's actually quite reasonable and it is supported by the Rules Designer as the auto override conflict policy. You just need to understand your business' assumptions or even better, let them articulate the assumptions explicitly.

For details on manual and auto override conflict resolution see Understanding Decision Table Conflict Analysis.

Avoid conflicts in a decision table by keeping the action part uniform for overlapping rules. For genuine conflicts let the specification drive the decision between conflict resolution and refactoring the decision table.

Conclusion
I hope you find the above useful. If you have already developed your own best practices I'd be happy if you leave a comment and share how they compare with these. If you want to try the examples, you can get the project from Subversion or download it as a 7-zip archive.