‘The Null’ Nuisance

3 February, 2009

While working on enahncements on a project already in production, I had a very interesting conversation. Let me give a brief background – the core architecture is all in place and we need to build in new functionality. Of course, refactoring is being done along the road. In a specific scenario, I got into a conversation with a fellow architect on usage of “nulls” and “null checks”. The theme of the conversation was “Should a method return a null or an initialized instance of the class”. Let me take an example:

There is a service method that connects to a database loading records for all users in the system. In the DAO we are loading the recordset from the database and converting to an ArrayList of DTO (ValueObject). A sample code to map the a DTO generally is:

List<User> users = null;
for(int index = 0; index < recordSet.size(); index++)
{
    User user = new User();
    user.setFirstName(recordSet.getString(“firstName”);
    user.setMiddleName(recordSet.getString(“middleName”);
    user.setLastName(recordSet.getString(“lastName”);    user.add(user);
}

return users;


 

 

 

 

I had an objection to this style of coding. The simple reason being, on the front-end, I had to put a check for null which was un-necessary. Hence, the other classes that were consuming the results had to write the following code:

List<Users> users = loadAll();
if(users != null)
{
    /// do something
}
else
{
    if(users.get(index).getMidleName() != null)
    {
        // show the middle name
    }
    else
    {
        // do not show the middle name
    }
}

Now, consider a scenario with complex objects having lists all down the hierarchy. It means that before we access a property, we will have to provide a null check. Soon, this “do nothing” null check will become a headache. Someone has coded a null propogation somewhere and we can not trace it. We feel the easiest way is to put in a null check. In my given example, I would have my JSP strewen with null checks cluttering my code.

Unfortunately, this will not solve the real problem. A simple solution is to identify the code where a null reference can be introduced and handle it there. The rest will be happy about it.

More importantly, et us pause for a minute and ask ourselves – Is there something that the application can do, with an object refering to nothing? Let us go back to my example and see how is the application going to use the user list. We need the list of the users to display a report for the users listed. If no users are returned, the uer should see “No users exist”. The UI is no sure, what represents  users – a null object or an initialized object with 0 size or an exception. This will mean that the developer consuming the method will have to write these multple conditions for a simple check.

We can do oe of the following: 

 

 

 

 

1. Throwing a business exception that voilates a business logic can be an effective strategy. However, it largely depends on how do you use exceptions in applications. Remember, raising an exception is an expensive operation.

2. Alternatively, you can provide an Empty implementation of the object that can do something useful like logging an info or an error to the log system.

I am not a hugh fan of throwing an Exception, and also because it is expensive, I am exploring the second option. This changes my code to:

List<User> users = null;
for(int index = 0; index < recordSet.size(); index++)
{
    User user = new User();
    user.setFirstName(recordSet.getString(“firstName”));
    if(
recordSet.getString(“middleName”) == null)   // You can also use StringUtils from apache.lang
    {
        user.setMiddleName(“”);
    }
    else
    {

        user.setMiddleName(recordSet.getString(“middleName”));
    }
    user.setLastName(recordSet.getString(“lastName”));    user.add(user);
}

if(users == null)
{
    // throw new business exception
}

// else we return an initialized list.
return new ArrayList<User>();

This will change the UI code to:

 

 

 

 

 

List<Users> users = loadAll();
// code to show the middle name – if it does not exist, it will show up as blank.


The most evident benefits is – “No more if statements for null checks on the UI. Check is being pushed down in the call hierarchy. Hence, multiple methods calling the same method will not have to worry about nulls.”

The most important question is “Is this approach safe?” Nothing ever is. There is no reason for someone to code incorrectly. Of course, we can not on external libraries never to return null references, but when you write your own code, following this approach can lead to a less cluttered application and a better control over source code.

Remember: The approach is not always necessary, just ensure that the null reference should not be catastrophic.


Top 25 Most Dangerous Programming Errors

14 January, 2009

The 2009 CWE/SANS Top 25 Most Dangerous Programming Errors is a list of the most significant programming errors that can lead to serious software vulnerabilities. They occur frequently, are often easy to find, and easy to exploit. They are dangerous because they will frequently allow attackers to completely take over the software, steal data, or prevent the software from working at all.

Read complete article here:http://cwe.mitre.org/top25/#CWE-319


Extract, Transform, Load

14 January, 2009

ETL in computing terminology refers to Extract, Transform and Load process. This is related mostly to data warehousing projects. A ETL framework involves the following three steps:

1. Extract: This is a process to load the data from a data source which could be a database, or a file dump from another system

2. Transform: This step involves, massaging the data to an appropriate form. This may need to to trim down the data or aggregate data from multiple data sources

3. Load: This is the final step, which uploads the data in another data source like database or generate a flat file.

Extract

This first part of the process involves reading data from various data sources databases. The data itself could be in different format. Some of the very commonly used data formats are databases and flat files. In some cases the data sources may also include some non-relational data sources.

Transform

This next step involves application of various rules on the dataset and prepare the data for the next step of Load. Some of the datasets may need very little or no transformation, while there may be other data sources that need very complext levels of transformations to meet the business requirements. Some of the common operations that may be needed here are:

  • Filtering the data set for a subset of records
  • Generating new values based on existing columns (using pre-defined formulas)
  • Splitting of data set into different tables
  • Aggregating data from various data sets

Load

The load phase loads the data in the target. This phase can do various things depending on the business needs. Sometimes the load may need uploading a fresh data set on a incremental basis. In other cases it may require to update an existing dataset

ETL Flow

1. Cycle Initiation: This is the very first step in the ETL process, where you collect all the reference data and validate that the settings provided are correct. This is the initialization phase. If there are errors during initialization, the ERL process fails.

2. Extract: In this step, you read the data from the datasource

3. Validate: Here the data is validated against a pre-defined business ruleset

4. Transform: Apply any transformation rules

5. Stage: This can be categorized a sub set of the transform stage. A business requirement may need us to load the data in a temp space like when we need to aggregate data from more than one data sources. In that case, we use a tamp database to hold the data sets before we can apply transformation.

6. Load: Load the data into final data source.

7. Cleanup: Clean up any temp files / databases.

Challenges

Some of the common challenges are:

  • An ETL process involved considerable complexity and significant problems can come up with an incorrect designed solution
  • Data sets in production can be vastly different than what developers of the system use. This can lead to huge performance bottlenecks
  • These types of solutions grow horizontally which involves adding more data sources either to extract or load. The solutions should be designed to support addition of such data sources with minimal effort

Performance

This is the biggest challenge that any ETL solution has to struggle with. Most often the slowest part of the ETL process is the load phase where we have to take care of the various database structures, integrity of the records and indexes. The transform phase can also lead to some performance bolltenecks if there are needs to perform some extensive data transformations.

Best Practices

Layered Architecture Design

Core Layer: This is the primary layer which holds all the business logic or core processing like Extract, Transform and Load

Job Management Layer: This layer should take care of scheduling jobs, managing queues and other operational activities like activation of tasks, alerts etc

Auditing and Error Handling: This layer should be dedicated to auditing process, logging entries to log files or database. Also, providing error handling support

Utilities: A common layer to provide common functionality across layers

Core Layer

This is the most important layer and holds the most logic. As a good practice, this layer should be divided into three sections, which should be controlled around a commoin Processing logic. Some common components of this layer can be:

1. Controller: These hold the processing logic which co-ordinate the entire ETL lifecycle. They hold the details of the various utilities and invoke them as needed.

2. Readers: These hold logic to read data from data sources like databases and flat files. Their responsibility should be to load the data set and make it available for next phase.

3. Transformer: These components hold the logic for applying transformations to the data. Transformations can be business validations, mappings or other logic.

4. Mappers: These hold the mapping for a transformation. The controller should be aware of the mappings that are to be applied to the loaded data. In most common cases, the framework should make interfaces available to the consumers of the framework to define mappings. The framework (via controller) should consume those mappings

5. Validation: If there are validations needed to applied, these components should be defined individually. Again, in most cases, the framework should make these available as interfaces and concrete implementations would be provided by consumers of the framework.

6. Loaders: These hold logic to load the data into a data source like databases and flat files.

I am not a Subject matter expert on ETL, but hope this helps.


What should I do?

5 January, 2009

Has this question ever crossed your mind? With evolving technologies and framework this is a question I ask myself all the time especially when I have a new project on its outset.

A few weeks back, I started to work on a architecture definition that holds true in most cases. Of course this is going to be on J2EE platform. With this series, I will try to provide my understanding of various available frameworks and comparisons for existing technologies. This series will be in an attempt for me to define a technlogy stack and a taxonomy that I can re-use across projects hoping to get a productivity boost. I am not saying that the stack will not evolve. What I am trying to say is “Be ready!”

Cheers


Need for 3-tier Architecture

21 December, 2008

Last week, I was working to define an architecture for an existing application. When I walked into the room with the prposal the Senior Delivery Manager asked me “Why do we need an architecture? Why can not not use what we already have?” His concern was logical, this shift was going to push his behind schedule. While I spent next 20 minutes explaining him the importance and need of a 3-tier architecture, it dawned upon me that i have done this several times. Only if i have this documented on paper it would save me lot of time.

What is a Layer?

A layer is referred to a logical separation of code. In J2EE world this is referred to generally an independent Java project that holds the logic. A layer is responsible for speaking to other layers in the application providing or extracting information. An example is the Presentation Layer that is responsible for showing data to the user but it has the responsibility of extracting the information from various other layers.

Two-Tier Architecture

A two-tier architecture is represented when all the code for extracting data from the database and presentation logic i.e. show data to the user resides in the web layer itself. Some definitive advantage of this approach is that it is handy and provides rapid development. However, this approach has some obvious dis-advantages:

  • Putting all the code in the web layer makes if difficult to maintain. 80% of the time of the application life cycle is spent during maintenance and support. Having unmanageable code only makes matters worse
  • Code reuse is not possible. Many a times with changing needs, organization decide to change the application front-end of the presentation. At times, they decide to add some other add-ons. With code sitting on the web layer makes this impossible. Hence, the application can not be scaled
  • Relying on data source (JDBC) controls makes things more complex.

How do we solve this problem is by introducing a 3-tier architecture which abstracts the code based on logical groupings i.e. Data Access, Business Logic and Presentation Logic. This could be a slow process to start with, but has many advantages in the long run.

Hope this helps.  Soon, I will post about the 3-tier architecture and talk about its benefits.


Java Collections | Performance Benchmark

21 October, 2008

Managing list or collection of objects is a very common scenario. In addition, managing that list effectively, that provides the optimum performance is also a very common need. The Java programming language offers many in-built data types for representing and modeling collection of objects. Some of the commonly used data types are:

java.lang.ArrayList

java.lang.HashSet

java.lang.TreeMap

 

Each of the data types behave differently under different scenarios. In addition, when writing algorithms that demonstrate highest levels of performance it is necessary to make the right choice. For many developers and architects it is not an easy choice.

This document provides details of a comparison done across various data-types supported by Java Collections Framework. In addition, it will study their performance under different circumstances.

Final complete analysis in the java-collections-performance-evaluation document.  Dowload PDF.


Singleton – Boon or a Sin

20 April, 2008

Over last few weeks, I have faced quite a few issues with Cairngorm’s Singleton pattern and I decided to put forward a post that should help in making some decision. While I found a few articles about Singletons, but not even one that talks about how should we use Singletons.

Ask any programmer, and they will instantaneously discourage you with the use of global data (objects). But, many a times when you find a need where you have to have some objects available globally and also need a single point of access example: User’s state, permissions which has to be retrieved globally across the user session. And, it is then when you use the design pattern singleton.

When is a class really a Singleton?

Ask yourself:

  • Will every application use this class exactly the same way?
  • Will every application ever need only one instance of this class?
  • Should the clients be unaware of the application that this class is part of?

If you can answer all the above as a Yes, then you found a singleton – remember your Logger / Logging classes. Thats what you need as a singleton.

Now, let us switch focus to Flex, and how can we make use of a Singleton. As we all know that Flex is all about Events and thats how any two components interact wit each other. Singletons here become very handy, as you can dispatch en event on a Singleton Event Dispatcher and the component who needs to listen to it, can easily be listening on the Singleton. Solves many of our problems. Huh!! does it? I am putting down some code for the Buttons (which I am treating as a component). Try executing this code, and you will find that when you click on any one of the buttons, both the buttons handle the event and show and alert twice.

In my next article, I will explore the issues of Singleton with Cairngorm.