Friday, April 25, 2014

Configuring Aspect With Spring AOP

tl;dr Using AOP involves you identifying cross cutting concerns (Advice), extracting them out into a separate module and have them called at certain points in your code execution (Join Point) using certain expressions (Point-cut) to select these points where you want your cross cutting concern logic to run. Configuring thus involve telling Spring where your extracted logic is and the point-cut required to know where to apply them.

This post is part of the Configuring Spring Series.

Develop a sizable application and you would soon find yourself repeating some operations: certain logic; function calls that keeps recurring now and then. An example of such a recurring operation is logging. At different places, through out your application, you may find the need to have some information logged; either for debugging purposes or for auditing or for whatever reasons logging was invented. After a while you would soon find out that the log calls are sprinkled about the place in your code base. The drawback of having code scattered this way is even more if the code being repeated is not as trivial as log calls; Not good.

I have worked on a code base where this was the case. This is generally not advisable for various reasons: One, it fast become tedious having to repeat the same boring logic over and over again. Two, it leads to code entanglement as you have the flow of business logic being interrupted by mundane things that does not add to the business logic at hand. Third, it leads to code scattering. Same logic scatted all over the place. Even though the logic might be encapsulated into a method or function call, the method or function call would still be scattered all about the place. Not too good.

The explicitly of having to repeat these recurring calls might seem like a good thing, but with scale, it becomes not that much of a good thing.

Would it not be nice if it were possible to extract out, these recurring method calls, have it in some sort of separate module and then have it magically called when those operations that require them are reached during your code execution?

These kind of problems/situations is what Aspect Oriented Software Development seeks to solve/mitigate with Aspect Oriented Programming. It allows you to extract operations that cut across different aspect of your application and have them called when needed.

These kind of operations are usually called cross-cutting concerns, because, well they cut across various concerns in your application. :)

Apart from logging, operations that you would most likely run into, that can easily be classified as being cross-cutting concerns includes: Authorization, Error Handling, Performance Monitoring etc.

This post describes the process of configuring Spring framework in other to be able to use AOP in your application. As you might have guessed, the topic of Aspect Oriented Programming is a very broad one. And since these posts are mainly focused on configuration activities in Spring, I would not go into details of programming with Aspects; but instead explain basic concepts needed to get started and provide an overview of how AOP can be configured in Spring Application.

If you are familiar with event driven languages like Javascript (or any UI framework in most languages), you won't be totally wrong if you think the concept of Aspect sounds very familiar to what you do when you define functions as event handlers. And with event delegation, you can have this function registered to be executed when certain operations/event occurs within your application. The same reason why doing this makes sense also applies to why Aspects are recommended.

So let's get started with some of the basic concepts.

Saturday, April 19, 2014

A Tale of Bicycles, Complex and Stereotypes

"You Africans please listen to me as Africans...and you non Africans, listen to me with open mind"

So began Fela Anikulapo Kuti in Shuffering and Smiling before he lunched into a musical rendition that describes a reality only mostly Africans might be able to relate with...

And in that same spirit, I write this post...

Of late I have become more acutely aware of certain thought patterns the social system I live in has unconsciously etched in my mind. And it reeks of acceptance of stereotypes and of inferiority complex.

I would explain with a story involving bicycles...

You Nigerian? Do you remember when one transport minister proposed the idea that we should all start riding bicycles?

I remember and I remember my reaction to it. It was that of disgust, disdain and incredulity.

Why? my God, we are in the twenty something century! Keke? This guy wants to take us to the stone age! Why do these leaders like to make us look so backwards! Imagine! Just look to the "developed countries" (whatever that means)...they have moved past riding bicycles! This dude wants to take us back! Uncivilized, uneducated baga! So we would now be the backward African country these "developed people" would now start looking down on as the place where everybody rides bicycles: the primitive transportation machine? How do these people get to become leaders sef...?

State of mind? Disdain!

Then I went to Togo and spent about 3 months working there. And saw that a large amount of the populace goes about on bicycles and scooters...I viewed this with a mixture of amusement and disdain. But not only these, there was some smugness also. See them...backward African country...even for 9ja, we don pass this stage. How can you be riding "keke" all about the place? So Ara'ko-ish!

State of mind? Smugness and disdain!

Only for me to get to the Netherlands and discover there are more bicycles than people.

And people jolly well go about their daily life using bicycles. It is not a strange sight to see people all dressed up in their suit and tie with their briefcase, riding their bicycles to work. It is no strange sight to see mothers strap their babies to a seat that has being specially attached to the back (or sometimes front) of the bicycle.

Just Google Dutch people riding bicycles.

...And all of a sudden riding bicycles stopped being uncivilized or backwards! In fact it is something to recommend! Look, it is nice on nature, you don't want to continue harming our dear planet Earth with all these locomotives that emits dangerous chemicals? With bicycles, you don't get to emit any of such, so it helps us fight this global warming thing.

And also, it is soooo good for the heart! You know, cycling is good exercise and helps keep body and heart in good shape!

State of mind? Let's do it!


What changed? The people riding the bicycle!

It is quite shocking and sad to observe how my emotional reaction towards the idea of riding bicycles moved from utter disgust and disdain to one of admiration and commendation to the point of recommendation due to the type of people involved.

It is a different thing if my initial negative reaction to populace adopting the bicycle as a prominent mode of transportation was based on valid points. Perhaps something in those locality that makes bicycle riding ineffective? costly? But no, that was not the case.

When I shared this with a very good friend of mine, he made the following statements

...One May question the media through which we rationalize some of these things- and how societies have ebbed some systematic prejudice to how we view things. We are all guilty, to strive beyond it has to be a conscious decision that is by no means easy...

There are different angles to this observation and a quick look at history can help explain why things are currently the way they are. But it is quite jarring how the world we live in and its social structures affects the stereotypes we end up holding of the world around us and most importantly of ourselves. The harmful thing with these inclinations is that it could go unnoticed. An unconscious lens set up inside our minds, through which we now view the world.

It is also harmful when you consider the implication. When you have a situation where a societies' choice of solutions to their problems, when a societies identity etc are all unconsciously measured and framed against a mental yardstick of what we think some people from another society entirely would think of it, then we have an insidious problem at hand.

Where then is self determination. self identity, self realization? Where then is the ability to look inward, tackle your problems squarely and apply relevant and local solutions as needed?

It would be good for my people to stop, take a while and try to be introspective and observe some of our reactions to things around us; how we frame our problems, how we frame our identity, how we consider the solutions we think is cool (appropriate) and see if it does not suffer from this unconscious tainting...

As my friend said. " strive beyond this state, has to be a conscious decision..."

And with that, I end with the words of another conscious musician: Bob Marley...emancipate yourself from mental slavery, none but ourselves can free our minds.

Friday, April 18, 2014

Configuring Spring Data JPA

tl;dr Spring Data JPA enables a Repository style of accessing data where the data source is a JPA powered data source. Configuration is simple. Have a working Spring JPA configuration, then add the Spring-Data-JPA as dependency to your project and enable the functionality by wiring the appropriate bean in your Spring Context.

Configuring Spring Data JPA is part of the Configuring Spring Series.

This short post would show how to easily configure Spring Data JPA for use and some related concepts that should help explain the rational behind Spring Data.

Spring Data JPA itself is part of a larger umbrella project: Spring Data. Which seeks to provides an easier, less broiler plate way to accessing data. A lot of the projects under the Spring Data use the Repository pattern, while some don't. Spring Data JPA is one of the projects that implements the Repository Pattern.

Since the Repository Pattern is central to Spring Data JPA, it is recommended to, at least, have an overview of what is going on when it is being used. After this, we go ahead to look at the configuration procedure, which is very succinct.

Repositories can be viewed as abstraction over data. This explanation, although partly correct, does not do justice to the unique identity of the Repository pattern. The question might be, if it is an abstraction over data, how is it then different from DAO's?

There are quite a lot of varied opinion regarding the difference between Repositories and Data Access Objects; but I like this answer to the question on Stackoverflow a lot.

Most specifically the part where it says:

DAO is an abstraction of data persistence. Repository is an abstraction of a collection of objects.

DAO would be considered closer to the database...Repository would be considered closer to the Domain, dealing only in Aggregate Roots. A Repository could be implemented using DAO's, but you wouldn't do the opposite...

This explanation also touches on some key concepts out of Domain Driven Design: Domain and Aggregate Roots. Understanding these also would help groking the essence of Repository pattern itself. Here is a nice blog post that talks about Aggregates and Aggregate Roots in Domain Driven Design. It is a post in a series. The other posts should shed more light on other parts of DDD.

For the more adventurous regarding the subject of DDD; the bible itself is a recommended read. If its 506 pages look intimidating, then maybe a less voluminous guide would be more appropriate: InfoQ Free eBook : Domain Driven Design Quickly. It is just 104 pages.

In short, as can be seen from the explanation of the difference between DAO Pattern and Repository Pattern; the Repository is a collection.

The developer using the Repository is not concerned about the source of the objects. The source could be a Database, a Network, File system, or a Web service. It does not matter. DAO on the other hand, more often than not, deals essentially with the Database.

It is worth nothing here that DAO actually stands for Data Access Object and not Database Access Object. It seems the pattern evolved to mean Database Access Object. :|

So with Spring Data JPA, you work with Repositories which returns to you, objects or collection of objects that are sourced from a JPA based data store.

So with this fact established. The actual configuration is trivial.

Since it is Data JPA, configuring it requires that you have a working JPA configuration in place. You can read Configuring Hibernate JPA in Spring Framework if your JPA provider would be Hibernate. The configuration procedure applies if other JPA provider is being used.

To add Spring Data JPA, you need to do two things. Add it as a dependency in your project (pom.xml in this example as Maven is used) and enable it by wiring the necessary bean in your Spring context.

In pom.xml add:


and in your Spring Context add:

jpa:repositories is a Spring xml namespace that serves as a short cut for explicit bean definition needed to get Spring Data JPA running. You can read the section on Hiding Bean Definition via Namespaces for more about this.

The base-package tells Spring JPA Data where to find interfaces it should use in implementing Repository objects for your application. Yes, Spring JPA Data looks for interfaces you specify and provides the actual needed implementation for use at start up. Cool right? This is another way Spring Data JPA makes data access easier with less code. For a more detailed explanation on this, read Working With Spring Data Repositories.

More materials on Spring Data JPA in general can be found on the project page on

Tuesday, April 15, 2014

Why The Hell Do I Need Types? Because Fahrenheit can't be less than −459.67

For quite a while I never got the need for a Type System in programming languages. Considering the fact that my first introduction to programming was via PHP and Javascript, and with little or no formal schooling in computer science itself, it is easy to see how I could have easily ignored Types altogether; or worse still consider them an unnecessary overhead.

Why do I need a Type system when all I want to do is to keep in memory the value of say the cost of an Ipad? Can't I just have:

$ipad_cost = 199;

And yeah, if someone reading the code wonders what currency this price is in? well isn't that what comments are for?

// cost is in dollars
$ipad_cost = 199;

Why Types? Why go define a class or Interface for something as basic as this? I may get the idea of Types, but...really?

This was largely my world view regarding Types (an unnecessary overhead and verbosity) until I encountered the situation in which I contemplated on the best way to hold the temperature of a region in Fahrenheit?

long temparetureInFahrenheit = 42L;


int temparatureInFahrenheit = 42;

...are temperature values not numerical values? so why not?

But with any of these examples, what is stopping my program from assigning the value −500.67 to the temparatureInFahrenheit variable?

Ha, then my code would be breaking a fundamental law of nature init? as the absolute zero in Fahrenheit is −459.67 which means you can not have temperature with numerical value less than −459.67.

See why then you can't model all numerical values as just an int, long or any of the primitive types that comes with almost all programming languages?

Would it not be nice then, to have a way to make my computer be aware of the fact that the variable temparatureInFahrenheit is actually of a type Fahrenheit and as such has certain rules it has to obey?

Yes, this is what Types are for and useful for.

They are not overheads but a great way to properly model your code and prevent erroneous slips like the one describe above, thereby reducing bugs.

Configuring Spring MVC

tl;dr The process of configuring Spring MVC involves configuring the DispatcherServler as a front controller in the web.xml and configuring the Spring context file where Spring MVC specific beans like Controllers, Handler mappings, View resolvers, Locale resolver and Theme resolver can be wired.

This post is about how to configure Spring MVC. It is part of the Configuring Spring Series.

Spring MVC allows you to put the Spring framework at the fore front of your web layer. As you probably know, it is possible to use Spring in a web application without Spring MVC. As mentioned in Configuring Beans In Spring Framework, you can use WebApplicationContextUtils to bring in the Spring context into your web application. In that scenario, Spring is not responsible for the whole Web layer, it just plays its part, mostly as a DI container. But with Spring MVC, Spring framework is put at a central and integral part of your web layer.


I would be using Maven for dependency management. To get Spring MVC, certain required artifacts needs to be added to your project. To get these dependencies with Maven, your pom.xml file may look thus:

Sunday, April 13, 2014

Configuring Hibernate JPA in Spring Framework

tl;dr To configure JPA in Spring via Hibernate, you wire up one of the classes provided by Spring that creates a bean of type EntityManagerFactory which then makes EntityManager available for you. There are two types of Entity Managers, and the class you wire up depends on which Entity Manager factory you would be using. We have Application Managed and Container Managed Entity Managers.

This post gives an overview of how to configure Hibernate as a JPA implantation, for use in a Spring application. It is part of the Configuring Spring Series.

In Configuring Hibernate in Spring Framework, we saw that in other to talk to the database via Hibernate, your application code would do so via Spring's implementation of Hibernate's main interface: org.hibernate.Session which is made available via an implementation of  org.hibernate.SessionFactory. And the process of configuration is just a process of wiring up Spring's to provide this needed SessionFactory as a bean.

You have a similar procedure when it comes to configuring Hibernate JPA in Spring. 

Instead of working with a SessionFactory, you work with EntityManagerFactory. And instead of Hibernates' Session you have EntityManager  through which the actual database access is done.

The process of configuring Hibernate JPA in Spring hence, is all about wiring the Spring bean that would make available for you the EntityManagerFactory.

Before we get to the business of actual configuration, let's get some key concept's explained.

Wednesday, April 09, 2014

Structure, Work flow, Design

They say it's good to have separation of concern, and I agree, but I would suggest that PHP's nature which easily allows the muddling of logic across layers of application creates a more fluid workflow (in the short term) that leads to more fluidity and better aesthetic looking creations; while with languages like Java; what you mostly get, (unless you put extra effort not to), are designs that feels more like they were constructed instead of inspired. With things looking all so structured and "boxy".

Friday, April 04, 2014

Is That A Reg Flag?

I am adopting a slightly different meaning to the phrase "red flags"; which in colloquial usage refers to a warning signal or something that demands attention. Although my modified meaning also can be seen as a warning signal; the new meaning I am ascribing to the phrase is based off the Red Flag Traffic Laws

The Red Flag Traffic Laws were laws in the United Kingdom and the United States enacted in the late 19th century, requiring drivers of early automobiles to take certain safety precautions, including waving a red flag in front of the vehicle as a warning.

The law as defined from Wikipedia. Emphasis mine.

An interesting part of the enactment:
  ...[a person] shall carry a red flag constantly displayed, and shall warn the riders and drivers of horses of the approach of such locomotives, and shall signal the driver thereof when it shall be necessary to stop, and shall assist horses, and carriages drawn by horses, passing the same.

To people of today's world; this policy definitely sounds absurd and backwards. But at the time it was put in place, it was done so as to address a real concern; safety to others in a world where self propelled locomotive is about to become more common...

But the absurdity of it is not my primary concern but the limitation the policy would have placed on the expression of a new technology. For one, having someone always in front of the locomotive means that the locomotive theoretically is not allowed to move faster than a particular speed. A big advantage of having a self propelled locomotive is then lost! Why have a car when you can only drive at a much slow pace?

And this is where my new internal usage of Red Flags takes it meaning. It expresses propositions, way of thoughts, policies that stifles the expression of innovation not with the intention of doing so but as a result of taking actions that intends to protect a valid concern.

And some characteristics of these kind of thinking; "these Red flags" can easily be spotted by taking a look at some of the characteristics of the Red Flag Traffic Law itself:

  1. The law was put in place in good faith. The intention was not to stifle expression of an emerging technology; but to protect the populace. But the outcome, invariably  limited the expression of a new technology
  2. The law was focusing on established way of life instead of embracing and exploiting a new way.
  3. Although the concern expressed by the law is valid; it tried addressing these concerns from the same paradigm level.

Making sure all self propelled locomotive have a hoot would have been a solution that sufficed. This is how addressing the concern from a different (or higher) paradigm would have largely addressed the concern without having to put an artificial limitation on the workings of the self propelled locomotive.

So when we are confronted with any new concepts; innovations or technologies that has the potential of disrupting the safety of well established way of doing things and we have a strong urge to put things in place that would address these concerns; we need to be aware that our actions might lead us to just be enacting our own versions of the Red Flag Traffic law. We don't want to do that.

In Software, You Build To Change Too

There are moments when differently considering how a domain is captured and expressed leads to an epiphany of sort: A much clearer insight into the matter at hand.

It could be a slight or simple change of point of consideration, but the insight it leads to, could be quite profound.

The Earth moved. A simple change in the way the solar system is viewed but a change that led to a significant upheaval of not just how we understand the cosmos; but a change that also rattled the political and power structures at that time.

I recently had a similar change with regards to how I internally conceptualize Software Development (or construction) and Software Architecture. Not surprisingly, my internal modelling has largely been shaped by the type of architecture that I am most exposed to: which is the civil type: how buildings are made, roads, bridges etc. And in these domains, the primary concern is building to last. The success of the architecture of a bridge is judged on how long it can last without fail. Same goes for high rise buildings. Building to change is not primary in these domain. 

This view has been projected onto how I primarily perceive Software Architecture. A great Software Architecture is the one that creates software that can always keep performing no matter what. This is the building to last metaphor.

But just as building to last applies to software; building to change is (should) also be core too. In fact; how well a software facilitate easy change would determine how long it may last.

Software is meant to mutate, by its very nature, with time. And a good software architecture is one that enables for easy change to the system while ensuring the system continues to provides its utility.

So when approaching a software creation process; keep in mind that building to change is as much important as building to last and let this fashion the architectural decisions you make.