Interface vs. Implementation Dependencies in Java

I often use the notion of interface and implementation dependencies, where interface dependencies are mostly always smaller. I think this is a very important concept to understand for Java developers, and although it seems obvious and self evident, many developers do not think along those lines and still couple classes too tightly.

Take this example:

class CassandraStorage {
	public void store(String key, String value) {
	    otherPartOfApp.doSomething();
	    yetAnotherPart.doSomethingElse();
	    cassandraClient.store(key,value);
	}
}

class MyApp {
	@Inject CassandraStorage storage = null;
	public void myCode() {
			...
	}
}

The dependency chain for MyApp is:

MyApp -> CassandraStorage -> Cassandra Framework -> Many many more
                          -> Many other parts of application

The problem with this are the many dependencies the implementation of the Storage class introduces. When we add an interface, decoupling the usage from the implementation, we can decrease the numbers of dependencies significantly.

interface Storage {
	void store(String key, String value);
}

class MyApp {
	@Inject Storage storage = null;
	public void myCode() {
			...
	}
}

The dependency chain now only includes

MyApp -> Storage

broken away from

CassandraStorage -> Storage

with some benefits:

  • This breaks dependency chains early
  • Speeds up compilation
  • Easier to modularize
  • Helps break cycles

So use the concept of interface and implementation dependencies, where interface dependencies are mostly always smaller. I think this is a very important concept to understand for Java developers, and although it seems obvious, many do not think along those lines.

Singletons without Singletons: Scala Type Classes

I was using Guice in a project recently. Objects which did not come out of Guice got their dependencies not injected. So I had a global singleton where objects could get their dependencies. Yeah yeah I know singletons are bad and stuff. It would be nicer to let Guice handle it all, but sometimes this is not possible due to framework restrictions where you have no controll over object creation.

For example one part of the project uses UseCase classes and injects depedencies inside them. I want to use those UseCases with

use(new ActivateEmailAddressUseCase(encrypted))

The definition of the use method is simple and looks like this:

object UseCase {
  def use[R](useCase: {def execute(): R}): R = {
    DomainInjector.injector.injectMembers(useCase)
    useCase.execute()
  }
}

where the global DomainInjector looks like this:

object DomainInjector {
  val injector = Guice.createInjector(new GuiceDomain)
  def injectMembers[I](injectee: I) =  injector.injectMembers(injectee)
}

So far so nice. The problem did arise when I was running only parts of the project against sbt ScalaTest testing. Those parts now were coupled to other parts because of the global singleton and I didn't want to include those other parts as depedencies. Bad. The problem is the GuiceDomain class where dependencies might go to different parts of the application - especially up the hierarchy.

Changing this to an interface implementation

object DomainInjector extends Injector {
  val injector = Guice.createInjector(new GuiceDomain)
  def injectMembers[I](injectee: I) =  injector.injectMembers(injectee)
}

and changing the UseCase class to use an implicit method paramater:

 
object UseCase {
  def use[R](useCase: {def execute(): R})(implicit injector: Injector): R = {
    injector.injectMembers(useCase)
    useCase.execute()
  }
}

Now the tests could include into their scope

object DummyInjector extends Injector {
  def injectMembers[I](injectee: I) = { }
}

instead of the DomainInjector and still work. Excellent, problem solved.

And if you do not know what this has to do with type classes: I do not know either after reflecting about the blog post 5 minutes after publishing. Sorry for that 😉

Interview with DSL, NoSQL and Scala Practitioner Debasish Ghosh

This interview is with Debasish Ghosh. He's writing the successful blog Ruminations of a Programmer with the tag line "A programmer's blog - will deal with everything that relates to a programmer. Occasionally, it will contain some humour, some politics and some sport news.".

Name: Debasish Ghosh (dghosh@acm.org)
Blog: http://debasishg.blogspot.com
Twitter: @debasishg
Github: http://github.com/debasishg

Tell us something about you (what are you doing, job, ..):

I am the chief technology evangelist at Anshinsoft, specializing in leading delivery of enterprise-scale solutions for clients ranging from small to Fortune 500 companies. We implement and deliver back office solutions for the Trading and Settlement systems. My research interests are functional programming, domain-specific languages, and NoSQL databases. I am a senior member of the ACM and author of the book DSLs In Action to be published this year by Manning. [Stephan: Very good book, I've enjoyed the latest MEAP version]

How did you come into programming?

I studied Computer Science at the Undergraduate level and got inducted into the world of programming from my school days. We did BASIC and C in those days and used Fortran for writing numerical analysis programs.

What do you love about programming?

The sheer joy of making things (to quote Fred Brooks). But I love programming so long it's a fun. I love when a program shapes the problem domain in an expressive manner and yet being succinct in expression.

Where do you think programming languages and programming in general is in 50 years?

I have no idea where it will go. We have been proved wrong on many counts till date predicting the future of programming or languages. Who knew we would be seeing the rebirth of Lisp in the mainstream at a time when Eclipse and Java were having a party.

How did you get your first job? What tips would you give to others?

I got my first job from the school campus recruitment. It was a fascinating experience trying to match up to the expectations of the corporate world as a young rookie. The first job of your career is like the constructor of your class - ensure proper initialization order to avoid unwanted surprises later.

What would you tell someone who wants to start a programming career?

Just do it. Don't ignore the fun part of it. A programming career sinks when it becomes *only* another way to get a paycheck.

What does programming differentiate from everything else in the world?

Actually it's not very different from anything else. You just have to find your sweet spot of creativity. As a programmer, I draw lots of inspiration from the writings of Christopher Alexander, the architect. I think his book "A Timeless Way of Building" is a must read for every programmer.

Thank you for this interview.

Continuous Deployment Setup at 2morethin.gs

I've set up continuous deployment for 2morethin.gs. Continuous deployment means that as soon as a developer finishes work, his code is pushed to the website. IMVU does it, as does WordPress.com and kaChing. This post should show you that there is no magic in continuous deployment, everyone can do it.

Why would one want to drop releases and do continuous deployments? The main benefit is that your time to market goes down drastically. Usually your time to market from idea to customer is weeks or often months. With continuous deployment it can go down to 30 minutes. This will enable your company to experiment more, take higher risks because you can change your decision in 30 minutes.

Continuous deployment setup diagram 2morethin.gs

The setup is quite easy and involves a HAProxy balancer, two Tomcats, some shell scripts, cron and Mercurial. It's very alpha but works. I develop locally - a benefit of a distributed SCM - and when I'm done I push to the central repository. There a hook executes and writes a flagging file to /tmp. Each minute a cron job runs, checks for the file and if it's there removes it and does a deployment. The deployment script is rather simple, it goes through the tomcats, stops each one, deploys the application and then restarts the tomcat. The HAProxy load balancer takes care of sending requests to the tomcat which is currently up, so the site does not go down during deployments.

Obviously missing currently is a test stage and roll backs if deployment on one tomcat went wrong, feedback is appreciated, leave a comment.

As continuous deployment involves a different thinking on the part of developers, testers, operators or devops, it's better to start early with continuous deployment than later. So if you're running a startup, do yourself a favor and use it right now.