Agile Zone is brought to you in partnership with:

I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

The Benefits of Testable Code

11.17.2009
| 18100 views |
  • submit to reddit

One of the most beneficial approaches that you can take in software development is to follow a test driven development approach. While we all understand why it's a good thing, it's often left slide in favour of adding functionality to reach deadline, or just to "save" time. 

One of the challenges for test driven development is making sure that your code is testable. Miško Hevery wrote an article about this very topic a while back. I thought he would be the ideal person to talk to me about testable code and test driven development. 

James Sugrue: Hi Miško, can you introduce yourself to the readers?

Miško Hevery: My name is Miško Hevery, and I build Web-Applications for a living. My passion is to share the knowledge between developers, as I think that developing software is too much art, and i would like it to become a lot more of science. I spent a lot of time giving tech-talks, both internally at Google, as well as at other companies and conferences, and  mostly focus on how to build better software by focusing more on testability. I want to bring software development back into the realm of everyday users and our teenagers, which will be our next generation of software developers. To that end I am working on allowing others to build web-applications using a novel approach of using nothing but HTML. We call it <angular/>, you can see a demo here: http://www.getangular.com/screencast


James: <angular/> sounds interesting - could you give us a quick overview of how it provides the functionality it does through pure HTML?

Miško:  <angular/> has two parts:

(1) HTML is a declarative language, but it is only good at rendering static content, What <angular/> does is to extend the HTML language to add data-binding, persistence, and looping constructs. In essence it makes your HTML smarter and more suited for building web-applications.

(2) The second part of angular is your data in the cloud. We provide REST API to your data and we do the hosting. This liberates the data as it can be accessed from anywhere and by anyone (not just by the <angular/> client) (according to security rules you specified).

The end product is that you can create an HTML form and through data-binding you specify where different parts of your data should appear on the page. <angular/> takes care of fetching the data, and merging it with the HTML template. And since it is just pure HTML the HTML can be hosted anywhere, such as a static host, or embedded in existing systems such as your Blog (example), or your Content-Management-System.


James: So, back to testability. Why do you think that it's taken so long for test driven development to get proper acceptance? After all, it seems like the most sensible way to develop?

Miško: TDD, may seem natural after you have done it for a while, but it is no more natural than riding a bike. It is a skill like any other, and as such the beginnings are heard and it takes a long time to master it. Most of us learn to code without TDD and by the time we encounter it we have had a lot of experience coding in "cowboy" style. Learning something new will slow us down at first, just as walking/running is a faster way of transportation than a bicycle when you first start it learning to ride it. However, I think the tide is slowly shifting. Many new languages have TDD culture baked right in (such as Ruby) you can see that in the support of the tools which you get right out of the box.


James: Let's look at your recent article on testability. I'm going to go through a few of the points you've mentioned with a few questions.

You list mixing object graph construction with application logic. Why does this help with testing? Surely there are more important things to do first?

Miško: Testing is all about instantiating a small portion of the application and exercising the code and asserting that it does something useful. The key here is instantiating small portion of the application. If you cannot instantiate you cannot test, and if you can only instantiate the whole application than you cannot have a small unit test. So instantiation becomes kind of a prerequisite which no one thinks about until they are trying to write a test. Imagine you are trying to test that the cookie handling logic correctly locates a user. You try to instantiate the class responsible but that class needs other classes, and so like a single thread hanging on your sweater you try to pull on it and other things show up as dependencies and your small test grows to the point where you have to make sure you have a real database, Kerberos authentication server, and most of your application running. Not what we have set out to do. Turns out that being able to control the way the individual class in an application are wired together is very important, if we want to keep the code testable on small scale. For this reason, we have to make sure that the code which does the wiring (your new operators) is not interspersed with the code which does the work (conditional and loops).


James: Your point on dependency injection is very valid. Some people still have trouble grasping the concept of DI. Could you explain it to us in simple terms?

Miško: I always say: "Ask for things, don't look for things". What I mean here is that if you need a class X you should ask for it either in the constructor or the method signature, rather than looking for it by instantiation [new operator] or by looking it up in a global space [aka Singleton.getInstance()] or by literarily looking for it in a [service locator]. What in the effect your class is saying is that in order to get my job done, i need A, B, C, therefore I will ask for A, B,C in the constructor rather than instantiating A, or getting B from global space using B.getInstance() or by looking it up in Service Locator as in Registry.get().getC(). What this means is that you left the job of instantiating and wiring to someone else, that someone else is the factory. This gives you tremendous amount of freedom and not just in testing, as you can easily wire the application differently, to get different behavior. For example you can wire a AlwaysAuthenticated class instead of KerberosAuthenticator, which makes development easier, as the developers no longer have to authenticate while testing.


James: Doing work in the constructor: it's tempting to do this when you're getting something going initially. Would you support my theory that you can just refactor it later? Or do you think it's best to work the clean way all the time?

Miško: It may me tempting, but every time I have said, "this time it is different" I end up getting bit by it later and having to refactor. What kills you is that wiring small portions of the applications together is by far the most common thing you will do in your unit tests. Which means that any work in the constructor will have to execute many times over. Say you want to test a Printer. Its print method needs a Document. What you want, is to say new Document() and get on with the business of testing the Printer. But if the Document constructor does work, say HTTP request to fetch the content, than you will get distracted trying to get your Document instantiated while, what you really want to do is test your printer. To make tests easy you need to be able to construct objects at will, otherwise you will spend way to much time fighting with the initialization logic in your test and will lose focus.


James: I really like the analogy of global state to GOTO. Surely there's no excuse for people using global state anymore.

Miško: That is what I think, but the thing is that most people fail to realize to things. (1) Singletons are global state. (They have the static field usually called instance in them) and (2) global state is transitive, which means that even if you have a single static field inside a single Singleton any object which is accessible from than single instance is still globally accessible. Most applications which I have come across with are full of Singletons and hence full of Global State. Here is a simple test. Could you instantiate two instances of your application in a single JVM? If you have any global state than the answer is no. But why would you want to instantiate two copies in a single JVM? Easy, every test is a instantiation of a small portion of the application, and all tests run in a single JVM.


James: You hate Singletons - I believe there's even a code checker at Google for this. But for me the jury's out on this one. I don't like too many singletons for sure, but just one in my application could possibly help with things. Would you agree? Can you explain your anti-singleton-ness to us?

Miško: First lets get our terminology straight: (1) There are Singletons (capital S) as in the name given to the design pattern, which has as a private constructor and a global internal variable usually called instance. We get a hold of a Singleton by calling a static method as in Singleton.getInstane(). (2) There are also singletons (lower s) which simply means that we have a normal class (public constructor no global state), and inside our application we only have a single instance of it. We get hold of singleton by asking for it in the constructor. There are a lot of reasons to have singletons, as in a single instance of something shared among many other objects, such as a cache, and I use singletons all the time. The problem is not with having singletons (one of something), but rather with having Singletons (one of something and it is global). Asking for a singleton through dependency injection (no global state) is good practice, but getting hold of a Singleton through global state is recipe for disaster.


James: You sum up the issue with static methods really well when you say you don't know how to test the main method. Why do you think there  is such a fascination with static methods when we have such a good object oriented language?

Miško: OO is not intuitive. If it was, than the first language we built would have been OO. OO is about collaboration between objects, whereas procedural codes is about telling someone the steps needed to get something done. Static methods are procedural whereas instance method are OO. We are wired to break things down into a list of things to be done, instead of thinking about an ecosystem of objects which can collectively get things done. Using static methods sparingly is probably OK, but static methods beget more static methods, since one you cross the boundary from the OO world to procedural, it is unlikely that you will come back. To me it is a slippery slope. Rather than spending time thinking wether in this case static method is OK, I have a rule not to think about it and just avoid them.


James: Can you explain the composition over inheritance rule a bit more? If I understand you correctly, you mean that it's good practice to avoid using inheritance to reduce the amount of clutter?

Miško: When I first learned about inheritance I got supper excited. With just a single keyword I could got so much behavior into my object. I once wrote a class Pixel (I was doing image processing) and I needed to keep it in a list, so I made the Pixel inherit from a List. I was so proud of myself. Life was good until I needed to keep the Pixel at two lists at once, and I could not as the Pixel was a list and I could only be part of one List. In retrospect it is the worst thing I could have done. The point of inheritance is to take advantage of polymorphic behavior NOT to reuse code, and people miss that, they see inheritance as a cheap way to add behavior to a class. When I design code I like to think about options. When I inherit, I reduce my options. I am now sub-class of that class and cannot be a sub-class of something else. I have permanently fixed my construction to that of the superclass, and I am at a mercy of the super-class changing APIs. My freedom to change is fixed at compile time. On the other hand composition gives me options. I don't have to call superclass. I can reuse different implementations (as supposed to reusing your super methods), and I can change my mind at runtime. Which is why if possible I will always solve my problem with composition over inheritance. (But only inheritance can give you polymorphism)

James: Could you give a concrete example of how polymorphism is better to use than conditionals?

Miško: One of the cool things about OO is that polymorphism gives you different behavior based on instance. To achieve that same thing in procedural language you would have to use a switch statement and place the code from each of the subclasses to the corresponding case statements. Now it is also common that you would have multiple switch structures in different location of your code. For example rendering and parsing a date would be in different methods which would switch on type. Adding new behavior such as GPS coordinates would require you to remember to change both locations. In OO you can replace what you are switching on with just a dispatch to a method. As a side benefit the parsing and rendering code for any one type now live next to each other, and you can add new types without recompiling the whole project. An if statement is just a switch with two branches, so it is equivalent. Now there are some ifs which can never be replaced such as relative comparison (<>) but most of the ifs in an application or actually of flag type as in if (green && short) {leprechaun code}. Here we are switching on type, and OO has types os first class citizens and so we are reinventing something which a language already has.


James: Your last two points are all to do with mixing concerns. Do you think it's always because we rush things out the door?

Miško: Even if you give people more time, they will still mix concerns and make systematic mistakes. They make these mistakes, because they have not fully comprehended the implications, and that is how they were thought, and giving them more time will not make the code any better. People like to use "I was under time pressure" as a defense, after they realize that some of the decisions which they have made cost them dearly. If you know that a decision will cost you dearly in the future, you will not make that no matter what the time pressure is. Blaming the time pressure in hindsight misses the real, problem, which is that you simply did not know back than. I have discover this when i was on the project where people were complaining of the way it was and they were blaming time pressure. A decision was made to rewrite a small portion, so you would think that people would not make these mistakes, but contrary, they made the same mistakes again, they even copied the problematic code to the new project. This lead me to realize that it is easy to see that something sucks, but it is not so easy to realize what is the root cause of it, or to do anything about it, and so we just blame the time pressure to make ourselves feel better.

Mixing of concerns is one of those subtle things, which everyone agrees on in principle and than when they start coding they break. They make the Car class be responsible not just for driving (legitimate concern), but also for building itself, building the engine, and loading the driver from the disk.



James: One of my pet hates is the mixing of business logic in user interface code. Does that annoy you too, or have you seen worse?

Miško: Mixing logic with presentation can make code hard to understand, but that in it self it does not necessarily make it hard to test or maintain. Similarly having separation does not automatically mean testability if you did not properly separate the wiring and logic code. While I personally think it is a good idea and always try to separate them as much as I can it is important to realize that separation is not for the sake of separation, but for the sake of something greater. I separate, because it makes my code easier to test and because it lowers my cognitive load when I am working with it.  I feel that many times people separate things because they have always been told to, but they fail to gain any benefits from it, since they have done it the way they have been told rather to achieve some specific benefit. I have broken this rule in few occasions, since I was able to achieve my goal of lowering the cognitive load, and testability without paying the added cost of separation, and that is fine, as long as you know what your goals are.


James: Let's look at the complicated case. I've decided that unit tests are the way to go in my project. But I've a load of legacy code. Unit testing will be tough- is it worth the refactor? How can I make this easier on myself?

Miško: It is important to not loose focus, which is to deliver the project. The way I usually solve this is that I write the new code in a clean testable TDD way, and than I use one of two strategies:

1. I can wrap the legacy code in a clean interface and write glue code between my ideal interface and the hard to test legacy code. I will probably have hard time testing the glue/adapter code but at least everything else is testable. 

2. Or, I can go and refactor the existing code, but only what i need to achieve my testability goals.

Which of the two strategies you chose will depend on you experience and the complexity of the refactoring you are facing. One thing I noticed is that I often start from the other end where most people start. I write my ideal test, and than try to figure out how i can make it work through refactoring and or adapters, rather than trying to write a test for the current code.


James: If I was to give a statement on the importance of testability it would go along the lines of "developer testing early saves you time later, even if it seems to take up time. Writing testable code makes your code more coherant, cleaner and easier to come back to". What would your statement be?

Miško: Firstly let me point you to an article where i discuss the cost of testing.

I love TDD, because I don't have to thing about breaking things, this removes a level of paranoia and ads confidence to take on any refactoring job which keeps your code in top notch shape. But most importantly since I don't have to think as much about coding, I can use my brain to think more about overall vision of the application. Testing does not make your application better because it your application sucks less (it has fewer bugs), it makes your application better because you spent more time thinking about the application, and you were able to re-structure the application.


James: For all the readers of this interview, who now see the benefits of testability, what one tip would you give them to get them on the fast track to testable code.

Miško: Try to find your own toy project where you attempt to learn TDD, before you bring TDD to the monster legacy codebase which you have at work. (Learn to bike on flat land, before you go mountain biking down a steep slope.) Test first may sound simple, but it is a skill, like any other, and as such it will take you months to become an expert at it.

James: As an industry, software development is still in the early stages. Do you think that TDD helps to give some quality assurance to what we produce? What are your thoughts on how to make software development a more mature profession?

Miško:  People often have the expectations that TDD, produces bug free software, and when it does not they get disappointed. Bugs come in two flavors: (1) I misunderstood what needs to be built and I built the wrong thing and (2) I understood correctly, but in the process of translating it to code I made a mistake. TDD, can only help you with the second one. I like to think of it as TDD helps me built what I intended, but whether what I intended is what needs to be built is a different story. So TDD helps to give some quality assurance but it is not a silver bullet which solves all.

Software industry is very much in the infancy, as software is much more of an art than science right now. Looking back I see that we are discovering new methodologies by which we built software and these methodologies are being slowly translated to new languages which embrace them. OO is an example which started as a methodology for dealing with data and become baked into the language itself. I think the next round of new languages will embrace testing and dependency-injection as first class constructs, helping us further codify the best-practices.

Finally, I think the industry needs to reach out to our school system and bring the classes more up to date with what the industry needs. C/C++ may be the perfect language for building Operating-Systems, Virtual-Machines, and video-codacs, but they are the wrong language for building applications, wether they are desktop application or a web-application. Today most new graduates come out with knowledge of C/C++ and are thrown into building apps, without any knowledge methodologies of building the large scale systems. I would love the universities to focus more on methodology, and generic languages, rather than on one specific language which is 30+ years old.

Comments

Rogerio Liesenfeld replied on Tue, 2009/11/17 - 10:24am

TDD is not the same as "testable code". In fact, these are separate and independent concepts. Even "testability", in the final analysis, is an empty word.

Sam Su replied on Wed, 2014/09/10 - 11:09pm

it and personally recommend to my friends and ulefone users . I am confident they will be benefited from this site.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.