My big aha moment in software development came when I learned to do Test Driven Development. The subjective and objective quality of my code has gone through the roof, and I was hooked. In this blog I want to share everything I know about good, testable software design.

On this page I want to hear from you! What aspect of testability would you like to know more about. Please leave your suggestions as comments and, I am looking forward to answering them.


295 responses so far ↓

  • Andy // Jul 25, 2008 at 12:52 pm

    Hi Misko,
    I really liked your article “Top 10 things I do on every project”. It is very well written.

    Could you please suggest me a good book on how to effectively do unit testing. I wish to learn how to test conditions, loops and exceptions etc.

  • misko // Jul 27, 2008 at 10:57 am

    I can recommend these two books by Dave Astels:
    * Test-Driven Development: A Practical Guide
    * A Practical Guide to eXtreme Programming

  • Michael // Sep 2, 2008 at 12:16 pm

    Hi Misko,

    first of all nice writing. I makes fun to read your blog!

    I think a very high testcoverage is good for any software project. At its best it is TDD.

    But what to do with existing project do not have any tests?

    And how to bring people in the office to write tests?

    Do you have any suggestions/books? I currently reading “Working effectively with legacy code” which answer Question. But question 2 still unanswered.

  • misko // Sep 6, 2008 at 9:55 am


    You ask excellent questions! but unfortunately I don’t have straight answers for you. Yes, the question you ask is what my job description is, but there is no one size fits all answer.

    I often use this trick described here if I know the exact behavior I want to get out of people. If the result can not be formulated like that, the only thing I know is to pair with people on their problems for few weeks and transfer my know-how / point-of-view to them by osmosis.

  • Philipp // Oct 26, 2008 at 3:09 am

    H Misko,

    I have a question regarding how Testing of the Graphical User Interface is done in the cycle of TDD? I didn’t find your email adress here so I am just writing a comment.

    Does GUI Testing play a role in TDD?

    I see how manual testing of the GUI is done, but that seems useless to me since you can’t really tell about the coverage of your tests. It should be possible to automate the whole process of creating a model of the GUI and then creating testcases based on the model. It differs from the testing you do I know. I am just curious.

    - Philipp.

  • Peter Gardner // Nov 14, 2008 at 12:48 pm

    I was wondering if you are still maintaining the Flex Calendar project on google code. Do you consider it complete?

  • Rino // Nov 19, 2008 at 6:26 am

    Hi Misko,

    Just watched your video on “Global State and Singletons”. Could you please provide me with some digital copies of the “review cards” you mention at the end of the talk? I’d really appreciate it! I enjoy watching your clean code talks.

  • Onne // Nov 20, 2008 at 3:30 am

    Hi Misko,

    I saw your googletalks about clean code talks. And I have a question; at one point somebody in the audience asked about some (global) error reporting thing (widget), which was used in so many places in the code, it would be hard (verbose) to pass it along all the time. So I think he was using a Singleton for it. (Verbose since almost all constructors need it, and every object would require to keep a reference to it in a field.)

    I guess this is a common problem for things like logging or other ‘environment’ things. How would you recommend going about?


  • misko // Nov 20, 2008 at 8:03 am


    The cards are not yet available externally, but we are working on it. Check back, we should have something ready by next week.

    – Misko

  • misko // Nov 20, 2008 at 8:10 am

    Hi Onne,

    Yes, Logging is a good example of this problem. Have a look at

    In general singletons are only problem if their state effects the execution of your code. So immutable singletons (such as enumerations and Logging) is not. Your application does not behave differently because logging is on or off.

    As far as passing it around it actually is not as big of a problem as you think:

    If you use GUICE, than injecting Logging is no issues. If you don’t than you can be pragmatic about it and just do static Logging.getLogger(). However if you need to write a test which asserts that a logger got called, than you have no choice but to inject it.

    – Misko

  • Rob // Nov 20, 2008 at 2:32 pm

    Hi Misko,

    I watched your presentations on testing on youtube.
    When watching the presentation on singletons I started to notice the big overlap between what you are saying about testability and dependency injection with respect to global state has the same thrust as what object capability people are saying about authority with respect to mutable global state.
    Great to see this amount of overlap. Unfortunate to see the approximate same style of coding seem to be used by apparent disjunct groups of people for disjunct reasons. Or is it? It would seem that the best way to do and promote dependency injection would be to use and promote object capability languages and paradigms? Or am I missing important differences between ocap style programming and dependency injection style programming?

  • Maxim Tihobrazov // Nov 22, 2008 at 7:44 am

    Hello Miško

    I have a question about such situation: for example there is a web application which allows a user to manage some data (a lot of boring forms and tables). There are users who manage their own info. So we have a lot of methods like: GetSomeData1By(user), GetSomeData2By(user). And nearly every controller needs to know about current user from session. Would it be better to use some global thing like SessionManager.CurrentUser?

    and second question: How do you feel about this pattern for unit tests?

    class SomeEngine {
    protected static Db _databaseInstance;

    class TestableEngine : SomeEngine {
    public SetFakeDatabaseInstance(Db fake) {
    _databaseInstance = fake;

  • Patrick Melody // Nov 23, 2008 at 7:27 pm

    I just watched your “Global State and Singletons”
    google tech talk. a suggestion about terminology,
    you might want to call “serializable” objects like
    CreditCard system objects, and “nonserializable”
    objects like CreditCardProcessor i/o objects. at
    least from your talk, it sounds like the former are
    components of the system you are developing
    (however you define the boundries of that system)
    and the others are essentially interfaces to things
    outside your system. would this be accurate, or
    am i missing some important cases?

    - Patrick

  • Jason // Nov 23, 2008 at 8:53 pm

    Hi Misko,

    I share the same views as you on development, architecture, and testing. I would be interesting in finding out about how we might get you to come by our company for a talk and if there is a fee?

  • Jason // Nov 23, 2008 at 9:14 pm

    Hi Misko,

    What is your take on GUICE vs. Spring?

  • misko // Nov 23, 2008 at 10:34 pm


    GUICE is much newer than Spring. GUICE focuses on constructor injection and Spring focuses on setter injection. I am not an expert in Spring, but I like construct injection a lot more than setter injections. So I am partial to GUICE.

  • Urs Martini // Nov 24, 2008 at 2:23 am

    Hi Misko!

    I really enjoy listening to your talks and keep lerning new things every time! Thank you for that.

    When I read about your Flex-experience I asked myself which Flex-Framework you would recommend.
    We’re using pureMVC wich is great but has some issues concerning Singletons and global state. Which one do you prefer? Is there an architectural framework which doesn’t rely on global state and which supports dependency injection at all?

  • misko // Nov 24, 2008 at 8:46 am


    Check out:

    Flex is a bit of a problem since it does not have constructor injection. All flex views must have no argument construct. You need to use data binding to assign to the views the controller. And it is easy to miss.

  • Urs Martini // Nov 25, 2008 at 12:34 am

    Hi Misko!

    You got me wrong. I didn’t aim at visual components but at as3-classes (having no problems with arguments in the constructor): proxies, mediators, controllers, etc.

    The problem is, that the framework sometimes does ugly things with Singletons, mixed business-logic and object-graph-construction.
    On the other hand I don’t know a better one – the great cairngorm-framework has it’s problems too. Can you suggest something?

  • Alan R // Nov 29, 2008 at 1:35 am

    Hi, Misko. Do you have any advice for injecting dependencies into EJB 2 stateless session beans?

  • Nilton // Nov 29, 2008 at 1:06 pm

    Hi Misko,

    I’ve watched all your ‘clean code talks’ series and I found them extremely useful. Congratulations!! Could you please provide me with some digital copies of the “review cards” you mention at the end of the talk? I’d really appreciate it! Keep up with the great work!

  • Daniel // Nov 30, 2008 at 6:41 am

    Hi Misko,

    I have been writing a lot of GWT code lately and since Guice is not available inside GWT client side code, it all became very untestable, because I had no DI-framework at hand to enforce best practices.

    After watching your Clean-Code-Talks Series I got inspired on how to restructure my application. The one thing that is very hard to refactor is a class called “Status”. This class accepts StatusListeners that get notified if something failed (like an RPC call failed). Inside the failing code I can write Status.error(“Could not communicate with server”) or something like that. The StatusListeners get notified and can then display a notification to give the user feedback.

    I identified the Status class as some kind of Singleton, or better as Global State, which is to avoid accoding to your talks. How can I restructure my application without having to pass an instance of Status down the widget hierarchy or without writing many Factories for all the places where Status updates could appear?

  • Randy // Dec 2, 2008 at 11:10 pm

    Thanks for helping me get a deeper understanding of the power of dependency injection. But, what about objects that get instantiated conditionally? If you “new” it up and pass it via the constructor, if the condition is not met it will not get used and resources will have been wasted.

  • Lukas // Dec 5, 2008 at 1:56 am

    First of all, thanks for Your blog and videos, it’s really helps to understand things more easily (I mean more easily than just reading a book or so).

    Another thing is a question:

    What do you think about development style then you start work from writing a test, and then actual code that you need to test. I think in this way of development you will automatically write a testable code.

  • misko // Dec 5, 2008 at 8:43 am


    I think you are referring to Test Driven or Test First Development, and it is the only way I write code!

  • nazgob // Dec 10, 2008 at 5:17 am

    Hello Misko,

    I’m wondering how do you fight issue called “class explosion” ? Or perhaps you don’t? How can we tell that inheritance tree is too complex? I often see it as a problem when I refactor legacy code. I tend do more classes as it also helps SRP but… how do decide if it too much and not pragmatic any more?

  • nazgob // Dec 10, 2008 at 6:56 am

    Hello Misko,
    One more question after watching your talk about global states. What about having factories as singletons? Is this ok as it’s a “leaf” or should we pass factory instance in a constructor?

  • David Hasovic // Dec 10, 2008 at 7:20 am

    Hi Misko,

    Dude your clean code talks are awsome. I think it helped me have my AHA moment. This sort of coding is so addictive!


  • Leon Franzen // Dec 11, 2008 at 12:12 pm

    Hi Misko,
    What’s your opinion on using mocking frameworks like JMock and EasyMock? Clearly using them as crutches to get coverage on bad code can be pretty harmful, but they certainly seem useful for verifying behavior of code under test when the expected behavior involves operations on one or more injected dependencies. Is this a bad pattern? Does it point to architectural problems? Are there better alternatives to using a mock framework, like creating test implementations by hand, shunting real implementations or magic?


  • misko // Dec 12, 2008 at 8:05 pm

    @ Leon,

    Nothing wrong with JMock or EasyMock. Great tools which make testing easier. However, be careful that if all you have is a hammer everything looks like a nail. I use JMock very rarely in my code. However, I find that people who have hard to test code often over use JMock. But that is not a fault of the tool…

    – Misko

  • Leon Franzen // Dec 13, 2008 at 8:53 am

    So what are your rules of thumb that you use to judge when code needs refactoring vs. application of the JMock hammer?

  • misko // Dec 13, 2008 at 10:18 am


    Easy, my rule is don’t train more than two mock, never train a mock to return mock and should not be trained with more than four calls.

  • Liam Knox // Dec 25, 2008 at 11:15 pm

    Hi Mitsko

    I have just stumbled on your Clean Code talks. I have viewed a couple and find them generally very good. I do however think the views of reducing preconditions checks contentious.

    From you example is you are saying new House(null) should be allowable for testing basically your are infering that the state of a House is valid without a Door. In the live system however you may want to ensure this is NEVER the case. So by nature of the reduction of one NOP object you have increased the chance to the API failing in production.

    I dont really think the arguement of just because paint() does not involve door you should compromise the whole system stability. You can quite easily infer this in JavaDoc what the test is exercising, furthermore the test may change to exercise Door downthe line



  • Jason // Jan 3, 2009 at 7:25 pm

    Hi Misko,I have seen many posts of yours that talk about global state being undesirable and to avoid the use of singletons.  However, I am not quite sure where you stand on the use of Singletons…that is a single instance for the entire JVM.  This is the only type of Singleton that I believe in and I use this for a one main reason:  1) performance…sometimes you want to create a single instance and reuse it in many applications for performance reasons.  In this case, I often use a static method method, getInstance(), to ensure there is only one instace.What are your thoughts on this?Recently, I have been using a new approach by having a “global” MBeanServer and register the MBean with that server.  Since the MBeanServer can have only one object with a given ObjectName, it essentially allows me to have a Singleton for that ObjectName without using the Singleton pattern.  This removes the Singleton and the static method which makes it easier to be tested.What are your thoughts on this approach?Jason

  • misko // Jan 3, 2009 at 10:07 pm

    Singletons are bad idea, because they cause JVM global variables.

  • Shahar // Jan 4, 2009 at 6:35 am

    Hi Misko,First I would like to thank you for the “Guide to Writing Testable Code”, which really helped me to think about better ways to organize my code and architecture.Trying to apply the guide to the code I’m working on, I came up with some difficulties. Our code is based on external frameworks and libraries.Being dependent on external frameworks makes it harder to write tests, since test setup is much more complex. It’s not just a single class we’re using, but rather a whole bunch of classes, base classes, definitions and configuration files.Can you provide some tips about using external libraries or frameworks, in a manner that will allow easy testing of the code?Thanks,Shahar

  • misko // Jan 4, 2009 at 12:23 pm

    @Shahar, here is the information you are looking for:

  • Tom // Jan 6, 2009 at 5:25 am

    What approach do you recommend when unit testing classes that need to create / delete files? I’ve pulled out file creation code into a FileFactory that I can mock – and which returns a File that I can also mock. I’ve used EasyMock for this – but it means that I have a mock returning a mock – which you advise against…public class FileFactory {    public File createFile(String pathname) {        return new File(pathname);    }}

  • misko // Jan 6, 2009 at 9:44 am

    What you are doing is correct. The issue is that File shoul be a value objects / newable. There should be no reason to mock it out, you should be able to just call new on it. After all you would not mock out a String, so why is File different. If you are using than java breaks the rule of newable. So you have to either 1) mock it as you are doing or 2) creat your own File class which you can new. Sometimes we have to pay for the mistakes of others.

  • Patrick // Jan 6, 2009 at 9:54 am

    Hi Misko, I really enjoyed reading (and watching) your material and it’s really helped me reorganize my code. Actually, while testability is great, I’ve primarily gained a lot in better structured, more usable, better API code from using these principles.But I’m having a problem refactoring away some particularly sticky Singletons (capital S) that are used all over the place by hundreds of objects. These Singletons are potentially accessed by thousands of dynamically instantiated objects at various levels. The DI solution of just sticking it in a factory that constructs the entire object graph at startup is not feasible. I’m using C++ so a DI framework is not really feasible either. Additionally, if every single object needs to keep a reference to these singletons then memory use will skyrocket.I would really like to see you elaborate on how to correctly structure code where let’s say a logger object needs to be accessable from every single place in a codebase (because logging needs to be able to happen anywhere). The only way I can see to avoid a Singleton is to inject it into every instantiation of every object at every level, but that gets out of hand and seems messy and annoying, although it fixes testability and makes for a “truthful” API. You may say, well you have a badly designed object graph, and maybe so, but there are objects from time to time that need this kind of “super accessibility”. How do I deal with this? Maybe I have a higher level problem I’m not aware of, and your discussion of the matter would help me see it.Also, can you recommend any good books on structuring code that discuesses dealing with these complex real world situations in a pragmatic way?

  • Jason // Jan 6, 2009 at 3:50 pm

    Misko,I recently came across a Singleton scenario and I am not sure there is a good and easy solution for refactoring so that it is no longer a Singleton.  The class is a custom class that extends a JAXB generated class.  This class is created by the JAXB framework when parsing a XML file.  Therefore, the class is not created by the IoC/DI container and thus I have not been able to find a way to inject a needed dependency that is being used in many places.  Also, this dependency most only have a single instance or there is a huge performance hit.  The only solution that I can think of is to add a static method getInstance() on that class so that the class instantited by JAXB can access the same instance instantiated by the IoC/DI container.  I have tried “autowiring” but have found that IoC/DI containers don’t autowire classes they don’t create.  Alternatively, I guess I could try to do something clever with AOP in order to avoid the getInstance() method.  How would you handle this problem?

  • misko // Jan 6, 2009 at 10:11 pm


    You are right. When other un-testable libraries make our life hard we have no choice but to fight static with static. My suggestion is to create a Singleton as a form of communication but make sure that your code uses proper dependency injection and only use the Singleton inconstructor to bootstrap yourself in the factory. Look at my latest post on testing third party library.

  • Matt Wilson // Jan 15, 2009 at 11:29 am

    I’m a python programmer, which is a dynamic language.This blog [1] makes some interesting points about how maybe DI isn’t needed in python because it is so easy to alter the module namespace during runtime.Instead of forcing every dependency to be passed in as a parameter, in python, we can replace the real module-level objects with fake ones.What do you think about that idea? More generally, do you have any different advice for programmers using languages where everything can be manipulated at runtime?[1]

  • Markos Charatzas // Jan 16, 2009 at 7:22 am

    Hello Misko!Thanks for all your thorough articles on testing. It’s really life changing :) Could you please give us your perspective on:”Testing Private Methods”?Thanks. Keep them coming!

  • Steve // Jan 19, 2009 at 4:15 pm

    Hi Misko,I would like your opinion about where dependencies should live in the following example:I have a user interface that gets a command factory injected into its constructor. When the user performs an operation, such as clicking on a button, the following code gets executedvoid OnClick(object sender){    ICommand cmd = commandFactory.CreateCommand(“MyCommand”);    cmd.Execute();}The problem is that MyCommand has some dependencies, and I don’t really want my UI to know about those dependencies. Is this typically handled by storing references to the dependencies, such as the application model, inside of the command factory, or is it preferred to pass arguments to the CreateCommand function?Thanks. Your articles rock!

  • misko // Jan 19, 2009 at 8:52 pm


    It depends on your situation. But it sounds like your factories should have the dependencies injected in them.

  • Chris // Jan 20, 2009 at 11:11 am

    Hey Misko -I understand that dependency injection is good.  However, I’m still working to grasp the entire picture.Who does the object creation and how does that fit into a project structure?  Assuming we’re doing everything manually, where to the factories fit into the picture?I understand that DI frameworks take some of this out of view, but I want to understand how things would happen without the frameworks first.Does anyone have a good blog entry on this aspect of the project?  I just find that you tend to mention it in passing a lot – that everything will get built, but I havn’t seen much in the way of specifics as to how you would structure that.Thanks,Chris.

  • misko // Jan 20, 2009 at 10:04 pm


    perhaps this can answer some of your question

  • Simon Gunacker // Jan 22, 2009 at 1:38 am

    hi misko,i have seen your speech on replacing ifs by polymorphism’s very well explained and thus easy to understand.I was trying to refactor an xml-parser which looks like this:while (p.hasNext()) {   switch (p.getEventType()){   case START_ELEMENT:   case CHARACTERS:   case END_ELEMENT:   …   }}i created an abstract class called event which is subclassing a start_element-, a characters- and an end_element-objects.start_element and end_element are still abstract classes subclassing some specific start-/end-elements.all of those objects are supposed to “build up” a few huge person-objects according to the information given in the parsed xml.well, the point is: i am struggeling with my objects and how to wire them together to perform their actions.My parser is just about 20 lines of code, so i wonder if i could just send you my stuff over together with some thoughts i have. Maybe you would be so kind to reviwe it and then give me a helping hand on it.regards, simon

  • misko // Jan 22, 2009 at 7:27 pm


    sure, send me the code snippet. But I gave up on XML parsing long time ego. Check out XSTream, it probably does what you want.

  • Tim // Jan 24, 2009 at 10:39 am

    Hi Misko,First, let me thank you for taking the time to share these best practices & taking the time to answer individual questions.I’ve started refactoring some code, and I wondered if you could shed some light on the best way to handle errors to keep the code testable. Exceptions or Error codes ? I know it’s an heated debate, but I was wondering if one solution was more suited for testable code. Any idea ?Thanks :)

  • Simon Gunacker // Jan 26, 2009 at 12:45 am

    hi misko,have you already got some ideas concering my issue about replacing the switch statement with polymorphism in an xml-parser.regards, simon

  • Leon Franzen // Jan 27, 2009 at 6:15 pm

    Simon, try using ANTLR.  I think it uses the visitor pattern to handle each case.   They may already have a grammar for what you’re trying to parse.

  • Leon Franzen // Jan 27, 2009 at 6:24 pm

    Oops, sorry for cluttering the comments.  Didn’t see that it was XML.

  • Tom // Jan 28, 2009 at 4:42 am

    “Easy, my rule is don’t train more than two mock, never train a mock to
    return mock and should not be trained with more than four calls.”How would you avoid the problem of  ‘too many mocks’? Usually it indicates a code smell – if it seems hard to test then it is probably doing too much – therefore refactor. But sometimes this does not seem possible. “Nothing wrong with JMock or EasyMock. Great tools which make testing
    easier. However, be careful that if all you have is a hammer everything
    looks like a nail.”Can you expand on your views on mocking frameworks and best practices? Thanks!

  • knot // Feb 5, 2009 at 1:10 pm

    Hi Misko,If I understand you correctly, you are advocating that object construction should be done in a separate place, and then used later on by the business logic.However, in cases where object creation happens all the time, not just initially, how do you suggest we organize the code. Specifically, how do you handle instances like GUI interactions that result in new objects being created in the model.In such a case, it seems like the only thing to do is to inject a factory into the model, and then let the model call the factory to create new objects. Is this the right approach?Thanks for all your articles!

  • misko // Feb 5, 2009 at 1:53 pm

    There are certain set of objects which can be always newed up. Check out

  • Morten V. Pedersen // Feb 10, 2009 at 3:42 pm

    Hi Misko,One question: When trying to refactor some code to use DI and factories, I run into the following situation – I’ve created several layers of factories base on the objects lifetime e.g. the application factory creates the server and uses DI to pass a session factory which the server uses to create new sessions etc. Basiclly when I want to test this code I suddenly have a dependency on the session factory in my server test – should this be solved using mock factory creating mock sessions? Basically I guess I’m asking whether you create interfaces to your factories so that they are mockable?

  • Christian // Feb 18, 2009 at 1:29 pm

    Hi Misko,first of all a great thanks from me for your blog. This is really awesome. I do know and practise DI for some time now, but I guess I didnt use it right in all circumstances. I do have a question though.Today I wrote a very little plugin that just imports projects in eclipse, so that I am able to call this from a script (its a headless application), so that I can automatically import and share projects. Since this was a very little program, I followed your advice and tried to eliminate every “if” i came about.All my “ifs” were now in my Factory code. But I did have one place, where I wasn’t very satisfied. The problem is this:Since this should be a good behaving application, it locks the workspace, so that no other eclipse application can use this workspace.And the application also does nothing, when the command parameter that states the name of the project is missing. So I do have one factory that checks the parameter and either return a noop command or the real importer command. No big deal. The problem came up, when I tought about the locking. My idea was, that I first lock the workspace before everything else. If the locking fails, I do nothing. So I wrote a factory that either returns a factory being able to create my command, if the workspace is locked, or it returns a factory that always return a noop command.The code looked very beautiful except for one thing: the first factory that return the command factory executes the locking code and decides on the result. This looks a bit like mixing business code with object creation code. But I didint have a better idea.What would u do?Greetings,Chris

  • misko // Feb 19, 2009 at 9:30 am


    Sounds like you are very much on the right track, and I am happy to hear that you are trying to eliminate the ifs. You are right that usually we do not want to have any ifs in the factories, but that is not a hard rule. I suspect (but don’t know for sure without looking at your code) that there is an impedance mismatch between the locking API and your desire to have if-free code. So your if may be unavoidable. Example of impedance mismatch is a Hashtable. Calling get() requires to check for null. If you could pass in closure into hash table as to what needs to execute if nothing is found than you could get rid of the if. The point is that when facing external APIs which are not written with “if-free” code in mind you may have no choice but to use an if when calling these APIs.

  • Christian // Feb 19, 2009 at 4:07 pm

    @MiskoThanks for your reply. I think I understood your point about the impedance. What I did not fully understand, is how I can get rid of the ifs in the factory code. I would really like to discuss this with you, but I am unsure if you are really willing to spare your free time for this kind of stuff :-) )) If you wish, I could send you this code (its really small). And I guess that it would help me a lot.Greetins, Chris

  • Christian // Mar 5, 2009 at 3:18 am

    Hi Misko.I was thinking the last days about a problem with removing ifs in code. As you said, any state information that is checked via ifs can be replaced by other non-if code. And you made impressive and intuitive examples.I was thinking about your compute-node example (how to represent 1 + 2 * 3 in nodes in a tree).  The thing I was missing in your example (and thinking about for the past days) was how does the tree get build? For example assume there is a input string and this gets parsed and the output of the parser is the node tree. I was thinking about this parser part. How can this code be if-free? My first thoughts were that the parser must decide on the input characters and then create the neccessary nodes in the tree. And I could think about a way to loose all ifs.Then an idea struck my mind. I could create a NodeFactory that has a map where the keys in the map are the input character types (in this example values and operaters). The values of the map are information or classes or factories, that help in creating the nodes. Now the parser only has to ask the nodefactory about a node for a given type. And the factory itself just uses this type information as a lookup in the map and then creates the node. –> no more ifs.What do you think about this solution?Greetings,Christian

  • misko // Mar 9, 2009 at 7:21 pm

    Building tree requires a parser. Parsers have notoriously lot of ifs. the reason is that you are trying to dispatch different behavior depending on  what character you have next. Plus it is double level. There is a lexer which turns characters into words and a parser which turns words into grammar. 

    yes you could get rid of the ifs by using hash-maps but that is just a different kind of switch statement. There are certain things where ifs will always be, specifically when, working with primitives. But when dealing with classes you can go a long way without them.
  • Christopher // Mar 10, 2009 at 5:17 pm

    Howdy. You say that code in the constructor should be very limited – mainly just field assignment. Where would you put logic that handles input validation? Input not just as in dependency building, but input data of different kinds too. Would that be a layer above? There can be “broken” objects if used wrong?

  • misko // Mar 10, 2009 at 9:29 pm


    It should not be the responsibility of the Value object to know how to validate itself. Instead the responsibility falls onto the class which reads the data from the form and constructs the value object.

  • Tim // Mar 12, 2009 at 4:30 am

    Hi Misko! How should I avoid having a Mock that returns a Mock? I’m mocking HttpServletRequest, but I’m also mocking out the HttpSession that it returns – is this wrong?
    request = createMock(HttpServletRequest.class);session = createMock(HttpSession.class);expect(request.getSession()).andReturn(session);(I’m using EasyMock)

  • misko // Mar 12, 2009 at 7:49 am

    The fact that you have your mock return o mock is a sign that your objects are breaking Law of Demeter. See: The issue here is that Servlet API is horrible in this respect and you have no choice but to de it. But the issue is with the API. Your code should extract what it needs from the HttpServletRequest/Responso and not pass these objects around your code. There are some great Servlet frameworks which do a good job insulating you from it. (WebWork for example)

  • Amol // Mar 12, 2009 at 10:01 pm

    Hi, Misko. I like your blogs very much. It changed my programming drastically to good. I have a question though. Your emphasis on no “new”ing inside business logic makes sense, but for some situations it can be tricky to do so. Let me give an example, when you use State design pattern, the Context object does not wants its clients to be aware of the internal state, so it may encapsulate them and may need to “new” the default or initial State in the constructor. What to do in such cases? Where I don’t want the client to be aware of the internal objects I’m using and want to also be able to test that class in isolation.

  • misko // Mar 13, 2009 at 8:42 am


    I think your questions may be answered here:

  • Leon // Mar 13, 2009 at 5:26 pm

    Can you comment on dependency injection and its relationship to the need for end-to-end tests vs. smaller scale tests between modules and classes?  There is some disagreement at my company on how much we should focus on each type of test.  Our test suites lean heavily toward the end-to-end side of the spectrum which leads to extensive setup and long build times.  I’m trying to find some evidence that dependency injection can lead to smaller component level testing which in turn can replace the need for so many heavy weight tests.  Although I believe this to be the case, I’m not successful in finding hard supporting evidence.

  • Simen // Mar 17, 2009 at 12:56 pm

    I really enjoyed your articles and it’s definetly made me start thinking. I’m trying to apply this to my AS3 projects but I somehow always end up struggling with the bucket-brigade problem. This is where you have a deep structure of nested “views” that all want to communicate with a controller, read data from a model or utilize a service but that would require you to send along the dependencies of each view to the next into infinity, resulting in the easy way out; Singleton pattern.

  • Sridhar Visvanath // Mar 26, 2009 at 1:58 pm

    I am a great fan of TDD as it evolved my design in a big way. I like the philosophy, application and its impact on my design.  I also like tools like Clover that help measure code paths that have been hit / not hit.Since I have used these features (TDD, refactoring, refactoring to patterns) etc for more than 2 years now, my gray area is pretty much around metrics. For instance, if I run my unit tests I can use code coverage tools which looks at instrumented code and give me metrics. if I however, run a test automation which does let us say UI automation / Service automation (where code path is hit from some other machine etc)Can I till use code coverage tools to measure the coverage. I mean is there a good way to use my instrumented code base

  • misko // Mar 26, 2009 at 7:19 pm


    Great question. I think the answer will vary depending who you ask, but here is my opinion. End-to-End tests are valuable, but the coverage is misleading. You can do a simple operation (such as login, create a record and logout) in your application and get high coverage say 30%. The high coverage is because even the simplest operations such as login/out and CRUD exercise most of the frameworks in your application. But what are you really asserting on the end of this operation? Not much. What about your confidence that the code works as intended. Again not much, certainly less that 30% of coverage you got. For this reason, I think code coverage is of very little value with end-to-end tests. But the opinion of others may very.

  • Riccardo Tarli // Apr 14, 2009 at 1:20 am

    Hi Misko,
    First of all I wish to thank you for your interesting and inspiring blog.
    I’m going to introduce my dev team to your testability guidelines and I already know that someone will raise some objections. To prevent that I’m reviewing some “real code” to show how it can be refactored in order to improve usability. Recently I faced the following situation (C# )

    public void Foo(MyClass fooObj)
    if (fooObj.InnerMethodA() == true)
    // Demeter law violation!!
    int x = fooObj.InnerMethodB().InnerInnerMethodC();
    // other stuffs

    Assuming that fooObj.InnerMethodB() returns an object of class MyClassB, I think that a possible refactoring is:

    public void Foo(MyClass fooObj, MyClassB innerObj)
    if (fooObj.InnerMethodA() == true)
    int x = innerObj.InnerInnerMethodC();

    And the caller will call this method as:
    x.Foo( foo, foo.InnerMethodB() )

    The objection I can hear raising is: “The new signature is error prone: someone can call me as
    x.Foo( foo, otherFooObj.InnerMethodB() )
    Previously this was impossible, or at list limited to the point where the MyClass foo onbect was constructed.”
    What’s your opinion about that?

  • misko // Apr 14, 2009 at 12:43 pm


    One possible way to solve this is to have MyFlass have methodC() which forwards the call. However, without real example it is hard to follow and give advice. :-)

    – Misko

  • Pimm Hogeling // Apr 16, 2009 at 6:29 am

    Hi Miško,I’ve seen your “clean code talks” on YouTube and you point out some good points I tend to forget at some times.Because I’m writing an ActionScript 3.0 framework, clean code is really important. After all, if my code is not clean writing clean code on top of my framework will become difficult.Thanks for sharing your knowledge!

  • peter // Apr 16, 2009 at 5:00 pm

    Hi. Just found your website. Great!! Here’s a short question. Does Dependency injection / inversion of controll break “Information hiding” ??


  • misko // Apr 16, 2009 at 6:27 pm


    I don’t think DI breaks Information Hiding. Why do you think it does?

  • peter // Apr 17, 2009 at 1:52 am

    Its not me personally, its a coworker and here is the begining of his argument… .>>”Control should never be given to the consumer because it means that the consumer would have to posses a detailed knowledge of collaborators and internal workings of the provider (the thing the consumer is using). This is why I don’t like the constructor technique … it goes against every hormone in my body!”
    I was curious on your thoughts  about thatThanx

  • misko // Apr 17, 2009 at 6:18 am


    But the consumer (the one who is collaborating) does not know anything about my constructor. The consumer asks for the object in its constructor as well. Everyone knows exactly what it needs and nothing more.


  • peter // Apr 17, 2009 at 6:41 am

    @Misko> Thank you … I thought I was missing something. Thats what I suggested to him, but  I think I’m going to have to read your posts on changing developer behaviour to learn how to deal with him.
    Thanx again, I’ll definetly be back with lots more questions on different subject matter, now that I’ve found your site .
    Thanx again- and have a great weekend.

  • igor // Apr 20, 2009 at 12:59 pm

    I would be interested to know your opinion about interaction testing.Thanks

  • Titi Wangsa bin Damhore // Apr 26, 2009 at 10:20 am

    I have a question regarding dependency injection.say i want to create a classcall it, WebGetTaskWebGetTask would need a dependency to HttpServicebad code 1Code:private HttpService httpService;

    List<WebGetTask> list = new ArrayList<WebGetTask>();
    list.add(new WebGetTask(httpService));
    …ok. i know this is bad, because httpService is injected, but its never used, except for the creation on a new WebGetTaskokbad code 2Code:private WebGetTaskFactory webGetTaskFactory;

    List<WebGetTask> list = new ArrayList<WebGetTask>();
    …i think this is better, because we use a factorybut…but..from where i’m standing,i can see thatin WebGetTaskFactorywe are still injecting a HttpService and not doing anything to it except for the sole purpose of creating a new WebGetTasksoto recapmy question ishow do i design a factory class (WebGetTaskFactory), that creates new objects (WebGetTask) when the new objects require a dependency (HttpService) on their constructor without simply injecting and passing the dependency (HttpService) ?or rather, is this the way to do it? if so, then it’s all good, if its not, then please guide me to how to properly use DI and factory pattern.thanks.

  • misko // Apr 27, 2009 at 7:57 pm


    instead of asking for httpService or factory, why can’t you just ask of the object which you need. In your case it is WebGetTask.

    Is this class supposed to be a factory (in which case the new operators are justified) or application logic (in which case no new operators)?

    – Misko

  • Titi Wangsa bin Damhore // May 3, 2009 at 10:12 pm

    i seebasically what i need is a list of WebGetTaskso is the a better solution?public void process(List<String> list){List<WebGetTask> tasks = webGetTaskFactory.createTasks(list);//process them}—WebGetTaskFactory(HttpService httpService){//assign}public List<WebGetTask>  createTasks(List<String> list){List<WebGetTask> list = new ArrayList<WebGetTask>();for(String item: list){list.add(new WebGetTask(item, httpService);}return list;}i think my question is more on the WebGetTaskFactoryits in the business of creating objectsbuti just passed in httpServicethe WebGetTaskFactory does not do anything to itexcept use it in the construction of a new WebGetTaskdoes that violate the law of demeter?or simply putDoes injecting something to a factory class but not using it (except as a constructor for a new class), violate the law of demeter? If not, is it bad? If so, what’s the alternative?

  • Ela // May 15, 2009 at 1:27 am

    Hi Misko,I attended your talk at GeeCON ( hope your vocal cords are back to normal now :-) ) and would like to ask a short question. My boss knows about TDD but won’t allow us to use it because he thinks that it is just a passing hype that everyone talks about but no serious, big projects actually use it on daily basis. How could I convince him that it is not so?

  • misko // May 16, 2009 at 2:14 pm


    I have tried to answer your question here:

  • Jakub Gwóźdź // May 19, 2009 at 9:44 am

    Hi MiskoI’d like to learn more on best practices of organizing test data for unit test. I mean – my program saves it’s configuration in .xml through XStream and it worked well.But recently I went into testing spree and now I spend my time writing tests for everything.So I’m testing my class. I worked a solution in what I have “testData/config” directory in which I have tons of testThis.xml, testThat.xml and so on. And in I have tons of @Test that reads these xmls and performs relevant checks.This works, but I’m not too sure if this is the best solution. Is there any better?(Of course initialization/configuration xmls are just an example here, it could be any longer than single line of text data, even binary one)Regards

  • misko // May 19, 2009 at 8:09 pm


    sounds to me as if you are trying to test your application an a functional level. This means that your tests instantiate the application very close to what is in the production. My suggestion would be to do more unit tests, where you instantiate just a handful of objects and perhaps few mocks. Config is a wiring problem, which is what functional/scenario tests are good at. On the other hand testing if your ifs and loops are correct you need unit tests which are a lot more focused. If may not be obvious how to break a large piece into smaller pieces which are unit testable, but that is where the trick lies.

  • Jakub Gwóźdź // May 20, 2009 at 12:40 am

    Okay, my tests works (and instantiate) only one class, sometimes with it’s direct collaborators. It’s not warming up whole system, but still I think I’ve got your point. I brought “” as an example here, but what concerns me are best practices in organizing test vectors and results in situations where single line of text in parameters or results is not enough. And it is even more important in more complex tests when I get a set of input data (binary, xml, whatever) that caused problems and want to perform test against them after each full rebuild.

  • misko // May 22, 2009 at 11:33 am


    You should have both kinds of tests. Few end to end tests and lots of unit-tests. Sounds to me, that when you have complex configuration you should have larger test which proves that the configuration works, but do most of your testing on unit test level. 
  • Martin // May 27, 2009 at 3:16 pm

    Misko:I have been reading your posts and I am trying toimprove the testability of my designs. I am having a hard time though, with the application configuration files. In our apps, the support team is in charge of deploying and supporting the applications and they usually do it by editing a config file where many application setings are placed, e.g, timeout values, error codes, external web service URLs, constants that specify whether a specific patch or workaround is to be used, path to temporary file folders, etc. Right now those are global constants (thus evil), but they are useful from a support point of view, because they know that all the parameters they can tweak in an implementation are in one place and they dont need to be developers to understand them. How would you go about to be able to have a centralized configuration file and have the parts of the app that need those settings to get them, without a Environment objet that gets passed around in every method?Another example of frequently used global state would be constants, for instance: if  (currency = Money.USD)is more readable thanif (currency = 48) //Or whatever would be the currency codeBut you have there a static property, therefore a hidden dependency of the code to the Money class.How can I get the benefits of those static constants without passing Money objects all over the place?

  • misko // May 28, 2009 at 9:18 am


    I would solve this with GUICE.

    1) Have a parser which reads all of the configuration parameters from the file and configures GUICE injector
    2) For each parameter you need to do something like bindConstant().annotatedWith(“”).to(valueReadOutOfConfigFile);
    3) Then anywhere in your code you can ask for the constant like this. MyConsructor(@named(“config.port”) int port){};

    No global sate no, passing around context object. Each class just gets what it needs, nothing more.

  • Martin // May 28, 2009 at 12:18 pm

    …@named(”config.applyPatch”)boolean USE_PATCH;if (USE_PATCH) { //Patched logic} else { //Normal logic}

  • Martin // May 28, 2009 at 12:21 pm

    Isnt there a dependency of the code from the injected values? Those injected constants aren’t  some kind of global state? What if people start to use them as global constants?How different would that be to a registry/config object with the constants that is globally accessible, maybe via a singleton, which can be mocked out for testing?Your example uses the config values as constructor parameters, would it be ok to use them inside the code too?…@named(”config.applyPatch”)boolean USE_PATCH;if (USE_PATCH) { //Patched logic} else { //Normal logic}

  • misko // May 28, 2009 at 2:40 pm


    nothing wrong with global constants, provided they are truly constant. PI is a constant and it creates no issues. The problem is when you have global mutable state. Then all hell breaks loose. Problem with a central repository is that everyone knows about it and as a result the code is not reusable and it is hard to figure out which class is influenced by what. When you make it explicit and injectable than everyone knows only what they need and it is easy to see what variables each class is dependent on.
  • Tom // Jun 2, 2009 at 4:16 am

    I have a question about testing abstract base classes. From OO perpective such classes are valid (code resue) but when it comes to unit testing them there are problems when using currently available frameworks. Do You know any method except custom inheritance and tests written as part of a subclass.

  • misko // Jun 2, 2009 at 9:39 am


    When you TDD you create a class A and than class B with tests. You than realize that A and B need to have a common base class and you create it. You still have the tests and full code coverage. Your question only makes sense if you write tests after the fact, which is not the best way to do it. When you TDD this situation never comes up. Same question is how do I test private methods or state.

  • Tom // Jun 2, 2009 at 12:49 pm

    @Misko In the situation you’ve mentioned that’s 100% correct. But what happens when your code base evolves and you decide to add new funcionality to the base class? How would you test it then? Isn’t it so that deriving class is a client and should be mocked to check if base classe’s contract is met? What is more in your approach one would have two tests (for both A and B) which would test the same thing in a base class. That would be code redundancy – if my base class changes I have to change tests for all my derived types.

  • misko // Jun 2, 2009 at 1:44 pm


    Again, you add functionality because you have a tests which describes a scenario which describes the new functionality. And than you implement the code to make the code pass. So as long as you do Test First the question is bit misdirected. So I do not have an answer for you.
  • Olivier // Jun 7, 2009 at 7:14 pm

    Hi,I’m trying to build a simple Java SE app using MVC. So far, everything went right until I had to create new views based on user input. For example, I have a Login form that needs to open a Dashboard form once the login is successful.Now, I’m wondering who is responsible for creating the instance of the Dashboard? Also, I have some data that needs to travel from the first form to the second (a User object created from the login credentials entered by the user). The second form request this data as a parameter in its constructor. Currently, it’s the controller of the Login form that creates the Dashboard…I hope this doesn’t sounds like a “please write my code” question but without a concret example, this situation is somewhat hard to explain.

  • Craig // Jun 10, 2009 at 4:46 pm

    Hi Misko,Thanks for all your efforts, the content you have provided is an invaluable aid to developers.My current challenge is that I am working with a team of junior and offshore developers that have not yet grasped some of the basics of OOA/D.  Much of the content you provide here would be too advanced.What would you consider as the current best resources for giving people new to java a solid foundation?Thanks

  • misko // Jun 12, 2009 at 12:23 pm


    I don’t have any special secret sauce unfortunately. Getting good at OO takes years of mistakes. :-) but the should be a good start as what to do and what to avoid.

  • misko // Jun 12, 2009 at 12:28 pm


    Usually you have ApplicationFactory class which is responsible for wiring the whole thing together. The AppFactory creates a LoginForm. The LoginForm takes DashboardFactory in its contstructor. So when the login is done it simply says dashboardFactory.create(username_or_anything_else_to_pass). This way the LoginForm has no idea how to create dashboard only that a dashboard needs to be created. The ApplicationFactroy is then responsible for creating the DashboradFactory and fitting it with anything it needs on behald of the DashboardForm.

  • Olivier // Jun 12, 2009 at 5:38 pm

    @MiskoThanks for your response! After re-reading some of your post, I’ve came up with a solution similar to what you’re suggesting. I wasn’t too sure of myself though (me = newbie), so it’s good to know that I got it right!Thanks also for your awesome blog. I’m learning a lot!

  • Kevin // Jun 15, 2009 at 2:07 pm

    I am assuming you would recommend injecting factories for newing up resources when a method requires. For example, if business logic determines a filename to write to, inject a FileOutputStreamFactory with a method create(File).

    I am curious as to what your pattern is for the resource factories. I haven’t found a satisfying way to organize them. I do a lot of work with resources that cannot be created until a business object’s method is invoked, and I end up with the clutter of many simple factory interfaces.

  • misko // Jun 17, 2009 at 10:47 am


    Most of the time you application logic does not need to know about factories, since you inject the object which you directly need. Injecting a factory implies that the object you need has a shorter lifetime than the holding object. Obviously from time to time we have to do that. But overall we should try to minimize it. If you find yourself in situation where you have to inject a factory always ask yourself if you could make the current object a shorter lifetime. My personal experience is that people often times have too many long lived objects.


  • Kevin // Jun 17, 2009 at 12:02 pm

    Thanks for the response, Misko.

    That makes sense, and I try to follow that advice. I find it true that usually many objects can be wired together during the construction of one. I have a lot fewer factories than I would have expected a year ago.

    What I have run in to is resources whose lifespans seem like they should be shorter than that of the holding objects, especially ones which might fail to open and should be closed properly. As a simple illustration:

    void export(File file, byte[] data) throws IOException {
    OutputStream outStream = outputStreamFactory.create(file);

    try {
    } finally {

    I’d rather not inject such an output stream as it might never be needed, or maybe the object will export to different files. Is it reasonable to have a factory for creating the output streams? How would you handle such resources?

  • misko // Jun 17, 2009 at 2:37 pm


    Yes it is reasonable. But perhaps you could abstract all of the IO operations such as opening and closing behind an interface and than inject real implementation or in memory mock implementation.

  • Mike // Jun 29, 2009 at 5:32 am

    Hi Misko.

    I’ve been reading through your blog posts over the last few days and have found them extremely useful – I’ve been practicing TDD for a few years now but your posts have deepened my understanding a great deal.

    I have a question regarding testing of Active Record style domain models – not the ruby on rails implementation, but something that very closely resembles the fowler pattern.

    The problem is: client code of these objects will instantiate them directly, modify some attributes and then invoke a save(), or insert() method directly on the object. Writing a unit test that doesnt talk to the database is difficult since the save/insert methods are inherited from a super class which handles the persistence using an object responsible for database access.

    As I see it, the problem is that Active Record stlye domains cross the boundary between what you desribed as Newable/Injectable. The “model” part is newable, but the data access part is injectable (ideally).

    The challenge I’ve had testing is finding a suitable point at which to mock (or stub) the database access. I thought of replacing the new CustomerModel() (for example) with a call to a factory that would be provided using dependency injection, such as factory.createCustomerModel() but this feels like a bit of hack, and indeed you’ve warned against this directly in some of your posts.

    The other option would be to define something static on the model super class to allow the default database object to be replaced before the test runs the client code. Again though, this doesnt “feel” that right to me.

    What would you suggest?

  • misko // Jun 29, 2009 at 11:05 am


  • Mike // Jun 29, 2009 at 12:26 pm

    Thanks for taking the time to respond Misko.

    My hunch was the record is really a newable, but I couldn’t see how without having unit tests hit the database. The repository object works really well, thanks.

  • Lars Carlsson // Jul 7, 2009 at 1:23 pm

    Hi Misko, one disadvantaged I have experience when using more polymorphic coding standards Is that non-programmer like DB/Network experts may have problem to understand the code because they experience it not as linear as a procedural programming language. I feel that I don’t get as much help when having step-debugging session with a DB/Network expert where they finds the code messy and want to add more conditional into the code.

    The question:
    Would you agree that polymorphic code can create issues when working with persons that have other experience and have a procedural way of looking on code?
    And do you have any solution for this issue?

  • misko // Jul 7, 2009 at 1:51 pm


    Yes, I agree if you speak OO and they speak procedural, you will have trouble communicating. Not sure how to fix it other than get everyone on the same language. :-(

  • Alan // Jul 9, 2009 at 10:01 am

    Misko – found you via google tech talks. They are great thanks, do more please.

    I have recently gotten into ‘Clean Code’ via Robert C. Martin.

    When I combine ‘Clean Code’ with your video where you suggest avoiding conditionals, I have found my code is much, much more ‘clean’.

    My question: what is your opinion on commenting – when I’ve written an app with few – if any- conditionals, small functions and small classes.

  • misko // Jul 9, 2009 at 10:07 am


    to me comments mean that the code is not self explanatory. I do write comments from time to time, but it is more of a TODO to make this cleaner. What i don’t like is to have redundant comments. As in // this class implements interface X, or getter for X property // I con infer that by looking on the code.

  • Kevin // Jul 12, 2009 at 5:36 pm

    Misko, thanks for the advice. I haven’t responded earlier because I’ve been trying out what you suggested, hiding difficult-to-test code behind interfaces. I have been very happy with the results.

    I thought that the use of factories in these cases seemed a bit smelly. I still had to mock out some complex objects, especially with JDBC PreparedStatements and ResultSets. That’s hard, and I avoided testing those classes because even with jMock it was still difficult to prepare mocks.

    Now, I extract all the difficult-to-test code to a different class, retaining all the business logic in the original class. If need be, flow can be controlled from the original class. This was the concept I was missing.

    Perhaps you could write an article on this topic.

    As an aside, I started a new project using Guice recently. Except for having to consult the reference material for new uses, which I’m having to do less frequently, it’s quite nice. I think I like it more than handwritten factories, but it’ll be a while before I can really see it in action. ant-testability-explorer has become a must-have for me.

    Lastly, your presentations and articles have made huge improvements in how I think of object interaction and how I write software. Thank you for your testability advocacy!

  • Perry Valdez // Jul 20, 2009 at 12:05 am

    Hi, I’ve been reading your site, and I’ve learned many things from it!

    A recurring theme on your site is that “Do not mix object construction with business logic”, i.e., separate the factories from the business objects.

    But what if, in my business situation, it turns out that a factory *is* also one of the business objects?

    Say, I’m constructing a Web server application. My design is, whenever a Web client obtains a successful connection to my Web server, the Web server instantiates a new thread that will handle the Web client. In my sample code:

    public class ClientSocket {


    public class WebServer {
    public ClientSocket listen() { … }


    public class ClientHandlerThread {
    public ClientHandlerThread(ClientSocket socket) { … }
    public void launch() { … }


    public class WebServerApp {

    public void run(WebServer server, int port, String… args) {
    boolean quit = false;


    ClientSocket socket = server.listen(port);
    if(socket != null)
    clientHandlerThread = new ClientHandlerThread(socket);




    In this code, the WebServerApp is clearly a business object, yet it is also a factory of threads. So how will I apply “Do not mix object construction with business logic” in this case?

  • misko // Jul 20, 2009 at 1:20 pm


    the key is you want to get rid of the new operators so instead of
    lientHandlerThread = new ClientHandlerThread(socket);
    lientHandlerThread = clientHandlerThreadFactory.create(socket);

    This way you can always put in a MockClienHandlerThreadFactory and mock it out in test.

  • funnyguy // Jul 29, 2009 at 4:41 am


    First off, excellent site, great and insightful content right up my alley.

    I needed to know if you are planning to extend the testability exlporer to J2ME also, or can it be used in its existing form for J2ME?

  • misko // Jul 29, 2009 at 7:31 am

    I believe it should already be able to analyze J2ME code, but you have to run the Testability Explorer in J2SE and analyze a J2ME jar.

  • yashodhan // Aug 6, 2009 at 7:42 am

    Hi Misko ,
    Great Blog for learning testing/TDD. I want to know your thoughts on making a code base testable which has not been designed keeping in mind unit testing/testability.

  • Thomas // Aug 10, 2009 at 11:10 pm

    Hi Misko,
    really great blog you are writing here … it gives a lot of insight. I have a concrete question. Assuming you have an application with a Swing frontend that is used to collect data input and is then storing this data via an application server (EJB3 / JPA) to the database. No logic or anything. What would you consider meaningful JUnit tests for such an application as it feels on first sight as if there is not too much for unit-testing. Would be great to hear some ideas from you. Thanks in advance and
    - Thomas

  • misko // Aug 11, 2009 at 8:18 am


    I would write a tests which shows that I can marshal basic data from the UI to the DB. Even if there is no logic you can always test that persistence works.

  • siva // Aug 13, 2009 at 9:04 am

    Hi Misko, What are your suggested best practices for testing multi threaded code? Are there ways in which you test for certain race conditions, deadlocks, etc.

  • Gabriel // Aug 17, 2009 at 2:17 pm

    Hello Misko,
    I’ve got some basic questions, perhaps you’ve answered them before. When can I tell if a class has too many collaborators? Is that also a sign that the class is doing too much? The class is fully testable but I need to inject and set up many collaborators for that and I just know something is not right.
    Thanks in advance! :)

  • misko // Aug 17, 2009 at 7:39 pm


    It is a judgment call. At some point the number of things you are passing through the constructor becomes too much and you will need to group related things to a higher level object which becomes a facade for the replacement ones.

  • Alex Dowgailenko // Aug 18, 2009 at 6:13 am

    Hi, I’ve read several of your entries and found them to be very interesting. So I’d like your opinion on something.

    Most times, speed and efficiency is important, and depending on the language, to obtain speed and efficiency means backing away from some TTD principles. How do you balance test driven development with speed and efficiency of your code?

  • misko // Aug 18, 2009 at 8:09 am


    I think the apposite is true. The more I TDD the less I debug and quicker I deliver. The reason is that I have been TDDing for 3 years, and as a result it is very natural for me and takes zero effort. The more complex the problem the more important TDD is. However when you are new to TDD your are doing two things, you are learning new skill (TDD) and you are writing new code, and as a result you are slower than if you were not writing tests. You need to pay the price of learning new skill sometimes. The tradeoff is not TDD vs speed, the tradeoff is new skill vs speed today and debugging tomorrow.

  • Marcello Duarte // Aug 21, 2009 at 12:38 pm

    Hi Miško

    I can appreciate the benefits of avoiding global state (in all its forms), specially on how it accounts for a more testable and clearer code. Thanks for your talks and this forum.

    Isn’t the trade off here one of maintainability versus code efficiency? You are making a valid point on your last answer, but I hear in Alex voice a concern on loosing some of the benefits of keeping some static content in your classes. Static calls are faster and often reduce execution time by the caching the result of some object creation. In application context configuration objects that can mean having to reload a long xml file every time the object is constructed. Declaring you “instance” property as final is a good solution but it is technology bound. Many languages won’t support final for properties. Do you avoid static variables and methods in all circumstances?

  • misko // Aug 22, 2009 at 6:41 pm


    there is no trade off as you can have long lived objects which cache such information. Global state is not the only way to get longed lived objects. The problem in global state is that it is globally accessible and you don’t know who and when is accessing it. This makes it very hard to follow the program along.

  • Alexei Lupan // Sep 1, 2009 at 6:59 am

    Hi, Misko,

    is there are available somewhere the video with you presentation @ “2009, Aug 19th – RIM Test Automation Conference – Psychology of Testing”?

    Thank you.

  • misko // Sep 1, 2009 at 7:07 am


    sorry not yet, but I am working on it.

  • Fabricio Buzeto // Sep 1, 2009 at 12:42 pm

    Following the traditions of the day.
    Your blog was referenced by me today.

  • Sebastian // Sep 2, 2009 at 12:34 pm

    Hi Misko,

    First of all thanks for sharing all your simple but fantastic knowledge.
    I wanted to ask you if there’s some doc explaining in detail the testability explorer tool. I’ve been able to ran it but I don’t know If I did well because the project is a completely mess -untesteable hard code- and all I always get when I print a summary is “Excelent classes” :)
    I think I’m doing something wrong.

  • Amol // Sep 9, 2009 at 1:35 am

    Hi, Misko

    I’m bit of confused about which approach (Mockist, Classical) to TDD should be fallowed. The mockist approach is good when it comes to writing true “unit” tests and saves lot of time, but comes in my way when I need to refactor my code, since they are too much coupled to target code. On the other hand Classical approach to TDD takes time to set-up the test is to much tedious, also sometimes I feel that they aren’t reducing the scope of my tests. What advice you have for me?

  • fqqdk // Sep 9, 2009 at 2:32 am

    Amol: I think you should follow both.
    Unit/Small tests are written by the mockist approach, and Functional /Medium tests are written by the classical approach.

  • Marty // Sep 9, 2009 at 5:52 am


    I also have to congratulate your blog and the techtalks… they are really fanatstic.

    I do have some understanding issues concerning DI and “value-dependen” objects.

    Value-dependen objects are objects wich are created with some current runtime data, e.g

    public Foo(Bar bar, int someValue) { … }

    Lets assume Bar is injectable, but someValue changes during runtime, so the object is different for different creations.

    I know that Guice (e.g.) has the @Assisted annotation, but this would lead to inject the Factory to create the object Foo with the int value.

    This doesn not sound well for me… If object Bla depends on Foo, how to solve this – except given Bla the factory to create Foo with some specific int value ?

    Thanks and cheers

  • misko // Sep 9, 2009 at 8:56 pm


    I think what you are referring to is described in more detail here:

  • Marty // Sep 9, 2009 at 11:52 pm

    thanks – yes I referred to that basically ;-)

    somehow missed this article


  • Rusty // Sep 11, 2009 at 9:18 am

    Misko, have you or any of your team mates looked at the Wicket web framework? I’m confused because the Wicket project seems to be staffed by a lot of smart people, but their code invariably has constructors that are doing a lot of work. Take for example, and note that its constructor is calling a dao, and then it’s calling setupPage() which does a lot of work.

    I also find a lot of their code hard to understand, but I don’t know if that’s me or their code.


  • misko // Sep 11, 2009 at 10:28 am


    yes the code does not look very unit testable, but I don’t know anything about it to comment.

  • Marty // Sep 16, 2009 at 3:28 am

    question about the MusicPlayer example…

    ’m still not really can follow this :(

    If your requirements now say that MusicPlayer has to have a name (String field) – it becomes a Newable and its not injectable anymore ?
    So what to do with the current MusicPlayer, because it also has the AudioAdvice field – and the injection fails…

    what is the solution for that ?

  • Subb // Sep 23, 2009 at 5:41 pm

    I was wondering what was your thoughts on IoC Containers like Castle Winsor Container.

    Isn’t it just a Service Locator with a new label?

  • Subb // Sep 23, 2009 at 9:40 pm

    Well… after a little investigation, I’ve found out that my team has wrapped a single container inside a static class. That’s why I tought Castle Winsor was like a Service Locator when in fact my team misused it.

    boy, that’s pretty bad…

  • Roberto // Sep 28, 2009 at 9:03 am

    Hi Misko,
    this is my situation:

    I have a layer that is responsable to run some queries (against different http system like atomics, solr, ecc) and I want to test my code that uses this layer.
    How can I understand if my code uses this layer in a proper way?
    I started testing using the object returned from the data layer, but in this case i have to make http requests for each test and every test takes a lot of time.
    The only thing that this data layer is doing is to get some parameters, build up a sql query, and send it to atomics or solr. In the end it gives me back a bean filled with all the data.

    Thanks very much for your explanation! :)

  • misko // Sep 28, 2009 at 7:33 pm


    I usually test this by building an ideal interface which returns a value object which is easy to instantiate. That way I can create an easy emulator. Than I test each adapter with the slow HTTP only once. All other tests are using my emulator.

  • Robert // Sep 30, 2009 at 11:58 am

    Hello Misko,
    I’ve been reading your articles on testing, Singletons, the evils of static data and the virtues of dependency injection.
    I recently watched a video you did on Clean Code Talks on the subject. During the Q&A session you were asked about the rather common case of a logging facility that may be called in many places. The question was along the lines of “if I have a method 10 layers deep in my program, are you suggesting that I pass the logging object on every method from top to bottom”. Your answer was no but your elaboration wasn’t clear enough, at least for me, to understand how this would be accomplished – at least in the land of no globals/singletons.

    • Assume I’m writing a C++ (*not* Java) app and I will likely be logging/tracing in many places in my program. Given that Singletons/globals are bad and that dependency injection is good, how do I get by without the Logging object being part of every signature.
    • I’ve looked at the Chrome source and they make liberal use of the Logger object and it is certainly not passed on every method in which it is used. Is this bad?
    • In practice, using C++, have you ever seen a large scale project where the logging, or other frequently used object, is passed from main() all the way down to everywhere it’s used? I just can’t imagine this being done in practice in an environment such as C++ which lacks mature dependency injection frameworks like Guice.


  • misko // Sep 30, 2009 at 9:41 pm


    I think these may shed some light:

    You, don’t pass things all the way down. In general every object only know about what it directly needs, so passing things down is a violation. the second blog article talks about it.

  • arun // Oct 8, 2009 at 5:22 pm

    Hi Misko,

    Thank you very much for the posts. I learn and understand a lot from it.

    I have an application that have four modules that talks among themselves using jms queues and with external systems using queues/webservices.

    We have some unit tests in place currently. We are trying to develop automated regression tests (end-end).

    I am not sure where to start (new to test automation) and the existing system is complex with its dependencies on the db/queues/so many number of classes.

    And we use ServiceLocator (anti-test pattern) too, to retrieve the objects necessary to process business logic :( .

    Each module has several classes that depend on each other and testing the module in isolation would require complex test fixtures.

    What/Where would you suggest for me to start?

  • Maxi // Oct 15, 2009 at 7:41 am

    Misko, hi, i’m from Argentina and i like a lot your technical talks.
    First, sorry for my english. I want to ask you, about how to design the
    config subsystem, for example for a gui application.
    You have many path of execution, depending of X setting.
    I see many applications using a singleton, and the class simply ask if X setting
    is true (getting from singleton).

    How can you make a clear and testeable desgin, not using singleton, to face the problem ?

    Bs. As. Argentina

  • misko // Oct 15, 2009 at 7:55 am


    what you are asking is a very complex questions, which cannot be answered in a single comment, blog or article. :-) but a good place to start is GUICE, and if it is a GUI that MVC.

  • Glen Stampoultzuis // Oct 20, 2009 at 10:02 pm

    One things I find really hard is testing low level JDBC calls. Trying to mock out the complicated chain of JDBC calls is really time consuming and akward. What approach do you use?

  • misko // Oct 20, 2009 at 10:07 pm

    yes, mocking SQL sucks, so i use in memory JDBC such as HsqlDB or McKoi

  • Glen Stampoultzis // Oct 25, 2009 at 4:10 pm

    Miso, I was kind of expecting that answer but at the same time I’m a little disappointed by it. Using a substitute database (even an in memory one) is going a little beyond what I’d call “unit” testing. Also even if using a database feature not available in your in-memory substitute database you’re out of luck. Still, not sure what the answer is here. From my experience mocking JDBC is not very productive.

  • niranjan // Oct 28, 2009 at 5:14 pm

    Hi Misco,

    I am trying to setup my eclipse environment as per your instructions. I did setup the ant file as per instructions and did setup the builders.

    However we use maven and ant file does not have classpath used by maven and my tests break because of class not found error. Code compiles fine.

    Any ideas how can I setup my eclipse to use with maven? Ideally I want to set it up only for myself and not impact the whole team as everyone can setup his/her test cases based on the area they are working on

  • Yashodhan // Oct 29, 2009 at 9:10 am

    Hi Misko ,
    Thanks for the great blog and talks/slides.

    I work on mobile applications J2ME , Black-Berry , in platforms as these the tools required for unit testing ,CI , automated (headless)testing are not available of the shelf like J2SE ,JAVA EE.

    How can i follow all these things on such platforms.

  • misko // Oct 29, 2009 at 2:38 pm

    When i come across a tool which I can not find, i built it. :-) Perhaps this is your calling?

  • Tommy // Oct 30, 2009 at 9:39 am

    I work with ASP.Net. I would like to create a class that will read my settings
    from my web.config and provide strongly typed representations of those settings.

    Since modifying the web.config triggers the app to restart, it might as well be
    considered readonly. Given that, my first inclination is to make a static helper
    or use a Singleton for this since even though the variable will be global, it’s
    values can’t be changed and thus shouldn’t cause any conflicts. Right?

    Is a static helper class or a Singleton still bad in this case? If so, what solution would you use?

  • Andrej // Nov 4, 2009 at 1:37 am

    Zdravim . Pocuj ci by nebolo zle publikovat tu tvoju teoriu aj po slovensky aspon ciastocne. Predsa len kazdy nevie v SK tak dobre anglicky . A urcite by to ocenili aj nejaky tý cesi .

  • misko // Nov 4, 2009 at 8:40 am

    Ahoj Andrej,

    it would be great to translate many of these articles, but unfortunately my written Slovak sux. But I would be happy to work with someone like yourself and help you do the translation. You could be the famous guy in Slovakia for doing this. :-)

  • Laykou // Nov 4, 2009 at 2:50 pm

    Ahoj :)

    Páči sa mi tvoja práca a tiež som fascinovaný počítačmi a IT a programovaním…. Pravé by som sa rád začal učiť v C++ a efektívne používanie algoritmov. Vieš mi poradiť nejaké dobré zdroje, kde začať, prípadne ak C++ nie je ta správna voľba, tak na čo sa mám zamerať?

    Veľmi zbežne ovládam Pascal a Delphi. Kedysi som tiež začínal v BASIC (našiel som si v knižnici nejaké knižky .. takto som sa aj dostal k programovaniu). Momentále najviac pracujem asi v PHP.

    Som 15 ročný študent na Gymnáziu a ešte rozmýšľam akou cestou sa vidať. :)

  • misko // Nov 4, 2009 at 3:35 pm


    I have not touched C++ in years, and the work I do C++ is not the best, as it is too low level, so I can not give you advice on C++, but I can give you general advice. To learn anything you need to make up a project, and than deliver on that project, and in the process you will learn.

  • Alan Pinstein // Nov 5, 2009 at 9:56 am

    Hi Misko-

    I’ve been reading your blog posts and watching your videos and trying to improve my DI/testing skills over the past year. I’ve made significant progress, but I am having trouble figuring out how to architect some injectables correctly.

    I have a web app framework that I wrote and use — it’s a pretty typical MVC framework with a front-controller.

    The simplest example that I can’t figure out that I would like your help with is this… how to properly construct/inject a MailerService. For instance a User model needs to be able to send a message when a new user registers.

    So I have something like:

    User->sendWelcomeEmail(MailService $mailer)

    Which I think is fine. It is fine to inject into a function rather than setter inject the mailer, right?

    But when I run into trouble is how should my *controller* get the MailerService?

    The MailerService instance itself needs to be injected with the appropriate config [host & credentials] for dev/staging/production.

    So my quandary is that if I new the MailerService at the application level (which knows dev/staging/prod) then I have to violate Law of Demeter in the controllers like so:


    But if I move the construction of MailerService into the controller, I have to use global state in the controller like so:

    $mailer = new MailService($configGlobal['smtp']);

    Now that I’m writing this out maybe I am seeing the solution… do I just need an Application.config where I can inject this type of information? But that smells like a “container” which is also on the “do not do” list.

    I would really appreciate your advice. I have been battling this one out in my head for a long time without any solution and even talking it through with lots of other devs and we can’t figure out the *right* way to do it.

    Thanks in advance!


  • misko // Nov 5, 2009 at 11:05 am


    The simplest is to inject the MailService to the Controller so that in controller you can do this:

    The mail service is made in Application which is a factory and which creates the Controller and injects the MailService to it.


  • Alan Pinstein // Nov 5, 2009 at 8:13 pm


    Wow thanks for answering so quickly! I didn’t expect that.

    I read the article (which btw I hadn’t seen, so thanks) and understand that example just fine. I feel like my setup has one additional layer of indirection that makes it hard for me to apply that solution.

    In your example it’s clear what to do because LoginPage has 2 dependencies, and LoginServlet is there to be a factory for it. But in my case (and maybe this is where the flaw is), I don’t have LoginServlet; I have Application (the FrontController), which maps the request to the LoginController class *dynamically*, and thus isn’t aware of its specific needs compared to any other class.

    So how are Application and the various ConcreteController instances supposed to coordinate to inject the required dependencies?

    HTTPRequest has no idea what services ConcreteController needs. Do I need to just decide what services are “application” scope and inject all of them into the BaseController constructor and not care if some ConcreteController subclasses ignore some of them? That seems kind of strange…

    Maybe my architecture is fundamentally broken? Maybe I have ended up making it impossible to do the Factory wiring at the right level of scope? Maybe something about the dynamic instantiation of classes which have different needs is throwing the wrench in the works?

    How would you do it in this case?

  • misko // Nov 6, 2009 at 9:01 am


    I guess from the notation of the example that you are in C so this double indirection is a problem. Here is how I would solve it in Java

    If you use GUICE than you would have an injector. You would than simply say injector.getInstance(LoginPage.class) or injector.getInstance(SettingsPage.class). Since injector uses reflection each page can ask for different things. This makes the wiring simple. since your page factory simply has a reference to the page class and injector and creates the concrete class.

    In C you don’t have the luxury of reflection and GUICE. so what you need to have is a map of class tokens to function, where the functions are factories which will produce the Page instance at runtime. This means that the PageFactory gets injected with this map and uses it to build pages.

    It is than the responsibility of the Application(Factory) to create the map and populate it with the factory functions.

    (You can substitute factory function for a FactoryInterface)

    happy coding

  • Alan Pinstein // Nov 7, 2009 at 9:31 am


    Thanks for the follow-up. I will read up on GUICE and see if I should craft a DI container or use an existing one. I am in PHP, so I do have the benefit of reflection, if that opens up any other alternatives.


  • Tommy // Nov 13, 2009 at 1:39 pm

    Misko, do you have any advice for me regarding my question from Oct. 30?

    Sorry about the formatting on that post. Because the textarea on the page is small I composed it in Textpad and I forgot to remove the line breaks before I pasted it back into the textarea.

  • misko // Nov 14, 2009 at 3:40 am


    sorry for missing this question earlier. Even thought it is static for the duration of the execution of the code, it is not static for the developer. In other words it is not clear at compile time what are the values. For this reason you will run into two problems.

    1) as a developer it will not be clear to you which parts of your code will get which configuration settings:
    2) Unless all of your tests use the same settings (unlikely), you will not be able to change the values of singletons which will prevent you from testing the code.

  • Jonathan Aquino // Nov 14, 2009 at 1:53 pm

    Misko, is there an online video that you would recommend that would help my co-workers to get fired up about TDD? I searched for “tdd kent beck” videos, but the only one I could find was a keynote that he did, and he rambles somewhat. It’s not a good intro.

  • misko // Nov 17, 2009 at 1:19 am

    I have recorded some in the past, but I have not had the processed yet… Hopefully soon…

  • Edwin // Dec 3, 2009 at 7:11 am

    i’ve become quite the believer in depending injection, but one scenario where i am unable to apply this knowledge is in as pages are not created through constructors, is there no delicate way to inject objects aside from “newing” the objects i want in the init event?

  • John // Dec 4, 2009 at 8:10 am

    Hi there,

    Have read your writings with great interest, and am beginning to push for it’s adoption and adaptation into our projects.

    One thing that is confusing me at the moment is what the ‘CL’ is that you refer to – initially I thought it was a shorthand of class, but now I think maybe it’s some Googlish jargon for a project or work ticket?

    Can you enlighten?



  • misko // Dec 4, 2009 at 8:12 am

    CL -> Changelist

  • John // Dec 7, 2009 at 8:17 am



  • Mike // Dec 8, 2009 at 9:58 am

    Just wanted to say thanks for all the great writing and techtalks you have done. I remember when I first heard about GUICE and automatic dependency injection, it sounded like people were taking this stuff way too far to the extrme.

    Now I’ve seen the light.

  • Berlin Brown // Dec 18, 2009 at 8:39 am

    I have this code (you probably can ignore that it is Swing code), but I usually end up with too many arguments in my constructor. Should I use model bean class and then pass that object in the constructor?

    public BrowserFrame(final JTextField url, final JTextArea response, final JTextField command, final JButton actionButton) {

    this.urlField = url;
    this.responseArea = response;
    this.commandField = command;
    this.actionButton = actionButton;


    In this code, I am considering adding more objects, used by this class. Do I keep just adding more args and pass them in the constructor. Possibly use setting injection?

  • Dave // Dec 23, 2009 at 4:58 am

    Hi Misko,

    I am a strict follower of your teachings. However, very often I come accross the problem where the controller which wires everything together ends up beeing too large due to the nature of the task. For example I have a registration controller which has 4 different types of registration with many options each. Even though all I do in this controller is instantiate the classes i still end up having to create quite a few (wiring related) helper functions with wiring related logic thus ending with a controller which is 500 lines of code long which makes me uncomfortable. In a sense what I am saying is that even the controller ends up being a place where “coding” is done. How do I deal with this problem.

  • Christian // Jan 8, 2010 at 11:26 pm

    Hi Misko,
    I stumbled upon your blog a few days ago. Someone at the CodeRanch mentioned a link to the googletesting blog and I found yours from there. I find your articles very clear and enlightening.
    I’d like to know your thoughts on the following issue. A method in object Z needs to construct two non-singleton objects A and B, which both require a third object C.
    Therefore I need to make 3 calls to the factory referenced in Z. The creation of object A and B is spread over several places and gets a bit obfuscated.
    I was thinking about alternatives like constructing both objects in a single factory method that returns a tuple.
    How do you handle such spreading of object construction code?
    Btw, do you know of a tool that can build a Construction Graph from Java code?

    Thanks a lot.
    Keep up the good work.

  • misko // Jan 9, 2010 at 10:23 am


    It sounds to me like you are looking for Automatic Dependency Injection framework. Have you looked at GUICE, PicoContainer, Spring?

  • Christian // Jan 10, 2010 at 5:43 pm

    Thanks Misko,

    The project I’m working on uses Spring JavaConfig for singleton objects like services and DAOs.
    Perhaps I need to look into the automatic dependency injection features.
    Sorry for the stupid question, but can DI frameworks help to dynamically create non-singleton objects (where the information needed to create the object is not available at application startup)? I usually use factories for that.
    Is this only supported in Guice/PicoContainer and not in Spring?

  • misko // Jan 11, 2010 at 7:41 am


    I am most familiar with spring. The short answer is that you need to build a factory. If you want to inject the same object than you need to have scope for that object, such as RequestScope, as in inject same instance to everyone in the same HTTP request, but different instance for different requests. In Guice you also have assisted inject, which may help you with what you need.

  • Koen // Jan 11, 2010 at 1:43 pm

    I have a question about the ‘mocks that take mocks (very bad)’ part in the guide to testing here:

    I use a persistence solution similar to what is proposed in this article:

    I call it a repository. What I do is pass a repository in my controller. To expand on the example in this last article, the CarController would receive the CarRepo through its constructor. If the controller needs to get a specific car it would do as in the example

    Car car = carRepo.getById(123);

    The question is this: If I want to test the controller using mock objects I would inject a MockCarRepo that provides a MockCar object. I then check if the correct action is asked on the MockCar object. But this is a testing setup with a mock taking a mock. If this is bad, how would can I improve it?


  • misko // Jan 11, 2010 at 2:12 pm


    Why return a MockCar? Why not just make a new car? Car should be a POJO and should not need to be mocked. You would not a mock a HashMap? So why mock a car? If Car has references to other injectables, than you need to refactor it so it does not. See:

  • Koen // Jan 12, 2010 at 11:39 am

    Thanks for answering Misko.

    Why return a MockCar? If I want to test my controller I would prefer to test it in isolation. Let’s say the controller received the startEngine() event from the view and I want to test whether it calls Car.startEngine() on the car, the only way to check it is by querying the state of the Car object (eg by calling Car.engineHasStarted()). But this seems to rely on the implementation of the car being correct and hence doesn’t test the action of the controller in isolation.

  • Christian // Jan 12, 2010 at 12:26 pm

    Hi Misko,

    Thank you for your answer.
    Spring also has HTTP and other Scopes, but I’m not writing a web app. I’ll look into assisted inject.

    Sorry I’m asking again, don’t want to pollute this space here. One last post.
    My initial question aimed more in the following direction.

    In a method in class M I need two objects, a and b.
    I don’t need object z there, but z is needed by a AND b.
    I would like to have the construction code of a and b in one method, but then I have to return multiple objects.
    I don’t really like the fact that the method in M has to know of z.
    I would really like to know your opinion on that. :)
    Thanks a lot.


    class M
    private final Factory factory;

    M(Factory factory)
    this.factory = factory;

    void doItLikeThis()
    Z z = factory.createZ();

    A a = factory.createA(z);

    B b = factory.createB(z);

    // do something with a and b
    // z isn’t really needed here

    void orDoItLikeThat()
    Tuple2 tuple = factory.createAandB();

    A a = tuple._1;
    B b = tuple._2;

    // do something with a and b

  • Berlin Brown // Jan 12, 2010 at 8:08 pm

    General Comment:

    This is the best programming blog I have seen in a while. I have learned so much from this blog over the last month. A lot of the TDD/Agile/Unit Testing people talk about 100% coverage and write tests first and refactoring. But these are all pointless if don’t have testable code. I haven’t seen anyone talk about really focusing on the testable code part.

    This blog has, good work. I enjoy looking at code from a testablity point of view. Also, does anyone else try NOT to run the application in its entirety and only focus on writing quality testable code and tests. It is a lot better, thinking of your application in units as opposed to thinking of your application as “write a runnable/prototype application first”.

    Thanks a lot. Programming is fun again.

  • Przemek // Jan 19, 2010 at 7:06 am

    Hello Miško!

    Once upon a time I asked you about when you want to use Guice and when to use manual Dependency Injection. Uncle Bob has just written a nice post about it:


  • Christian // Jan 27, 2010 at 8:28 pm

    Hi Miško,

    Do you know of an open source project which is written in this testable style, separating logic from object construction?
    I would like to learn from reading such code. :)


  • misko // Jan 28, 2010 at 10:48 am


    I have worked on two where these principles are applied:

  • Abhijeet Kashnia // Jan 29, 2010 at 7:37 am

    Hi Misko

    You mentioned using a factory to complete the object graph instantiation in a single place. But doesn’t this ensure that all classes end up as public, so that their constructors can be accessed by one factory?

    And how about a post on exception handling and any best practices that you might want to share? Its one area that remains fuzzy to me.

    Great site, btw.

  • Marty // Feb 2, 2010 at 3:44 am


    in our company we showed your CleanCode talks to our developers. The feedback was great, but now we are out of material ;-)

    Do you recommend any other video which cover CleanCode talks or Unittesting or anything about well designed programming etc ?

    Is there anything else out side ?


  • Marinko // Feb 5, 2010 at 3:20 pm

    Hi Misko,

    first of all nice writing. I makes fun to read your blog! I spend some hours watching your Clean-Code-Talks Series and make some researches in the www. I got inspired on how to change my coding style. How would you solve the following problems:

    The Problem
    BankAccountDao dao = new BankAccountDao();
    BankAccount account = dao.getById(…);

    class BankAccountDaoProxy implements BankAccountDao{
    public BankAccount getById(String id){
    BankAccount acc = new BackAccount();
    return acc;
    Create a concrete class, which implements BankAccountDao, using any DI container technology. So far so good.

    2 Problem
    BankAccount is created using the new keyword.

    Possible Solution
    class BankAccountDaoProxy implements BankAccountDao{
    public BankAccountDaoProxy(BankAccountFactory accountFactory)
    public BankAccount getById(String id){
    BankAccount acc = accountFactory.create();
    return acc;

    3 Problem
    BankAccount is not an abstract class. So the BankAccountDao has a dependency to BankAccount. Is the solution to always use abstract classes or interfaces as return value of any method?

    How would you solve the problems described above?

  • misko // Feb 6, 2010 at 1:45 pm


    Not all classes should be created using injection. Some classes are perfectly fine to be created using the new operator. Have a look at:

  • German // Feb 6, 2010 at 8:40 pm

    This is a design question. I have model which maps a certain file system structure, let’s say Folder, Subfolder and File. So, I parse the root and instantiate a number of Folders according to what’s there. Folders lazily instantiate (with new) their Subfolders when they are referenced, and Subfolders do the same with their Files. Since all these objects are created dynamically to map the actual structure on disk, I cannot build the object graph with a DI framework.
    I also have a Configuration object with a number of properties. File needs to take one of these properties. I think of these options and they all feel wrong to me: a) have global access for Configuration (ie Singleton). b) have all these classes declare Configuration as a dependency (constructor parameter) and pass it down from Folder down to File. c) Instead of passing down Configuration, pass down the parameter File actually needs. I chose option (c) because it seemed the lesser evil, but is there a better way to do it?
    PS: I’m using Scala so there might be a clever trick for this not available in Java…
    Thanks in avance.

  • Marinko // Feb 9, 2010 at 9:23 am

    Hi German

    Could you please list all the classes with their responsibilities in your example. That would help to understand what a Folder is and who is parsing the file system structure. I would also give us an overview, if a class has more than one resposibility. It seems, that this is the case in your example.

    Thanks Marinko

  • Chandramohan Padmachetty // Feb 13, 2010 at 9:03 pm

    Hi Misko,

    I would like to congratulate you for inspiring folks like me to understand the value of writing testable code. I really liked the way you have presented in your blog. I also had a chance to explore your new cloud technology (getAngular).

    I understand that getAngular is still in its Beta. I would like to check with you if we could do any business logics like what we do using our programming languages. For instance I was just trying to simulate a simple invoice functionality using getAngular. I had no problems in simple operations such as adding updating and searching an invoice indent. Now, I have business logic where I should not be creating an invoice request if the quantity of existing invoice requests per customer and per calendar year reaches a limit. Is this achievable in getAngular?


  • misko // Feb 14, 2010 at 1:30 pm


    Glad that you like my blod, A better place to ask a question about is on the group but the answer is yes, Check out and pay special attention to the MVC section. There you we show you how to build complex business logic with JavaScript through MVC. With JavaScript you can do whatever you wish in terms of flexibility as you are fully in control.

  • Ionsiik // Feb 15, 2010 at 12:17 am

    Hi Misko,

    First many thanks to your excellent blog and articles, the testing issue puzzled me quite a while and I just felt the code written was kinda conflicting with testing but not so sure what was wrong. After reading your writings many things turn out to be clear and I konw tradeoff thereof. And I do think test first is a fun if you have intuition how to write testable code.

    I do have some questions about UI testing though. In regard to UI desgin, I would like to konw what do you think if View class should be injectable or newable? For instance, in swing, a view class with many widges can be plain UI contsruct controlled by controller, or itself is controlling logic or has refenrence to controller which hence also reference maybe some heavy services. Which design is better? And what the impact would be considering testability?

    Swing components to me seems like newables themsevles because I will not test swing components. The construct of many swing components in this regard can also be considered as newable as there’s nothing to test about. There seems to be some points for view to be newables. But normally view is the top most creatures in OO design hierarchy which in turn has ref(direct or indirect) to nearly all others. This seems support that view should be injectables.

    I would like to hear your thoughts.

    Many thanks,

  • Chandramohan Padmachetty // Feb 15, 2010 at 2:46 am

    Hi Misko,

    Thank you for sharing the links.


  • misko // Feb 15, 2010 at 9:31 pm


    checko out Growing Object-Oriented Software, Guided by Tests

  • misko // Feb 15, 2010 at 9:33 pm


    I think views are very much in the domain of injectables. Think about it this way, newables are objects which only know about other newables and which are easy to instantiate. Like an address. View on the other hand needs to know about controller, which needs to know about complex services.

  • Ionsiik // Feb 20, 2010 at 3:39 am


    I am sorry I missed your article: I see You already showed you opinion.

    I agree, views to be newables may turn controller to be hard to test.

    Still I’m interested in the testing-ui-part2, if there will be any(I didn’t find it on your blog).


  • panzi // Feb 23, 2010 at 12:48 pm

    PS: Global variables aren’t known by (or cannot be expressed by) algebras, what imposes some theoretical problems on languages (or programs) that use them.

  • Tom // Mar 24, 2010 at 1:58 pm

    I was converted to the church of TDD years ago and I’d love to adopt other Agile practices. If I could talk my company into hiring Agile coaches, I would be a lot better off than just reading books. Could you point me toward some public resource that talks about the benefits Google experienced by hiring Agile coaches? That might persuade a few skeptics. Thanks!

  • misko // Mar 25, 2010 at 9:06 am


    I can recommend some good coaches at let, me know if you would like me to do any introductions.

  • asartalo // Mar 31, 2010 at 3:16 pm

    Hi Misko,

    I’ve been reading your blog for over a month now and I should say that it has been a great help to me. I’ve been practicing TDD for 3 years now (alone) but after reading your blog, I’ve realized why many of my code was hard to test! So thank you for this great resource.

    With that, I was hoping you could help me with this problem. I’m creating a simple web framework as a pet project for my self-education in REST and software development in general. It’s written in PHP. I’ve been stuck for weeks now trying to decide how I should do this correctly.

    I have an application class that depends on a router. As I’ve designed this currently, the application receives a request and passes the path to the router. The router then returns a resource based on the path. After that, the application forwards the request to the resource.

    In summarized code form (PHP, not well-versed in Java, sorry):

    class Application implements Requestable {

    private $router;

    public function __construct(RouterInterface $router) {
    $this->router = $router;

    public function handleRequest(Request $request) {
    $resource = $this->router->route($request->getPath());
    return $resource->handleRequest($request);


    My question is if there’s a better way to do this? I get a feeling that I’m violating LoD here. If so, how can improve this? And when I test this, I feel that I’ll have to pass a mock that returns a mock. :(

    P.S. Before, the router’s responsibility used to be the application’s but I moved it so that users of the framework can choose a different routing strategy if they want to.

  • misko // Apr 3, 2010 at 8:38 pm

    Hi Asartalo,

    Great question! Your code snippet is great as I have written the same exact code myself on many projects and I have even named the classes the same, so I know what you are talking about. I never thought about the LoD violation, but you are right in its strictest way it is. This can be generalized even further to this

    request = marshaler.deserializer(inputStream);
    resource = router.route(request.path);
    response = resource.execute(request)
    marshaler.serialize(response, outputStream)

    so in this case it breaks the LoD even more, but there is something about this code which clearly states the flow of the request, an so perhaps I will say that in this case breaking the LoD is worth it to get the message through to design it without LoD would be something that would be much less readable. :-) If you do come to a solution do let me know.

  • Marinko // Apr 9, 2010 at 1:49 pm

    Hi Misko

    What do you think about the Event Broker design pattern?

    The EventBrokerService is provided using DI to the classes using constructor injection. So far so good. The problem I see is that nobody knows what kind of events the specific class is able to raise. This breaks the LoD?

    Kind regards,


  • Sean // Apr 22, 2010 at 6:15 am

    Hi Misko

    I have very much enjoyed and benefited from watching your Google Tech Talks on youtube, as well as reading your blogs here.

    Have you ever considered presenting at the annual ACCU in the UK (

    I don’t know how familiar you are with the conference, but bear in mind that this is much broader than a mere C++ users conference (Agile, TDD, FP, Java etc), and you would be in good company (this year included Jeff Sutherland, Bob Martin, Andrei Alexandrescu, Jim Coplien to name but four).

    Hope to see you next year!

    Kind regards

  • misko // Apr 22, 2010 at 5:15 pm

    looks like I have missed it this year, would be happy to look into it next year.

  • Sean // Apr 23, 2010 at 8:32 am

    That would be great!

  • Roberto // May 19, 2010 at 2:23 am

    Hi Misko,
    do you have any guidelines about tests naming? I find hard to understand the unit tests of my project, so I would like to suggest a different naming approach. Do you have any idea on this?


  • Ramesh // May 20, 2010 at 5:45 am

    Hi Misko,

    I would like to know if there exists a eclipse plugin for testability explorer? Please point me to link if it available else let me know if you have a plan to provide one.

    Thanks in advance,

  • misko // May 20, 2010 at 11:13 am

    sorry, there is not. we started working on it but did not get very far.

  • Medinol // Jun 30, 2010 at 5:22 am

    Hi Misko,

    i really enjoyed reading your posts on singleton using.

    can you give me a link or direct me to a simple application in c# that implemets the ApplicationFactory pattern you talked about ?


  • misko // Jun 30, 2010 at 8:37 am


    sorry, I don’t deal with c#, so I am not aware of any examples, but they should be very equivalent to the java ones on this blog.

  • Amischol // Jun 30, 2010 at 11:46 pm

    Hi, Misko.

    I just know, about JsTestDriver, yesterday.

    I think that it’s one of the most important developments of the decade.

    My problem is that I can’t make working the plugin on my Eclipse.

    I’ve seen all the videos I found but didn’t found any solution.

    I installed the plugin, I show the correct view even I see how capture the browser (the plugin open the browser with the header of JsTestDriver.

    My problem is when I’m trying to launch my tests.

    I tried to launch the tests from JsTestDriver view, I tried to launch from Run As (context menu on editor) and I get an error that says something like “”, and if I make one Run Configuration Eclipse remains blocked and I don’t see any response (not in the browser, not in the Eclipse console)

    I’m using the example that remains in Google Code but I don’t found any solution.

    Can you guide me please?

    Can you make one step by step guide?


  • misko // Jul 1, 2010 at 10:39 am


    for JSTestDrive related questions send email to, there are lot of user out there which will be able to help you out and get you up and running. Also check out the project page:

  • Amischol // Jul 1, 2010 at 1:35 pm

    Hi, Misko.

    This mail returns me this error.

    “We’re writing to let you know that the group you tried to contact (js-test-driver) may not exist, or you may not have permission to post messages to the group. A few more details on why you weren’t able to post:

    * You might have spelled or formatted the group name incorrectly.
    * The owner of the group may have removed this group.
    * You may need to join the group before receiving permission to post.
    * This group may not be open to posting.

    Do you know where I can contact with someone that could help me?


  • Medinol // Jul 8, 2010 at 6:07 am

    Hi misko,

    I have a question regarding your well written articles about the singleton pattern.

    I think you make wonderful argues on why not to use this pattern at least not intesively.

    Saying that, how can i make sure there is really only a single instance, i.e. how can i enforce that there would be only one instance of that type of class, there is nothing that prevents the user of my libraries from creating more …


  • misko // Jul 8, 2010 at 9:52 am


    If you need only one of something than you simply instantiate a single copy of some root factory which keeps track to make sure that you have a single copy. If you instantiate the factory again, than you will have a new copy, but in my opinion that is a good thing. Why would you ever want to prevent the user from having two instances? Say you have an application and you need a central locking object which needs to be a singleton. In production you need one copy, but during testing you want a new copy per test to make sure that test do not share state through the singleton. In my opinion it is better to tell the user that only one instance should be made, and thus allow him to break the rule in testing (or maybe the user wants to run two instances in of the app in a single JVM in which case he really needs two instances.)

    When something is a singleton it is a singleton with respect to something. Usually the JVM. There is no way from preventing someone running multiple copy of the app. What you want is a singleton with respect to your application not with respect to JVM as single JVM may run multiple applications.

  • Roger // Jul 12, 2010 at 3:40 am

    Misko, You rock.
    I am trying to push better testing habits on my team and your explanations have really helped.

    I know this isn’t technically a question, but it had to be said.

    It can be very difficult converting a team that is stuck in its ways. Is it OK if I quote some of your posts/comments verbatim? I can’t think of a better way of saying what you say.

  • misko // Jul 12, 2010 at 10:37 am


  • Fabrizio Inguglia // Aug 13, 2010 at 5:47 am

    Hi Miško,
    I just sow your nice presentation advocating all bad properties of Singleton design pattern:

    I’m actually struggling to understand the general concept about it. In your “credit card” example you rightly point out that “hidden dependencies” can be misleading and hard to test.
    However, in my opinion, this is something related to bad programming and not necessarily tied to the use of singleton. From my understanding of Singleton you have a class with a private constructor and you get the unique instance trough a public method but it doesn’t force you to have all static methods for the class.
    In your example Database, OfflineQueue and CreditCardProcessor uses static methods and there’s no explicity dependency on testCharge() with those three classes.
    But imho this example is not about Singleton, is about bad usage of static methods.
    I could have something like:

    testCharge() {

    Database db = Database.getInstance();
    OfflineQueue offlineQueue = OfflineQueue.getInstance();
    CreditCardProcessor creditCardProcessor = CreditCardProcessor.getInstance();

    // the rest of your code modified with explicit dependencies


    Another option is to have these object created by another method and passed to testCharge() or created in testCharge through a factory. Actually the factory could implement Singleton internally.
    I cannot see the difference of using a factory compared to the example above, and as you state using factories is OK.
    So, I’m little bit confused.. my point is: if the problem is to make dependencies explicit, this can be done passing the singleton object to the client class through the method parameters, the class constructor or creating and explicit pointers to the object inside the client method.
    If the problem is related instead on the fact that there’s no way to access the internal state of singleton.. I’m still confused about the reason why it is needed.
    What if the Singleton developer takes care of separating the logic and the supposed method calling sequence from the client that using it? For example not relying on client calls to have a consistent internal state. Here some examples:

    A bad scenario:

    testCharge() {
    Database db = Database.getInstance(); // –> gives NullPointerException because in my unit test main class
    … // is not called and in main class I have db.init();

    A good scenario instead:
    testCharge() {
    Database db = Database.getInstance(); // –> no NullPointerException is raised because if a field in Database is
    … // null getInstance takes care of creating it (wheter or not internally
    // calling init()

    So isn’t it just matter of how a Singleton is implemented instead of the concept that “using Singleton is bad”?
    Please let me know! Thanks a lot for your help!

    Best Regards,

  • misko // Aug 13, 2010 at 9:21 am


    The issue here is global state. No matter how you implement Database.getInstance() there will be global state in your application. Your example has a single test, but in real world we have 100s if not 1000s of tests. What if different tests want to connect to different DBs. The global state prevents it.

  • Martin // Aug 14, 2010 at 10:43 am

    Hi Misko!

    first at all, thanks you for your explanations about DI and TDD! Im developer primary on Python, javascript and C++.
    I have some questions about some piece of code in python (dinamic languages), I’m writing an API, my code looks like…

    class Server:
    def __init__(self, resource):
    self.resource = resource = []

    def get_services(self): = self.resource.a_method()

    def get_service(self, name):
    return Service(name,….,….)

    My question is about the “get_service(self, name)” method because I see that I’m hidding objects relationships and I don’t allow to test with different kind of “Service” class.

    My question is
    How is a good approach to this kind of issues? I saw that in many differents projects.

    Another idea is the code below:

    factory = DefaultFactory()

    class Server:
    def __init__(self, resource, servicefactory=factory):

    def get_service(self, name):

    In that scenario instead, I use a keyword argument with a default value “DefaultFactory instance” and somebody can modify it for other purpose for example:

    f= FakeFactory()
    r = Resource()
    s = Server(r, factory=f)

    I dont know if it is correct, could do give me your opinion?

    Thanks a lot for your help!



  • misko // Aug 15, 2010 at 11:13 am


    The issue is the new operator. (In python there is no new but you are calling the constructor function, hence the same thing.) What you need to do to make this testable is to be able to call a different constructor. We usually solve this by injecting factory methods through the constructor. So instead of calling the class constructor you call the class factory method. Then in your tests you can inject either the real constructor or some other test friendly class.

  • Damon // Aug 20, 2010 at 10:44 am

    Hi Misko,

    I enjoy reading your articles and perspective on testing. We have legacy code that is not very testable. Two things I have taken on / been tasked with are:
    1. having our developers write more unit tests and more testable code;
    2. gathering some valuable metrics.

    I have read a lot on metrics, and know that they can be absolutely worthless and cumbersome if done incorrectly. The best advice I have seen is that you shouldn’t follow a fixed recipe, but instead, determine what is important to you, and gather metrics around that.

    With that, one thing that is very important to us is having more testable code going forward. I’m curious if anyone has taken on porting your Testability Explorer to c# / .Net?

    Also, I’m open to any thoughts (or links to articles) you have on this subject.


  • misko // Aug 20, 2010 at 3:20 pm


    Glad to hear that yo are getting some use out of this blog. I don’t think anyone has ported Testability Explorer to other languages, but I don’t follow .Net, so I don’t know of any useful metrics there.

  • wei // Aug 26, 2010 at 12:15 pm

    Hi Misko,

    Thanks to your articles, I have better understanding about testing JavaScript. But I have a question that can “js-test-driver” test browser extension?

    I am currently working on a project building extensions for three browsers, Safari, Chrome and Firefox, and am looking for a good test framework that can cover these browsers on Windows 7 and Mac OS X. The extensions will be pure JavaScript, CSS and html only.

    I wonder if you have any recommendation that can meet the requirements?

    1. API testing. Different browsers provide different extension APIs and we want to cover our extensions’ APIs which built on top of these APIs.
    2. JS code coverage.
    3. Works on both Mac and Windows.
    4. good reporting system.
    5. performance data.

    Other low priority items:
    1. crash dump information, javascript call stack…
    2. UI automation-> through UI, since extensions sometimes create buttons and toolbars on the browsers not in the web content.
    3. browser rendering time, this is different from the javascript performance data.

    I appreciate any your help.


  • phil swenson // Sep 8, 2010 at 12:16 pm

    I just looked at your slides here:

    I like what I see mostly. But I’m curious – what’s wrong with new Date().getTime()? How would you do this?

  • misko // Sep 8, 2010 at 12:26 pm

    new Date() is really new Date(System.currentTIme()); You can think of System.currentTime() as a global variable which changes by itself. The result is that you have no control over time when you want to do a tests. The solution is to inject Provider into your code and then you can control the carnation of the time.

  • Vera // Sep 9, 2010 at 9:42 am

    Hi Misko,

    Thanks a lot for your blog, it helped me to understand a lot of important concepts and see how they all connect to each other.

    What do you think about messages in assert statements?
    I try to write “message that is telling the story” in every assert, even if it seems clear.
    For example:

    assertEquals(“Expect number of apples increased after visit to market”, 5, apples.size());

    Sometimes I even add try… cath fail(someMeaningfulMessage) when verify mocks because it could be hard to understand tests when mocks are overused

    So do you think that messages in assert are additional means of writing story in test or test code must be so clean that the goal of it is clear without any additional information?

  • Mark Bleichert // Oct 22, 2010 at 1:54 am

    Hi Misko,
    I think your blog provides a lot of great information but I feel I find certain design principles difficult to apply to a Dynamic language like Javascript. I know you state your a big fan of JS and that prettymuch everything you write applies to JS as well, however I was wondering how you look at global state with regard to the Javascript environment. Pretty much all with do in JS in programmed against global singletons that are provided by the environment, hence the browser (DOM, window, document ect..)
    For example, if 2 objects A & B both access a global DOM object C… A will be able to affect the state of B through C… and this is unavoidable in JS.
    Another example: you have JS libraries (or your own extensions of a JS lib) that provide global static calls because they act like utility classes.. In these cases it doesn’t seem to make much sense to pass them in as collaborator objects.. because they act like an extension of the language.
    What’s your take on this ?

  • misko // Oct 27, 2010 at 9:12 am


    Global state is avoidable in JS, and it is a bed idea for the same reasons everywhere. In JS window is global state and it accessible from everywhere, so it is very tempting to refere to it. But resist the temptation. If an object needs an alert method, then that method should be injected. Here is an example
    // no DI
    Function Greeter(){
    this.greet = function(name) {
    alert(‘Hello ‘ + name);

    // Proper DI
    // no DI
    Function Greeter(alert){
    this.greet = function(name) {
    alert(‘Hello ‘ + name);

    By explicitly passing in what you need the Greeter object becomes testable is in your tests you can pass in mocks.

  • alfwed // Dec 2, 2010 at 4:54 pm

    Hi Misko,

    I’ve looked at all your exemples about DI which are pretty clear but I would love to know how you’d handle this case. I’m writing web apps in PHP but I guess the same problem exists in Java.

    So I’m using a MVC pattern for my own framework and I’ve got a FrontController which is responsible for “instanciating” the right controller. It looks something like that :

    class FrontController {
    public FrontController(Response response, Router router,
    ControllerInjector controllerInjector) {…}

    public void run() {
    String controllerName = router.getControllerName();
    Controller controller = controllerInjector.get(controllerName)

    ControllerInjector is my factory for controllers which inject all necessary dependencies to the requested controller. I’ve simplified it’s usage because of Java static language limitation but you get the idea.

    My problem is with the injection of my whole factory into the FrontController. Does it violates the law of Demeter? Is there a better way to achieve what I’m trying to do? I can’t know before hand which controller I’m gonna need in my FrontController. Am I missing something?

    It doesn’t hurt in a testing point of view but I’m trying to figure out what’s the best practice for this kind of cases.

    Any idea?

    Thanks and great blog by the way.

  • misko // Dec 3, 2010 at 12:19 pm


    what you are doing seems right to me. LoD is not a hard rule, rather a very very good idea if possible. Besides, I don’t think you are breaking LoD since you are not chaining, you are just taking the output of one dependency and giving it to the next one in order to make sure that the dependencies do not know about each other. That is not the same thing as reaching deep into a dependency, which is what LoD says is bad.

    – Misko

  • Roger // Feb 7, 2011 at 8:29 am

    In Videogames development, there tends to be a lot of unclean code. I have got a lot of the team using Factories and the Command Pattern, which has helped. but Globals and Demeter violations are two we are still suffering from at the moment. As well as lots of classes called “*Manager, *Runner or *Container” Halp!

  • Mark // Feb 16, 2011 at 4:29 pm

    Hi Misko,
    I guess my question is how to get good at programming Javascript (without DOM).
    My main programming language is Python. I worked though Crockfords book and I did some LISP lately to get better at FP. When using Javascript (node.js) I still get bitten all the time.
    Do you have some ideas on how to get me up to speed quickly?

  • misko // Feb 16, 2011 at 9:26 pm

    If you want to build AJAX apps without DOM manipulation check out:
    If you want to learn how to write JS, then you need to do it with test such as:

  • CQ // Feb 21, 2011 at 9:59 am

    Hi Misko,
    Big fan of your insights, your articles made me re-think how i should write code.
    I do have a couple of questions though:
    1. Utility classes. I am talking about a class filled with static functions. It would make the methods that use them hard to test, especially if some of the methods involves accessing the database, right? To solve that problem I thought about changing all the static methods to instance methods, and pass the Utility object to all the classes that need it, but is that the right approach? If I inject the Utility object into my class, the outside world now knows that I am depending on that Utility class, is there harm in that?
    2. I have written classes that are tightly coupled, do you think it’s a bad thing? I had a class A that needs a class B, but class B also needs a class A, so what I did was that I new’ed a B in A’s constructor and passed “this” into B’s constructor. Say if such a object map is acceptable, how do I do injection in that case? I can’t make the constructor of A asks for an instance of B because B’s constructor is asking for an instance of A, kind of a chicken and egg problem.

    Thanks for answering my question Misko.


  • misko // Feb 21, 2011 at 11:28 am


    i think this may answer your questions:

    – Misko

  • AJ // Mar 3, 2011 at 9:48 am


    First off, just want to say thanks for your effort to voice the importance of testability. I have seen your Clean Code Talks and read just about all of your entries on the subject (I think). However, I am having some (ok…lots of) difficulties with the application of your methods. Perhaps a specific example will shed some light. Currently, I have been charged with parsing a very large and complex XML structure using StAX. The difficulty I am having is seeing a way to do this other than having one very large and very ugly method to extract the interesting information. Do you have any thoughts on where to start with something like that? I mean, did this stuff just come naturally to you :) ? Anyway, any advice you have on this or just how to get started actually applying this stuff would be greatly appreciated.


  • Billy Foster // Mar 13, 2011 at 3:26 pm

    Misko – Say you have a method that (among other work) instantiates a Newable with the new operator. To unit test this method, do you need to substitute the Newable? Or is a test that doesn’t mock the Newable considered a functional test since it involves more than one class?

  • misko // Mar 13, 2011 at 3:37 pm


    as the name implies newables, can just be new-ed up. They tend to be leafs of the dependency graph, and their behavior is well understood and is well contained, so replacing them with a mock would not help you any. Such as a hash, or a list.

  • AJ // Mar 15, 2011 at 1:16 pm


    Quick question. Would using a builder pattern when faced with a large number of parameters be an example of an “API that lies” since the object being built by the builder doesn’t take it’s dependencies directly through the constructor, but instead through the builder?

  • misko // Mar 15, 2011 at 9:30 pm


    no. the concept of API lies, reefers to the fact that the object has more collaborators, then the ones which you have passed in. The way it gets a hold of them is through a global variable (Singleton) This is an issues since the object can change the state of things which you have not given the explicit reference to.

  • Ionuț G. Stan // Mar 23, 2011 at 3:15 am

    Hi Misko,

    I have a question regarding DI and third party modules. This subject is just briefly touched in your guided to testable code.

    Let’s say I build a great library and all the dependency graph construction is separated from the actual logic, i.e. I use dependency injection.

    However, I don’t want the clients of my library to have to inject themselves these dependencies, unless really needed. So, I’d like to provide one, or a few factories that would allow the client to use a “standard” version of my library. They’re free to inject their own components if need arises, but at first, I’d like to free them from configuring my library.

    Do you see any problem with that?

    The guide says there’s a peril that client code can use these factories (test constructors in the guide) in inaccessible contexts, but I think that at this point, it’s the client fault that he’s not using dependency injection.

    What do you think? And thanks for all your writing about this stuff. It helped me a lot.

  • Ionuț G. Stan // Mar 23, 2011 at 3:42 am

    Replace “test constructors” with “constructors with default argument values” in the previous comment.

  • misko // Mar 23, 2011 at 5:55 am


    I think you are correct with your analysis. As long as you give the client a constructor, and which allows them to do DI, you have done all you could to encourage them.

  • Ondřej Mirtes // Mar 23, 2011 at 6:02 am

    first I want to thank you for the great lectures you gave us on Monday and Tuesday at CTU FEE Prague! I am familiar with the concepts of DI, but your speech helped me to realize I can follow precise guidances if I am not sure which one is the right way to solve some problem.

    However, I want to ask about mocks – if I am to write a unit test (and by unit test, I mean providing the first level of dependencies to the class under test by mock objects, so I don’t have to construct the whole object graph), I tend to look into the tested method how it will use the injected interface, so I can find out which methods I need to mock (set their return values, declare thrown exceptions etc.).

    I am looking into the implementation, which I shouldn’t. I can not guess how the class under test will use the injected dependencies only from looking at its interface – which methods it will call, what it will do with their return values etc. I can not imagine doing TDD like this.

    Take for example the yesterday case with the credit card and card processor – I would like to mock the card processor and inject it into the credit card – but I need to know, what the credit card would do with the processor, so I can mock some methods from it, so I can know what to expect what the tested object will return. It’s a similar problem like with the service locator – I need to know the implementation so I can set up the locator with services the tested class need.

    I feel like I am doing something wrong here :)

  • misko // Mar 23, 2011 at 6:33 am

    Ahoj Ondrej,

    Mocking is tricky business. While mocking is the right tool for the job many times, I feel as if people generally overuse it. They see mocking as solve everything kind of tool. I find that I use mocking very sparingly in my code, and when I do, I use them on well specified interfaces which are public, not on private method calls. This works for me. So if you have second thoughts, then you are probably trying to use a mock on something which should not be done with mock.

  • pri // Mar 25, 2011 at 1:14 pm

    Really liked your seminar on Angular java was awesome!! Looking forward for more such knowledgeable seminars from you hope to see ya in Bangalore soon.

  • Jason // Apr 14, 2011 at 3:34 am

    Hey Misko,

    Haven’t had a chance to talk to you in awhile, but I was wondering if you ever used the Dependent Object Framework (DOF) in you TDD? I found this article the JUnit site and seems intriguing.


  • Neylor Ohmaly // Apr 20, 2011 at 11:47 am

    Hi Misko,
    i’m from Brazil and i like a lot your technical talks.
    First, sorry for my english. You said in a post that factories should have no logic, just instantiation.
    I have some classes that ask for parameters that is extracted from the program command line. I should
    not do any work in constructor and the factory should have no logic, so the logic that extract and validate
    the values from the command line string must be placed into a Init() method? The factory
    should create a instance of the class and them call the Init() method? Transfer logic to some kind of Initialize
    method is a good idea?

    Neylor, Brazil.

  • Matt Pease // Apr 24, 2011 at 5:11 pm

    Hi Misko -

    Thanks so much for your informative and useful talks.

    I have a method that starts a new http connection. This must be a common case when dealing with something like a browser object loading Urls.

    The lifecycle of these connections is less than that of the browser object. So I’m not sure what should happen when I call the view method of the browser.

    The view method should not call new HttpConnection. Got that.

    So there seems like there are a few possible solutions.

    1. to pass a factory that can build an HttpConnection to the view method.


    2. pass the HttpConnection object to the view method.


    3. pass the factory that builds the HttpConnection to the constructor of the Browser.

    Or… something else?

    You alluded to this in your talk on the evils of the new operator, and why we should pass in just the objects that we need into the constructor. I just couldn’t find a concrete answer anywhere.


  • misko // May 5, 2011 at 9:09 am


    good to hear from you. I looked at the link, and it looks interesting. I have not used it but it may be useful. I tend to set up my code in such a way that most of the code does not have a link to the DB, so i tend to avoid this problem, but I can see how something like this can be useful.

  • misko // May 5, 2011 at 9:14 am


    The rule about not doing work, is that your application behavior should be free of how you put it together. In your case the command lines control the instantiation process so they are linked with the factories. I would:
    1) have code which parses the flags, this would fall under app logic
    2) have it produce a configuration object.
    3) pass the configuration object to the factory which builds the application
    4) run the application.

    This way everything is separate and there is a clean separation between the two.

  • misko // May 5, 2011 at 9:17 am


    have you seen this article: I think it answers what you are looking for.

  • Joseph // May 7, 2011 at 11:09 am

    Hi Misko,

    First, Thanks a lot for all your hard work on promoting unit-testing.

    I have a simple question but hard to answer : Who should be responsible for checking params ? The caller or the method being called ? I read the opinion of Dave Thomas & Hundy Hunt in their book ‘The pragmatic programmer’ telling that we should follow the ‘design by contract’ principle.I’am ok with that in theory but in practice, it is harder.

    Let’s take 2 examples:

    doc = new Document();

    project = new Project(‘RootPathToProject’);

    In these cases, Where should I check file/directory existence & accessibility ?

    Should I validate data all the time by the caller, by the method being called, or it depends on the context?

    Finally is it a good pratice to check every single case of error (file availability, checking that a Path param is an existing path…) ? Because this make unit-tests harder to read & code.

    I Would like hear your opinion on that.


  • CQ // May 10, 2011 at 12:48 pm


    I don’t know if this is off topic, but I see in some of your presentations you used a Mac Book, why did you decide to use that instead of a PC laptop?

  • misko // May 17, 2011 at 8:36 am


    If you are writing code for your own consumption then your tests already prove that your code works. Why do you nee additional checks? Or to put it differently if I have a choice between writing a contract or a test, I take tests. (I say a choice because sometimes you can not have both.)

    If you are writing public API for others to use, then I would have a facade which is responsible for checking the arguments. This way you can have the value of useful errors and tests.

  • misko // May 17, 2011 at 8:38 am


    Yes, mac/PC is off topic. :-)

    But, I use mac because: 1) I have all the power of unix 2) the UI is very intuitive, and 3) the hardware is very good!

  • Sophie // May 18, 2011 at 7:28 am

    Hi Misko,

    I really like the idea of js-test-driver and try to integrate with YUI test framework. I notice the link to “Config file which works with YUI Test ” from page “” is broken. Anywhere I can see how it’s done? Thanks!

  • misko // May 18, 2011 at 12:25 pm


    you should email the jstd mailing list:

  • William Gomez // Jun 1, 2011 at 6:47 am

    Hey Misko, I know you had a couple of articles that touched on it, but how about a more in-depth article about what you’ve learned from Angular about writing testable Javascript ? Best ways to structure code for testability, etc. That would be very helpful to me!

  • misko // Jun 5, 2011 at 11:25 am


    I have been planning on writings some of these articles, but I am having hard time finding the time, but they are coming.

  • Tobias // Jun 10, 2011 at 3:54 am

    Hi Misko,
    do you have a presentation about how all this testing knowledge evolved at Google? I rember a presentation about “testing on the toilet” around 2008 and at IO 2009 there was this talk about Guice. Now there is this very detailed guide about writing testable code – where the good implementation always uses guice.
    What were the important steps in this process of learning? Which of them would you do different today?
    How do you rate the role of pair programming or code reviews done with tools like gerrit?

  • Daniel Sinker // Jun 16, 2011 at 5:23 pm

    Hey Misko, how did you let the Android team produce such an untestable system? Can you go give them some stern looks and a good spanking?

  • Johannes // Jun 20, 2011 at 3:16 pm

    Hi Misko,

    I have been reading some of your articles and while they make sense – it seems you have not really touched the area of listeners. It seems to me that a lot of the wiring in some applications are actually not just getting references to services but also registering callbacks/listeners on these. Whats the best course of action for this? Following the advice of: No work in constructors and pass temporary services as parameters the best way would be:

    In an init method that takes the event sources as parameters ? But if so, who is going to call it? The injector?

  • Suyash // Jul 1, 2011 at 10:44 am

    Hi Misko,

    I gave a talk yesterday at my company for the Eclipse Developer meetup and shared your blog/technique as to how make yourself more productive on Eclipse and use TDD:

    Thanks for putting it up, I heard you over at Google Angular meetup earlier in June.


  • Neo // Jul 31, 2011 at 5:53 pm

    Hi Misko,
    I pretty like your google tech talk about Unit testing.
    I personally use python unit testing framework to keep track of the failures. But I have a question Are there any disadvantages of unit testing except it taking time?


  • LA // Aug 3, 2011 at 11:58 am

    Hi Misko,

    It there a good tutorial on setting up and using Jasmine-Node? And also, what are some suggested guidelines for BDD for both client-side and server-side JavaScript?


  • Wouter de Kort // Jan 3, 2012 at 3:26 am

    Hi Misko,

    I would like to say that I’m learning a lot by reading your blogs and looking at the presentations :)

    I’m only having a question about how to inject disposable items.
    I’m a .NET developer and I use things like
    public class Presenter // Follows MVP pattern
    public void DoStuff()
    // Use a WCF service that should be closed properly (in test it’s mocked so no WCF)
    using(IMyService service = ServiceFactory.Instance.Create()) { }
    If I would pass service as a parameter, then the calling code would have to dispose of the service but the calling code is a codebehind file of my ASPX so that shouldn’t know about services and things like that.

    How would you handle this? Make the whole Presenter disposable and pass the service in the constructor (trough a factory) or… ?


  • karolina // Jan 17, 2012 at 4:43 am

    Hi Misko,
    two year ago we discussed your TTD-course at the Fac. of Math and Physics..during the time the situation changed and our vice-dean for informatics dept. is very interested in starting a new discussion about this, is your offer still valid?
    regards, karolina

  • Juan Pablo Olmos // Feb 5, 2012 at 9:09 am

    Hi Misko,
    I am trying to fully understand how I should create domain objects (entities and value objects) using a “new” operator or using a “factory” and how pass dependencies between them.
    My understanding is that I should use a factory almost every time (according to your post, avoid the use of the new operator and only use it when it’s “the end of the line”) in order to create complex objects wiring dependencies together (domain objects with dependencies). When doing this I’m referring to “newable” objects, my understanding is that newable objects are actually objects to hold data like Entities and Value Objects and most important newable objects are able to require other newable objects but they must not require injectable objects and vice-versa, I think I understand that part. Now, the problem I see is: what happens when I have a domain object and I need to use a service (injectable) in one or even all its methods let’s say for instance a logging service, another example, an aggregate root which is just an entity (newable) in my domain, the AR can hold a reference to its own repository, so I need a reference of a service in a newable object again, in this case, the service should be used in just few methods of the AR. Well now, how should I pass those injectables to newables objects?? (At this point, I am assuming that it’s totally valid to use the injectable from the newable, I mean I need to execute certain commands inside my domain object instead of just requiring data from them)
    1. I must not pass an injectable to a newable object so I won’t use DI in the constructor of the newable to pass the injectable
    2. I don’t want to inject properties either because doing that way I’d be violating the law of Demeter, and I’d have to hold a reference field to an injectable from my newable object and also I’d be hiding (making implicit) the dependencies of the object
    I can only think in this real alternative for now:
    –Pass the injectable object in each method call.
    * I am making totally explicit the exact place where I need the injectable service
    * I won’t hold a reference to the service in my newable object which means that, if I want to serialize my domain object I wouldn’t be serializing an external service with it.
    * I will just know about those dependencies when I call the method which means that I’m hiding the object dependencies at creation time
    * In every method call, I’d have to get a reference of the injectable manually (perhaps with a Service Locator but it’s the same result) which translates into “ugly code”

    I actually can think in another way of solving this but with my current knowledge I do not see how to implement it:
    Inject the dependencies automatically when I call the method. I think this would be the wow and the click in my head to solve this =), but actually I don’t know any framework to accomplish this. In theory I’m thinking it should look like this:
    void MethodNameCommand(IServiceInterface service , params);
    void MethodNameCommand [InjectionAttribute(IServiceInterface)] (IServiceInterface service , params);
    void MethodNameCommand[InjectionAttribute(IServiceInterface)] IServiceInterface service, params);
    Well, that’s just in theory, I think you get the point.

    That’s it. I wrote more than I wanted in first place =( So..What is your concrete recommendation about this, if you could provide some code I’d totally appreciate it (I’m a Dot Net programmer)

    regards Juan Pablo Olmos

  • Andreas // Mar 18, 2012 at 4:39 am

    Hey Misko,
    I just want to express my appreciation towards your work. I love it how you succeed in educating your peers. Well on your way to becoming immortal.
    All the best

  • Vine // Mar 18, 2012 at 4:08 pm


    It is quite amazing that each of your video has something for me. Thanks very much for sharing these with public.

    I am trying to understand the problems with testing/testability aspects of a browser itself(not web pages). More specifically relating to rendering of webpage with new/evolving standards (css3, JS, HTML5). Can you suggest any resources?

    I am sorry if this is not a right question to ask.


  • Jonah // May 11, 2012 at 1:40 pm

    Hi Misko,

    If you were building a project today with angular that required a number of complex UI components, what widget library would you use?


  • Adam // May 16, 2012 at 9:20 am

    Hi Misko,

    I really enjoy your talks and I find them inspiring. I was watching your video regarding DI dont look for things and I have a question. In your video you create an object DocumentFactory but you never shows us how to use it?
    I don’t understand how to pass factories into objects lets assume an if statement creates 2 different objects that means I need a factory for it where do I instantiate the factory? Would I have to pass it in the constructor and if that is the case then after the main method the first object will be taking 1000s of objects in its constructor.


  • Benoit // Jul 4, 2012 at 9:27 am

    Hi Misko,

    lately I watched a few videos from you, talking about testable code. I found them really insightful. As a professional, it also made me re-think my way of coding, which is always a good thing.

    I’m mostly interested by something you briefly mentioned at the end of one of these video: code review cards. I’ve been trying to find them on your website, but sadly I wasn’t successful. If you could point me to these cards, or if you have anything related to it, feel free to contact me!

    Many thinks and keep up the good work :)

  • misko // Jul 4, 2012 at 5:15 pm

  • Christian B // Jul 26, 2012 at 7:10 am

    Hi, i’ve seen your videos on YouTube an read alot of your stuff. I got a question:

    Let’s say you’ve got some legacy code, and the Configuration object is stored in the Registry.

    For instantiating other objects, i am implementing factories.

    Is it ok, if a factory knows about the Registry?

    Because all the time i call the factory, i would have to pass the configuration object into the factory.

  • Evs // Jul 29, 2012 at 12:18 pm

    Hi Misko,
    I am a student trying to apply your guide to my assignments, and I have a question about your second point of not using collaborators. Often the advice when one has too many parameters is the create a POJO that groups the relevant parameters together. Does this violate the no collaborators rule? Is there another way to avoid making a constructor that takes in myriads of parameters? Thanks!

  • Darren G // Jul 31, 2012 at 3:25 am

    Hi Miško,

    Simple question really:

    Let’s say I have a service class that needs to be connected to a remote service (database, API client, etc).

    1. I don’t want to do real work in its constructor.
    2. I don’t want to create a call order dependency in the client code on a connect() method; especially as it may be replaced by something that doesn’t even need to connect().
    3. I don’t want to call connect() in every method of the service class.
    4. I don’t want the factory to be executing business logic, such as calling connect().
    5. I want the object to be ready to use.

    When should I connect to the service?

  • Paolo Bizzarri // Aug 15, 2012 at 11:21 pm

    Hi Misko,

    great site of yours. I am a developer for the FreeCol project, and I have a problem applying your criteria to my software. Basically we have our FreeColClient class that has internally several other objects – namely the InGameController, ConnectController and PreGameController. All these three Controller objects take a reference to the main FreeColClient. I think that’s bad – but this means we should break any reference to FreeColClient inside these Controllers?

    Here is a reference to the code:

  • Samuel Hapák // Sep 2, 2012 at 1:40 am

    Hi Miško,
    I read your blog and it is great. Thank you for it.

    My question is about unittesting factories. How to do that? Let us imagine an example:

    We want to create Car(color, engine, wheels) so need Engine(power) and Wheel(radius).

    Let us have CarFactory that creates these things and put it all together making Car. How to test, the resulting Car produced by factory is made with correct color, Engine and Wheels? I would need to test whether the constructor was called with right parameters, but this is impossible. I could test the values of internal (private) attributes of these classes, but then it is not unittest anymore and changing implementation of the Car class would break the test.

    So, how should I test the factory?


  • Jan Bessai // Sep 12, 2012 at 3:31 am

    Hi Miško,

    I’ve just spotted a possible way how dependency injection can improve performance. The standard Hotspot compiler uses (as far as I found out) linear scan register allocation [1, 2]. In this algorithm, which is used widely among JIT compilers, short lived variables are more likely to be placed in registers and therefore benefit from faster access. Dependency injection reduces variable lifetime by keeping state as local as possible. Further dependencies per class are kept minimal and thus reduce the count of live variables fighting over registers (register pressure). Law of Demeter prunes deep call hierarchies creating less need to exchange variables in registers.
    I don’t know of any benchmarks to prove my case, but if a performance benefit of dependency injection can be observed these points can contribute.
    It would be nice to hear, if you know any work pointing in this direction. Do you think it is worth further study?

    Thank you for your great explanatory work on DI!


    [1]: Massimiliano Poletto, Vivek Sarkar: Linear Scan Register Allocation.
    [2]: Java SE 6 Performance White Paper.

  • Kevin Hillinger // Oct 29, 2012 at 12:15 pm

    Hi Misko,

    Do you know of any AngularJS consultants in the Chicago, IL area? Our team is trying to decide between frameworks and it’s important that we have a resource for training, etc.


  • Gary // Dec 13, 2012 at 8:34 pm


    I am not sure if you can help me really but if I am just beginning to learn PHP and programming concepts. Should I concern myself with TDD? I am trying to pickup on the best practices and develop good habits but am not really sure where to find them or where to start. Is there any books or anything else you can recommend?


  • Tomer // Jan 4, 2013 at 4:29 am

    Hi Misko,
    Over the recent week I have came across 1 of your video lectures, now i’m watching like the 5th or 6th one, I just love them.

    My question :) about dependency injection, what to do about loggers? usually i do create a new instance of a logger in my java classes usually looks like a private static Logger log = Logger.getLogger(MyClass).

    but this contradicts dependency injection, does that means that for EVERY CONSTRUCTOR i have i need to pass inside a logger? (this looks wierd) what do you say?


  • Ramon Chiara // Feb 1, 2013 at 8:43 am

    Hi Misko,

    Thanks for all shared information!
    I’ve learned a lot from you!

    While reading your guide “Writing Testable Code” I asked myself if you aren’t thinking about developing a Sonar plugin to check the flaws you mentioned. What do you think?


  • Varun Achar // Feb 7, 2013 at 12:02 am

    Hi Misko,

    Should one write separate unit tests for controllers, services and daos using mocks when we know that the service and dao are going to be called and hence tested from the controller anyway?

    I know that it violates separation of concerns rule if i only write the controller tests, but creating valid domain mocks for the tests is a real time killer.

    So should I write separate tests for controllers, services & daos or can this be avoided?


Leave a Comment