Thursday, January 19, 2012

Simplicity

Simplicity is the ultimate sophistication - Leonardo da Vinci
Rich Hickey presented a fantastic talk, Simple made easy - "Rich Hickey emphasizes simplicity’s virtues over easiness', showing that while many choose easiness they may end up with complexity, and the better way is to choose easiness along the simplicity path."

Anders Hejlsberg mentioned simplexity in an interview a while back as well where he says "Let me first talk a little bit about how I view simplicity in general. No one ever argues that simplicity isn't good, but people define simplicity in a variety of ways. There's one kind of simplicity that I like to call simplexity. When you take something incredibly complex and try to wrap it in something simpler, you often just shroud the complexity. You don't actually design a truly simple system. And in some ways you make it even more complex, because now the user has to understand what was omitted that they might sometimes need. That's simplexity. So to me, simplicity has to be true, in the sense that the further down you go the simpler it gets. It shouldn't get more complicated as you delve down. "


Over time I have seen quite a few systems with too much complexity. And mostly it was not needed. Just a lot of code added without too much thought to design. More thought should be put into design and refractoring and testing.

It is also funny how this parallels to a sense of minimalistic design for design and architecture.

Wednesday, November 23, 2011

Installing mercurial on CentOS or RHEL 4

For mercurial/hg you need a relatively new version of python installed. Since that is not available as an rpm let's compile the source.

From http://python.org/download/ download a python source version like http://python.org/ftp/python/2.7.2/Python-2.7.2.tgz

From http://mercurial.selenic.com/release/ download a mercurial source drop like http://mercurial.selenic.com/release/mercurial-1.7.5.tar.gz

Run the following commands as root:
#Install some dependencies
yum install zlib-devel.i386 ncurses-devel.i386 openssl-devel.i386 readline-devel.i386 bzip2-devel.i386

#Extract the python code
tar xvzf Python-2.7.2.tgz
cd Python-2.7.2

# Python will be installed in /opt/python27
make clean; ./configure --prefix=/opt/python27; make; make install
cd ..

# Extract the mercurial code
tar xvzf mercurial-1.7.5.tar.gz
cd mercurial-1.7.5

#Python will be installed in /opt/hg17
make install PYTHON=/opt/python27/bin/python PREFIX=/opt/hg17

#Add new python and mercurial to PATH
export PATH=/opt/python27/bin:/opt/hg17/bin:$PATH

Tuesday, June 14, 2011

Java7 Automatic resource management

ARM:

One of the useful features in Java7 is the Automatic resource management via the try-with-resources statement.

In the olden days thou would (or atleast were supposed to) code like:
void doSomething() throws IOException {
  OutputStream out = null;
  try {
    out = new FileOutputStream("");
    out.write(data);
  } finally {
    if (out != null) {
      out.close();
    }
  }
}

Which is error prone if you do forget to close the resources.

The new way is:

void doSomethingNew() throws IOException {
  try (OutputStream out = new FileOutputStream("")) {
    out.write(data);
  }
}

This is syntactically much more pleasing and does the right thing internally.

Going deep:
The try-with syntax works with any AutoCloseable implementation and you can have multiple resources as well.

The compiler will transform the above code into something like:

void doSomethingNew() throws IOException {
  OutputStream out = null;
  Throwable localThrowable1 = null;
  try {
    out = new FileOutputStream("");
    out.write(blah);
  } catch (Throwable localThrowable2) {
    // We keep a reference to which can add a suppressed exception
    localThrowable1 = localThrowable2;
    throw localThrowable2;
  } finally {
    if (out != null) {
      if (localThrowable1 != null) {
        // Already have an exception thrown
        try {
          out.close();
        } catch (Throwable localThrowable3) {
          // Add the suppressed exception during close
          localThrowable1.addSuppressed(localThrowable3);
        }
      } else {
        // Potentially throw an IOException due to failure when close'ing
        out.close();
      }
    }
  }
}

The pattern is:

  • If there are no exception - close() in the finally block OR
  • If there are no exception during operation but there is an exception during close() then throw it OR
  • If there is an exception thrown then throw it after closing the resource OR
  • If there is an exception1 thrown then throw it .. and if there is an exception2 closing the resource.. then exception1.addSuppressed(exception2). This is new in theThrowable class

Sidenote:
There was a huge effort to get closures into Java7 but none of the solutions was light on syntax/complexity. After the backlash over Generics a smaller but better step has been taken.

Sidenote++:
For scala see using. You do not need to wait for language changes to make syntactically pleasing APIs because of curry-ing and other fancy stuff.


More References:
ARM spec
Article on ARM

Wednesday, February 23, 2011

Beautiful software

<moody>
I feel a deep sense of happiness when I use Google products like gmail and chrome. Every now and then they update the applications and things just work. They make things look so simple but they must be super complex in the back. That's great software.

Great software can only be built by great teams. That means everyone from engineers to managers. Give enough freedom to the team to execute. Treat them like people. Understand software.

No software methodology can save you. Let the team define its processes. Let common sense prevail. And then greatness will follow.
</moody>

Tuesday, January 04, 2011

Where did the class get loaded from?

As with most enterprise apps gone crazy you have a bunch of duplicate jars or some jars at places you don't even know were in the classpath. And once a while you need to know from which jar a particular class file was loaded. To find this out run java with the -verbose:class flag. For each class loaded, the VM will print out the folder or jar where the class was found.



~ $ java -verbose:class HelloWorld
...
[Loaded HelloWorld from file:/C:/work/cygwin/home/rrevo/]
Hello World
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file]


Read java options for more info.

PS: It's time to start blogging again.

Wednesday, November 04, 2009

Linux on the desktop

Recently I performed some upgrades on my laptop and the sound broke once again. Sound has been flaky for a while now and I've had to use windows to use skype. This was a pretty useful tutorial which helped me sort out the issues - http://ubuntuforums.org/showthread.php?t=789578

But it got me thinking more about experience on Linux once again. Applications like OpenOffice, Gimp are inferior in usability to MS Office and Photoshop. Its painful when I need a newer version of software but the distro is older and so only an older version is available in the repo. Maybe its time to move back to Windows...

Thursday, October 01, 2009

An Overview of Spring

Spring is a very popular framework in the Java space and quickly becoming an alternative to JEE. Spring started of as an implementation of the ideas in the book "Expert One-on-One J2EE Design and Development" in 2002 by Rob Johnson. Today the project has grown into to a large framework with multiple modules to assist with different areas of serverside programming. Spring provides a lightweight container and uses POJOs. This makes code much simpler to reason about and also test. No starting a mega EJB container anymore with remoting when you don't really need it.

Inversion Of Control (IoC)
At its core, Spring is an IoC container. Generally at some point in code you use 'new' instances. If you are coding against an interface you end up with code like:

class Bar {
Foo foo;
void Bar() {
foo = new FooImpl();
}
}

Now the class Bar has a dependency on Foo and its implementation FooImpl. Now you could remove this dependency by using the ServiceLocator pattern but then you end up with a dependency to the ServiceLocator class and your code is not that testable anymore.
In Spring you instead inject the actual implementations at runtime and rules about which instances are to be returned are written in an XML configuration file (or via Annotations). So code becomes like:

class Bar {
Foo foo;
void Bar(Foo foo) {
this.foo = foo;
}
}

with an instance of FooImpl being returned where Foo is expected. Now Bar depends only on the interface Foo but not the implementation of Foo which is simply passed to it. Hence the name Inversion of Control as Bar does not depend on FooImpl but gets it.

More importantly the code can be tested very easily. If I wanted to test the Bar class I can very easily provide a mock implementation of the Foo instance. Writing testable code is difficult and a major part of the problem is breaking dependencies. You should probably never need to new objects again but just get them injected.

In the above example Foo is set in the constructor. This is an example of a Constructor based injection. Another way to inject dependencies is via setter methods. However I prefer Constructor based injection as it allows for final fields which should be the default to help with immutability.

Another important idea is how instances are created. This is known as scopes. By default instances are created only once and that reference will be passed everywhere similar to a Singleton. So one FooImpl instance is created and passed wherever a Foo is needed. A lot of code can be written in a style where there is no local state allowing for Singletons. Again since the Singleton pattern is not explicitly needed, code remains testable. Another scope is prototype in which a new instance of FooImpl will be created whenever a Foo needs to be injected. For web programming other scopes like Request, Session and Application also exist.

The complete lifetime of instances can be managed and there are many other features but thats another post. If you just need an IoC container then there are alternatives like Google Guice.

Aspect Oriented Programming

AOP allows for crosscutting code to be written external to the main business logic. This allows cleaner code in areas like logging. The implementation of AOP in Spring is based on Proxy based interceptors which happen at runtime. AspectJ integration is also provided in some form.
One of the major uses of AOP is defining transactions which will be covered soon.

Data Access and Transaction management

Most serverside code needs to talk to a database. Spring provides neat abstractions over JDBC and other frameworks to simplify code to a great extent.

A DataSource is usually configured and injected.
JDBC code is wrapped with classes like the SimpleJdbcTemplate. Queries become like:

String daString = getSimpleJdbcTemplate().queryForObject(
"SELECT daString FROM DaStringTable WHERE daStringId = ?",
String.class, daStringId);

Thats one line of code for what would have been multiple lines of JDBC like getting a connection, then statement, then query and result parsing. And there are no SQLExceptions. All of those are wrapped into a DataAccessException instance which is a RuntimeException. Create a generic handler in your code for exceptions because thats what you'll mostly be interested in. You can easily provide mapper classes to map from db values to object instances for custom types. Also variations exist for returning mutiple rows and other SQL CRUD operations.
And I almost forgot to mention that there are also named parameters for queries.

Using Hibernate is even easier. Use HibernateTemplate instead and get access to a hibernate API. Or JPATemplate if you want to use JPA. All of this code is obviously going to be tucked under a DAO tier!

Transaction management is also dead simple with usage of Java annotations. You declare the Transaction rules for a method invocation like Isolation level (Read uncommitted, Read committed, Repeatable Read, Serializable), Propagation (Required, New), timeout and exceptions for rollback. An AOP proxy is created over the method which enforces the Transaction rules over the underlying datastore.

Web MVC

Built on the core IoC functionality Spring has a Web MVC framework as well. Like Struts it is a request or action based framework. The DispatcherServlet class is a FrontController and acts as the entry point to the MVC framework. Typically request URIs are mapped to Controller classes. Controllers compute the Model and then render a View based on the Model for the request. A general multi tier architecture for applications is another topic.

Even more

There are quite a few other projects under the Spring banner. WebFlow extends Web MVC for richer work flows in webapps. Spring WebServices for WebService (duh). Spring IDE is a bunch of Eclipse plugins to help with Spring development.

Spring Framework 3 is going to be released. It adds better Java 5 support across various APIs. There is also a lot of annotation usage.

The company and future

Spring started off as a simple open source project and has now morphed into a complete stack framework backed by a company.
The core framework helps building applications. Further they added Groovy language and Grails. Mostly spring apps need a web container like Tomcat or Jetty to run. SpringSource also provides a custom Tomcat build known as tcServer with additional capabilities. Another environment is the dmServer which adds OSGi capabilities. For management and diagnostics they have additional tools. All of these play together to provide a really strong stack against the usual JEE standard running in an application container.

VMWare bought SpringSource which means that soon Cloud-deployed apps based on Spring are going to be dead simple to make. This means that VMWare will now compete with the likes of Google App Engine and Microsoft Azure as well by providing virtualized application frameworks.

Links