Posted by Timothy Fisher
Sat, 02 Feb 2008 23:30:00 GMT
It has been suggested to me by several reviewers including this one at the Java Lobby that the Java Phrasebook which I wrote last year would make an excellent text book or companion to a text book for a course on Java programming. After thinking about this, I think that coupled with some lecture notes or presentation slides, I agree that the Java Phrasebook could serve as an excellent companion book for students in a Java programming course. A strength of the book in that usage scenario is that it offers wide breadth in terms of what it covers. It does not go into great depth on alot of java features and technologies, but it has over 200 phrases which illustrate how to perform some of the most common programming tasks. The book is broken down into the following chapters with each chapter including phrases illustrating how to perform common programming tasks related to the chapter’s subject:
- The Basics
- Interacting with the Environment
- Manipulating Strings
- Working with Data Structures
- Dates and Times
- Pattern Matching with Regular Expressions
- Numbers
- Input and Output
- Working with Directories and Files
- Network Clients
- Network Servers
- Sending and Receiving Email
- Database Access
- Using XML
- Using Threads
- Dynamic Programming Through Reflection
- Packaging and Documenting Classes
I could definitely see a programming course follow this same structure with lecture covering the details of each topic and the Phrasebook supplementing the lecture with practical examples and review material. The book could make an excellent study guide as well for students in a Java programming course.
If you have used the Java Phrasebook in an educational course, I would love to hear from you. Education is another passion of mine, and it would be cool to hear that someone was using my book as an educational tool.
Tags education, java, phrasebook, programming | no comments
Posted by Timothy Fisher
Mon, 28 Jan 2008 04:54:00 GMT
NOTE: This is a reprint from an article that I originally wrote on a blog that I write for the Java Developers Journal. Since it was a fairly popular article there, I thought it would be a good idea to broaden it’s audience and repost it here. I hope that you find it helpful.
If you’re active in the Java community, you’ve probably come across the term “dependency injection.” This is a term that’s used more than it’s defined, and has left a lot of developers without a clear understanding of what dependency injection is, why it’s useful, and how to implement it. This article will address the what, why, and how of dependency injection.
Dependency injection deals with the concept of how we wire different elements of a program together. With the current push towards componentization of our applications this is an important concept to understand in order to build testable, and highly scalable applications.
Dependency injection is also often referred to as “Inversion of Control.” The term dependency injection turns out to be a more exact description of the usage of inversion of control for the problem context we are interested in. Before even delving into what dependency injection is, let’s state the goals and benefits of dependency injection. Through proper application, dependency injection can deliver a highly decoupled, highly reusable, very unit-test friendly, highly scalable, and very dynamically pluggable code base.
Although, you may not be aware of it, most developers have used the Inversion of Control pattern. A place where most of us have seen it is in the development of user interfaces. Remember back to the days when the user interface consisted of your program writing out prompts to the command line and waiting for user input. In this model, your application was in complete control. But, as we were pulled into developing user interfaces for the Windows world, suddenly things got more complex. Here the typical model became, register your event listeners with the various UI objects, and the UI will call you to process events. This is the Inversion of Control pattern. Your application is no longer in control of the main processing loop. Instead, you have given that control to the UI framework. So, Inversion of Control seems to be a pattern whereby you abdicate process control to another resource, outside of your programmatic control.
So, given that, now the question is, how does Inversion of Control relate to Dependency Injection? Well, a few years ago a few open source development teams began developing what they referred to as light-weight containers. Inversion of Control was touted as a primary feature of these new containers. This was the Inversion of Control pattern applied in a different area though. To illustrate this use of IOC, let me divert the conversation a bit to discuss a common development problem.
For this example, let’s assume we wanted to develop a simple program that would allow us to have a candidate for a given election selected for us automatically, based on compatibility of our values with those of the candidate. A simple object model of this program might look like figure 1.0.

Figure 1.0
In this model we have a CandidateChooser class which uses a CandidateEvaluator class to evaluate the candidates for us. So, we have a dependency between the CandidateChooser and the CandidateEvaluator class. There are 2 reasons why this dependency may be a bad thing, the first being that it makes testing more difficult, and the second being that it limits the re-usability of our CandidateChooser class.
So, instead of tying ourselves to a particular implementation of the CandidateEvaluator, let’s create an Evaluator interface, and make our CandidateChooser dependent on that. Now we can plug-in the particular Evaluator implementation that we want. So far, so good, but, we still have a problem. There still must be some place in our code where we instantiate a concrete implementation of the Evaluator interface. So, at this spot, we again have the dependency on the concrete implementation that we were seeking to remove.

Figure 2
Now, we’ve set the stage to get back to our discussion of IOC. We solve the dependency problem we ran into in the above scenario by applying Inversion of Control. We let an external container decide the concrete implementation of an interface to instantiate. We do not make that decision in our application code. This type of Inversion of Control is implemented through a technique we call dependency injection. Aha, we now see a relationship between IOC and dependency injection. Figure 3 shows our example with the addition of an external container performing the dependency injection.

Figure 3
When you want to get an instance of an object that is dependent on a container managed object, you ask the container to provide the instance. The container knows which concrete implementation of the dependent object to use and returns you an object with the appropriate dependency.
The next question we have to deal with is how the container knows which specific implementation of a dependent object an object should use. This step can be thought of as wiring all the objects in your application together. This requires a mapping of dependencies and implementations. This mapping is commonly either read from an XML file, or implemented in a separate class.
Dependency Injection and Unit Testing
Dependency injection brings improved testability as another of its benefits. Through the use of dependency injection, objects are no longer coupled directly to resource dependent objects, or heavy-weight container objects. Object dependencies can easily be mocked up and an object can be unit tested in isolation of other concerns.
Dependency Injection and Encapsulation
If you apply the dependency injection/IOC pattern throughout your code, you end up with a collection of objects, each exposing their dependencies through constructors or setter methods. Managing dependencies for this collection of objects is the lightweight container whose job it is to fulfill all the dependencies, thus creating a complete set of objects dynamically.
The fact that dependency injection requires all of your objects to expose their dependencies is sometimes pointed out as a criticism of this pattern. The thought is that this violates the fundamental object oriented principle of encapsulation. Strictly applying the principle of encapsulation would dictate that each object should know and be able to create their own dependencies, without having to expose those to other objects. What this really highlights is the fact that encapsulation should not be mandated so strictly. Strict adherence to this concept can cause all kinds of ugly design and coding workarounds to achieve desired functionality. There has to come a point when you recognize the limitations of any principle, and are willing to relax adherence to that principle when it makes sense and the net improvement in design is a positive one. Most people familiar with dependency injection do indeed consider it a net positive improvement in design and architecture. It actually applies encapsulation in a slightly different paradigm. It allows objects to focus on their intended functionality, without having to worry about the details of all the objects it may be using to implement that functionality. This can be thought of as functional encapsulation.
Dependency Injection and Factories
So, at this point, I’m sure that some of the readers are thinking to themselves. This all sounds pretty nice, but why not just use the factory pattern and factory objects. Isn’t that easier, and it eliminates the need for a container all together. Very good question, I think that dependency injection can be thought of as a further step on the design evolutionary path preceded by factory objects. First, let’s remember one of the goals here is to eliminate hard-coded object dependencies. So, if we are using a factory to create an instance of our dependency, we still have a hard-coded dependency in the factory, unless we externalize that into a configuration file. To take all the dependencies out of our main code-base, we end up with tons of factory objects.
Constructor Injection
Now that you have a basic understanding of dependency injection, let’s discuss two ways it is commonly implemented. The first way is called constructor injection. In this method, dependencies are passed as parameters to an object’s constructor at object creation time.
Setter Injection
The other popular form of dependency injection is called setter injection. Using setter injection, the dependencies are set using Java bean style setter methods on the object.
So what’s better, constructor or setter injection? There are vocal camps on both sides of that question. For example, the team that developed the Spring container favors setter injection, while the team that developed the PicoContainer project favors constructor injection. Ultimately, I don’t believe there is a universal best method here. You need to evaluate the two methods and decide which is preferred for your project.
Dependency Injection Containers
There are a growing number of frameworks that make dependency injection easier for the developer. These frameworks are most often referred to as light-weight containers. Currently, the best choices for a light-weight container are in the open source community. The two most common examples are Spring, and PicoContainer, both open source products. Both of these products have very good reputations, strong advocates, and large and very supportive communities. Spring seems to be gathering more and more steam and capturing more mind-share every day.
These containers allow you to remove hard-coded dependencies from your source code. Instead of in the source code, these dependencies are typically specified in an XML file. At runtime, the container then dynamically builds these objects and creates all the required dependencies.
While dependency injection is a primary feature of Spring, Spring also includes other framework components which are worth looking at and evaluating on their own.
Summary
So, having read through this article, I hope that you now feel better able to understand what Dependency Injection and lightweight containers bring to the table. This is such a hot topic currently that your certainly better off having that knowledge.
Until next time,
Timothy Fisher
Tags control, dependency, injection, inversion, ioc, j2ee, java, spring | no comments
Posted by Timothy Fisher
Mon, 21 Jan 2008 16:58:00 GMT
Over the weekend I finished reading the book The Rails Way. I actually enjoyed this book so much that I took the time to read it cover to cover. As good as this book was, it is not specifically the topic of this post. The last chapter of the book contains a series of statements by a bunch
of developers who have grown to love Rails. They explain what it is they like about Rails. Each of the statements is interesting, some more so than others. One of the very last statements, written by Nola Stowe, talks about the lack of community across languages and using the right tool for the job. This is what I want to talk about with this post.
Developers who speak extremely highly of a single language while criticizing other languages are being very closed-minded and are shutting themselves off to some great learning opportunities. Once you’ve mastered any given language, and even before you’ve mastered a language, one of the best ways to continue to grow your expertise of that language is to learn and study a new language. You may look at how something is done in a different language and that may inspire you to rethink how you are doing things in the language that you love. The Ruby on Rails framework is a great example of how implementation ideas in one language can influence many other languages. The Rails framework is one of the most innovative web applications to come along in any language. Rails introduced a simple way of building web applications using DSLs, convention over configuration, code generators, and a robust object relational mapping layer. Much of the core architecture of Rails has since been implemented in almost every other language that is used to build web applications. Frameworks in other languages such as Grails, Cake, Django and others all have borrowed ideas from Rails. Also, this borrowing of ideas is not a one way street. Rails was not designed in a vacuum either. While it is true that Rails did alot of new things, it too borrowed ideas from other frameworks and languages.
Consider PHP, this is a language that is routinely criticized as a language that creates some really awful applications that are full of spaghetti code. Is this the fault of the language? Of course not. PHP brought web application development to the masses and I’d venture to say that those developers that create spaghetti code applications with PHP would do no better in a different language. PHP5 actually introduced a pretty good object implemenation to the language and a good developer can write very good applications in PHP, just as a good developer can write good application ins Ruby, Java, or C#. Are there things that a Java developer can learn from PHP? I think so. I believe that each and every new language learned can teach you something.
Too often when you look for language comparisons you come across alot of articles, posts, and other content that praises one language and attacks other languages. If your a Ruby or Railis developer, you’ve probablyl seen the photo of the stack of books that someone put online a couple years ago. The photo shows a large stack of Java books sitting next to a stack of two Ruby and Rails books. The idea behind the photo being that Java is so complicated it requires tens of books to fully understand, while with Ruby and Rails you can get all you need with 2 books. Such a picture wouldn’t fare so well today. I’d venture to say that today Ruby and Rails related books are coming out at an equal or faster pace than Java books. Having alot of books out about a language and its various frameworks and libraries is in my opinion a positive thing. Java has a huge open source following and there are libraries available for Java that do almost everything you want. Having books available about these frameworks and libraries is not a bad thing and does not in and of itself make developing with the language more complex. With the surge in popularity that Rails brought to Ruby, the libraries are gettin better for Ruby but they still can not compare with what Java offers. In a similar vein, more recently there have been a series of videos that promote Ruby while mocking another language. These types of language hype may be entertaining but they are detrimental to the software development community at large in that they usually only breed more distrust and negative feelings across specific language communities. I believe that anything that discourages a young developer from learning a new language is a bad thing.
In the enterprise consulting world, you often hear that comment that such and such company is a Java shop, or a .Net shop, meaning that everything they do is in that language. I think that being characterized as a Java shop or a .Net shop, or a Ruby shop is not something a company should be proud of. For example, Rails has shown tremendous productivity improvements over other languages when developing database-backed web applications. A company that traditionally builds all of their applications in Java or .Net would be foolish to simply ignore this fact because they are a Java shop or a .Net shop. Similarly, Ruby is one of the coolest languages to be using right now. It has a dynamic and rapidly growing community, and the hottest framework on the planet in Rails. However, a project may come along for which there is an existing library implemented in Java which would allow you to complete the project quickly using Java, whereas in Ruby you would have to write this same library. Don’t choose to use Ruby because it is cool or the funnest language to use right now. Use a language because it makes sense for the projects your team is working on. JRuby brings even more interesting twists and scenarios. With JRuby it becomes easy to combine Java and Ruby on the same platform and within the same application. You could use the wonderful Java libraries while writing your new code in Ruby.
Neal Ford speaks of something he calls Polyglot programming. Polyglot programming is the concept of using many different language together even on a single project. The idea is that you should always be focused on using the best tool for the job. Today it is actually rare to write a web application using a single langauge. Your business logic may be written in Java, but consider other languages that you probably use without a second thought, JavaScript, SQL, perhaps a Perl script or too for maintenance tasks. The two primary platforms of today, the Java platform and the .Net platform, are both able to support a growing number of languages. For example the Java platform today supports Java, Ruby, Groovy, Scala and probably a bunch of lesser known languages. Each language may have strengths in a given area. Don’t be afraid to mix and match your languages even on a single project. Use the best tool for the job at hand. We should all be Polyglot programmers. Every good developer should expand their knowledge of languages beyond the one or two that they feel comfortable using. Even if you continue to use a single language, you may find a whole new way of thinking about that language when you’ve studied other languages.
Don’t let positive or negative hype turn you off from learning a programming language that may be outside of your comfort zone. I know that at first glance Ruby can seem very different to Java programmers. It is a dynamic, scripted language and that is a different world to many Java developers. I had been doing Java development for nearly 10 years before I learned Ruby. Now I advocate for Ruby every chance I get. I have not met too many developers who have given Ruby a real trial and have not come away with a positive experience, even if they choose not to use Ruby going forward. So in summary, don’t choose a language simply because thats what your company has always done or because thats the only language you know. I agree that those may in fact be important factors in what is the best choice for your team, but evaluate your optioins and use the right tool for the job.
Last week I attended a conference in Ohio called CodeMash. The theme of this conference is to bring together developers with different programming language backgrounds and have them learn from each other. I think the concept of the conference is wonderful. This is the second year that I’ve attended it and I will continue to do so in the future. We need more community across languages as opposed to just single language user groups and conferences. It would be great to see more user groups of different languages hold combined meetings with topics that are common to multiple languages. I think both groups can learn alot from each other.
Tags java, languages, php, programming, rails, ruby, .net | 2 comments