Tuesday, June 22, 2010

Ten Principles of Good Design: Dieter Rams

The ten principles of good design from the famous German designer Dieter Rams. They are generic and makes sense in any industry or product:-
  1. Good design is innovative.
  2. Good design makes a product useful.
  3. Good design is aesthetic.
  4. Good design makes a product understandable.
  5. Good design is unobtrusive.
  6. Good design is honest.
  7. Good design is long-lasting.
  8. Good design is thorough down to the last detail.
  9. Good design is environmentally friendly.
  10. Good design is as little design as possible.

More details about Dieter Rams & the principles here.

Thursday, May 13, 2010

Embedded Jetty Server

A simple utility class to embed Jetty web server:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public enum WebContainer {
INSTANCE;
private Server server;

public void startServer(String resourceBase, String contextPath, int port) {
try {
server = new Server(port);
ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
handler.setContextPath(contextPath);
handler.setResourceBase(resourceBase);
server.setHandler(handler);
////////////////////////////////////////////////////////
// add servlet context init params using the following
// handler.getServletContext().setInitParameter(, );
////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
// add event listeners using
// handler.addEventListener();
////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
// add filters using
// handler.addFilter(, , );
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// add servlets using
// handler.addServlet(, );
////////////////////////////////////////////////////////
server.start();
server.join();
} catch(Exception e) {
e.printStackTrace();
}
}

public void stopServer() {
try {
server.stop();
} catch(Exception e) {
e.printStackTrace();
}
}
}

Use WebContainer.INSTANCE.startServer(...); and WebContainer.INSTANCE.stopServer(); to start and stop the server respectively.

Thursday, April 29, 2010

Implementing a simple deterministic rule engine

The following is my experience of implementing a simple deterministic rule engine (if at all it can be called such) in JavaScript using Mozilla Rhino. This was part of the enterprise platform we are building in our company. We tried using Rete based JBoss Drools earlier but felt that a simpler deterministic rule engine would better suit our purpose.

The need for such a thing was due to various reasons:-
i) Rete based stateful rule engine was an overkill for our use case
ii) The non deterministic and asynchronous nature of Rete based rule engines makes debugging and testing very difficult (as pointed out by Martin Fowler)
iii) Most of the rules in our case were of the nature of validations or calculations which makes Rete an overkill
iv) A tailor made custom rule engine gives more flexibility and power
v) Our consumers (product developers) were not at ease with the programming style of traditional rule based approach


The approach went something like this:-
i) Enable server side scripting in JavaScript using Mozilla's Rhino engine
ii) Capture rules as metadata in the form of JavaScript statements (majority of them will be of the form if condition then action)
iii) Expose domain objects and other relevant APIs into the rule scripts at well defined lifecycle phases of entities (CREATE, UPDATE, DELETE, etc.)
iv) Execute the rule scripts within the context of domain objects and relevant APIs during the life cycle of domain objects (typically CRUD phases)
v) We also support a MANUAL context wherein developers can set relevant domain objects explicitly and invoke the rule engine

The beauty of LISP (and Clojure)

A couple of years ago, I accidentally came across the strange word Clojure, which I later came to know as a LISP style programming language on the JVM. At that point I was a total newbie to functional programming (and LISP), having spend most of my programming time on C, C++, Java, etc.

The first impression I had when looking at a medium size Clojure program was that of a mess of parenthesis. Why in the world would anybody want to write programs of this sort?

As many others, it took a while for me to truly appreciate the simplicity, elegance and beauty of functional programming in general and LISP in particular.

Clojure might have a popular future due to its clean way of handling concurrency and light weight threads (through Software Transactional Memories aka STM)

Hats off to John McCarthy for creating LISP and Rich Hickey for creating Clojure.

Handling Spring ApplicationContext events in Spring DM based OSGi environment

Listening for and handling Spring ApplicationContext events in a Spring DM setup needs needs two steps:

1) Implement a class for the interface org.springframework.osgi.context.event.OsgiBundleApplicationContextListener
import org.osgi.framework.Bundle;
import org.springframework.context.ApplicationContext;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextEvent;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener;
import org.springframework.osgi.context.event.OsgiBundleContextClosedEvent;
import org.springframework.osgi.context.event.OsgiBundleContextRefreshedEvent;

public class BundleApplicationContextTracker implements OsgiBundleApplicationContextListener {
public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) {
if(event instanceof OsgiBundleContextRefreshedEvent) {
// handle bundle start
} else if(event instanceof OsgiBundleContextClosedEvent) {
// handle bundle close
}
}
}

2) Expose the above class as an OSGi service by putting the following entries in Spring beans-config.xml

<beans:bean id="bundleContextTracker" class="org.mypackage.BundleApplicationContextTracker" scope="singleton"/>
<osgi:service id="bundleContextTrackerOSGi" ref="bundleContextTracker" interface="org.springframework.osgi.context.event.OsgiBundleApplicationContextListener"/>

Capitalism and environmental damage

One of the general principles on which Capitalist economy and market (particularly the corporate world), works is "produce more, sell more; buy more, consume more". This is inevitable as increased revenue/profit is the yardstick by which all corporates measure their performance. In the long run this can happen only if the seller produce MORE and the buyer consumes MORE. Advertisements do a fairly good job of making consumers believe that they are lesser if they don't have certain goods (even when they really don't need it).

MORE seams to be the war cry of the majority of us living under Capitalism (both producer and consumer). But where is the MORE coming from, what is its source? Clearly it cannot come out of thin air. No doubt, we keep on improving our business models , processes and technology . But they alone can't create this MORE. There is something more fundamental than our technical innovation, free market and global economy that makes this possible. What does it cost for this so called MORE to be produced and consumed? The short answer is NATURE.

Most of the gains of modern human societies comes at the cost of NATURE. Scientists estimate that the environmental damage done over the past few centuries by our industrial modes of production is almost irreparable. Most of our energy hungry economies today cannot function without adding more CO2 to the atmosphere or by putting more holes in "Ozone Layer".

The Capitalist cry for MORE will continue to increase the damage.It forces individuals and societies to push nature to its limits. Day after day we as groups and individuals ask more and more from nature. Our bore-wells and oil wells gets deeper, our forests gets thinner, species of flora & fona gets fewer in number. Nature though pushed to its limits, somehow meets our demands. But, how far will it go on?

A day may come when NATURE turns back on us and tells , "I have given all that I could, I have nothing more to give". Many environmentalists feel that such a day may only be a few decades or a few centuries down the line.

Is this (the greed for MORE) a fundamental contradiction within Capitalism, a contradiction much more severe than the "Class conflict/contradiction" of Marxist analysis? This problem raises more questions. Will our greed for MORE stop at some limit? Do we need to look for alternative political systems? If not Capitalism, what?

Though very young, Capitalism has been by far the most stable and most successful political structure in the history of mankind. Thanks to the scientific revolution that developed almost in parallel with itself, Capitalism has made life better for a large number of people. It has fed and clothed more people than any other political system.

Communism/Marxism offered an alternate system that promised to overcome the inherent faults of Capitalism. But living in a time after the collapse of USSR and the other Communist giant China getting capitalized more and more, we can definitely say that Capitalism is the only major political system in the world today. (Exceptions like Communist Cuba, Dictatorships, Kingdoms, etc. could be very well ignored.)

Whatever be its demerits, Capitalism has one virtue that almost all other political systems in History lacked. It has a self corrective factor within itself. And that is what has made it the most successful of all political systems. The solution for environmental crisis and other problems due to human greed cannot be alternate political systems (be it economic/fascist/theocratic) or revolutions. Any sensible solution has to be more practical and pragmatic.

Though an over simplification, we could very well say that Capitalism like any other human enterprise is a tool that we created for ourselves. Its not an uncontrollable giant that controls our fate (as the historicist would see it). And any tool could be wisely used or abused. More than a change of tools, what we may need is to learn the tools wisely.

The long term solution would be DISCIPLINE. We need to learn as individuals, societies and nations to restrain our GREED.

Wednesday, March 24, 2010

The "lyre & harmony" analogy of Simmias

The scene is from Plato's dialogue "Phaedo". Phaedo who was present with Socrates on the day of his execution, narrates the events of that day to his friend Echechrates.

Socrates is condemned by the Athenian to be poisoned to death, on the false charges brought by the trio Anytus, Meletus & Lycon. But, Socrates is not at all worried about death, and converses calmly with his friends on various topics. The conversation inevitably moves onto topics like death, life after death, soul, etc.


Seeing that his friends are surprised at his calmness, Socrates says that "...he, who has the spirit of philosophy, will be willing to die; but he will not take his own life." Death is preferable to life because the true state of man is his soul, and his body and the soul's attachment to the body is only a temporary corrupted state. A man is not supposed to take his own life because, his life is not his own property but that of the gods. The philosopher prefers the true knowledge and wisdom of the uncorrupted soul to the illusions and sufferings of the body.

Having given the Soul a higher plane of existence than the Body, Socrates proceeds to clear the confusion of his friend Cebes that the Soul may perish along with the Body, by giving a set of arguments to prove the immortality of the Soul:

i) Cyclical Argument:
Like asleep-awake, hot-cold, odd-even, etc. opposites generally have a tendency to follow each other. Death & Life being opposites follow each other. From life to death and death to life runs the cycle.

ii) Recollection Argument: Many times one kind of information or knowledge may indirectly trigger the recollection of other kinds of information or knowledge. Also people tend to have knowledge about topics which they were unaware of before being questioned about (a priori knowledge). This kind of knowledge is nothing more than recollection, which is possible only due the fact that the knowledge was there in the Soul beforehand.The Soul is not a clean slate (Tabula Rasa) at birth, but has knowledge from its previous births, which could be recollected.

iii) Affinity Argument:
The soul resembles that which is invisible, immortal and divine, and the body resembles that which is visible, mortal and earthly. The soul is related to the divine whereas the body is related to the corporeal. Hence the soul and its existence is not limited to the body to which it is temporarily attached.

iv) Absolute Form Argument:
Every phenomenon on Earth is an corrupted subset of an absolute and perfect form of itself. The beautiful is a limited representation of the divine absolute beauty, worldly knowledge is a limited representation of divine absolute knowledge, etc. Similarly, the physical life of the body is a limited representation of the "Absolute Form of Life" the soul. Hence soul is immortal.


Everyone around are captivated by the logic of these arguments. But two people Simmias and Cebes are doubtful. Their objections are as follows:
Simmias:- The harmony (music) of the lyre perishes before the lyre itself. How can the soul (the harmony) continue to exist when the body(the lyre) is destroyed?
Cebes:- The Soul may not perish with the body, but that doesn't mean its immortal. A weaver may weave many coats and outlive most of them, but the last coat he weaves shortly before his death outlives the weaver. Similarly, the soul may outlive many bodies, but can get gradually worn out and finally its last body will outlive the soul.

The listeners are dumbstruck. Both are powerful objections in front of which the earlier arguments of Socrates looks invalid. However Socrates takes the arguments one by one and defends the immortality of the Soul.

Before going into the details of Socrates' defense of the Soul's immortality, it may be worthwhile to understand the exact nature in which Socrates understood the term "Soul". Socrates had a materialistic view of the Soul. For him and for most people of those times, heaven and supernatural were physical places. The soul was a material entity just like the body, the only difference being that it has a higher plane of existence, is divine, and immortal.

The following were the arguments Socrates brought forth against Simmias:
i) In case of lyre and harmony, the lyre always influences the harmony and its never the other way around, but the soul influences the body through its thought and will. Hence the analogy is not valid. The body follows the soul but the lyre never follows the harmony, hence lyre-harmony is not analogous to body-soul.
ii) There are different degrees of harmony. A harmony can be lesser or greater in degree than others, whereas there is no such distinction for the soul.
iii) Harmony is a compound composed of the sum of its constituent elements. The soul a single entity and is not a compound.

The argument of Simmias has much relevance today. It turns out the empirical evidence and modern Science favors Simmias than Socrates. Benjamin Libet (1916-2007) has shown that conscious volitional acts start with the body and not the mind. The brain activity leading to a thought impulse happens a split second before we actually become aware of it. If so the lyre-harmony analogy of Simmias holds, and Socrates was wrong in saying that the soul leads the body.


Modern science has irrefutably shown the material basis (in the brain) of mental activities like memory, learning, recollection, etc. Hence, most of the faculties of soul that Socrates identified with (like recollecting, correlating, etc.) are dependent on the material brain. Once again it looks like Simmias was right and Socrates was wrong.