In Flaw #3: Brittle Global State & Singletons
you mention “# Adding or using registries” is a warning signal. However, most applications have some objects that need to be accessible application wide, or at least based on some context. How would we manage such objects without a registry?

In a Java web server, we would have to use registries and static attributes to manage user sessions, application scope, etc. I am not sure if these could be managed without registries and static attributes.

Overall, I do agree that usage of static attributes and registries should be minimized, but perhaps it is not possible to write an application without using them at all.

In “Flaw #4: Class Does Too Much” you mention “# Class has fields that are only used in some methods” as a warning signal. Again I agree, but at the same time there are cases where such usage would be valid. For instance in a DAO each attribute would not be used in all the methods. Also in UI components, each method will not make use of all the instance attributes.

Thanks for sharing your insights. It would be really nice if you can mention exceptions to the above in some future blog post.

2) If you insist on using Tomcat, or something else which does not allow you to do dependency injection, than you are right you need to have global variable where the world can communicated through. However, this variable should be closely guarded and only the constructor of the servlets are allowed to call it. Something like this

We will use the DI constructor for testing and only use the no arg constructor with the nasty global variable in production. The key is that ONLY the no arg constructor is allowed to talk to the Global variable! NO ONE ELSE is allowed.

It is TOTALLY possible to write an application without using global state. I have always write my apps in such a way.

LoD is a symptom. It is not a cause. The cause is that your object responsibilities are not ideal. So looking at the symptom it is impossible to come up with a fix until you can understand all of the pieces. This is what makes the LoD so hard to obey. The place where the mistake is made and where it is felt are not the same place.

Normally, I break my application into “zones” each zone are objects which have the same runtime. First are objects which live for the duration of application the singletons (Lower case “s” non global). These includes a factory which know how to create the next zone. The HttpRequest Zone. Those objects live for the duration of the HttpRequest and than they are garbage collected. Now a long lived object should never ask for a short lived object. So a singleton should not know about Request objects. But a request object can know about the longer lived (ie the singleton).

In your example the c.resolveB method seams to be in the wrong location. I think class A is long lived, but should be short lived. So when A is constructed it gets handed in B and the LoD problem goes away. If you tell me that there are reasons why A needs to be long lived, than I think you are mixing object concerns and A has too many responsibilities.

Basically you need to have some object FactoryA which is responsible for bridging the life-cycle of the two objects types. Each objects should be in the business of either graph construction or doing work. In your case your Class A does both, wiring and work.

Re: the warning about use of ‘new’ in a constructor. I understand we should pass in references to collaborators, but what about a Class that manages a List ? In the constructor one might use “new List()” to initialize the List. If the List is intrinsic to the class, why would it be folly to create it (empty) in the constructor? That way all your List based methods would at least have an empty List to work with. Is this the exception to the rule?

Thanks alot for your advice. You are right A is long-lived and there is no logical reasons why it should be. I use both EJB3 container and spring container. A, B & C are configured in spring, however A is injected in an EJB3.

One of the reasons why we use EJBs is because we found the tx management in spring to be awkward and prefer the EJB3 tx management approach. Since the EJB3 dependency injection capabilities are limited we still want to use Spring.

As you probably already know spring eagerly wires all objects on startup and in order to support smaller scopes than the singleton (“small s”) scope it uses proxies. Spring doesn’t come out of the box with a transaction scope even though I know it is possible to create custom scopes and use them.

So as you can see in my usecase its not trivial to make Spring (myfactory) to create A when the transaction starts and wire B at that point.

Do you think Spring falls short with managing object scopes?

PS: Your article and testing guide are great! Thanks for sharing the knowledge.

I strongly believe in keeping methods shorter than a screen. To this end, I create a decent amount of helper methods. These are great candidates for static methods if they don’t operate on fields and eclipse will help you realize that by making your method italic.

Further, taking apache commons io as an example, I’d much rather write:

I’ve been wondering about the Flaw #1: Constructor does Real Work. What if I have a class, that needs to do something before it’s really functional and properly set up. Who’s responsibility is it to make instantiated classes to do their initial setup work?

Say I have a RSSChangeListener which does something when a RSS feed is updated. RSSChangeListener’s constructor gets passed in a singleton RSSRepository. To start listening to the already existing RSS feeds, I need to ask RSSRepository for feeds the user has added. Then I start listening to changes to those RSS feeds. Of course later on the user can add more RSS feeds and my class needs to listen to those too.

How is the initial setup done? Whos responsibility is it to start listening to the already added RSS feeds? Constructor would be a nice place, because that way object is ready for use after being constructed by the factory.

Of course this problem exists with RSSRepository also. When does the RSSRepository read stored feeds from disk? And who tells it to do it? Whoever does that, must then tell every object relying on RSSRepository that now they can access the repository, because now it has its state properly set up.

If the factory initialization time is not the right time, what is? Do I need a separate class which just kicks every object created by the factories and tells them to initialize them to a sane state? With complex hierarchies of objects I’d need to make sure I kick my objects in the correct order and maintain that order when code changes.

Well written! However, static methods can be very important for reuse and logical reasons!! Couldn’t you just write each call to a static method inside an overridable protected method (which only purpose is to call the static method)? That way you have the possibility to override it for testing purposes…

Hi, Misko. Excelent blog post.In “Flaw #4: Class Does Too Much”, when you mentioned “Class has static methods that only operate on parameters” as a warning sign, how can we deal with classes that operate upon dates and strings, such as doing tasks like formatting and parsing? Those classes are common to have a lot of static methods that operate only on parameters..Is there a way DI can help with it?

[...] 1. December, 2008 at 17:21 | In Software | Tags: TDD Just stumbled over this article: “Writing Testable Code“. Apparently, it’s a set of rules which Google uses. While I’m not a 100% fan of [...]

[...] My point is that the most important thing a programmer needs is to learn how to write clean, testable code. Selenium and similar tools are useful, but secondary; what a programmer needs the most is to learn [...]

Hi,I watched two of your presentations on google and just read twice your pdf guide on writing testable code. I want to thank you, it was very enlightening. I intend to do a presentation to the developers in my company on that subject.Take care !

[...] that do nothing other than making simple assignments to fields. As Misko Hevery comments on his Guide for Writing Testable Code, constructors should do no real work. Mark Needham, in turn, advocates the simplification of [...]

Software are like plants. For Growing them you need to put in lot of efforts in the form of naming variables conspicuously and understandably, and follow several other guidelines (coding conventions). Your work is a must-ref for writing testable code. Thanks for making into it a readable and printable pdf format!

[...] at things I’ve put aside during busy times. Right now I’m finally reading through Writing Testable Code by the Google people. It’s good, if a little Google-centric (lots of references to Guice as [...]

[...] had the great pleasure of collaborating with Mi?ko Hevery and Russ Rufer in creating the Guide for Writing Testable Code. Please feel free to check it out, and leave comments here or on his [...]

I know it is a bad idea to inject collaborators simply to pass it on to some other collaborator, but how can you refactor the code when collaborator is method-injected simply to pass it to another method?

Example:
public void methodA(classX x) {
this.methodB(x);
…..
}

should I try to create another class, say C, to handle methodB, and method inject C to methodA?

In my experience the most important factor when testing are not the tools you use but how the code is written. If the code you’re trying to test is too coupled you won’t be writing real unit tests therefore testing will be harder and slower.

[...] Before I get more into IoC containers, let’s start with a simple dependency injection example. I will assume that you are familiar with DI and are aware of the advantages of constructor injection If not, I recommend reading this short intro to DI and then this guide about writing testable code. [...]

Regarding // No Arg Constructor required by API
It is possible to define some quality related annotations, e.g. @OnlyForContainer @OnlyForJpa etc and annotate the no args constructor with these quality annotations, so that it is evident to a developer not to use them directly.