Nov 08
2009

Unit Testing as the Last Resort for Code Verification

Posted by Christopher Diggins in TestingSoftware Development Methodology and ManagementAgile

cdiggins

I love code which is stable and rigorous, I just don't feel that unit testing is the most effective way to achieve it. 

I stumbled upon the following question posted on StackOverflow, "What's your most controversial programming opinion? ", and it made me think about my views on unit testing. 

I have mixed feelings on unit testing. I do use it often, but I find that it does not give me sufficient peace of mind, compared to other code verification techniques. The following is my list of code verification techniques in order of importance:

  1. System testing
  2. Use the compiler's type checker
  3. Use assertions 
  4. Code reviews
  5. Unit testing
First, any code verification technique is pointless without system testing. While it may seem almost obvious to include, it does happen where people get caught up in the minutiae of code verification and overlook the big picture of whether or not a system is behaving as intended. 
 
My preferred code verification technique is to leverage the language's type system to express assumptions, requirements, and  invariants. It is nice to know that if something compiles, then it is correct. Some examples of how this can be done are:
  • using unsigned types instead of signed types so you don't have to worry about non-negativity. Consider for example the example of using an unsigned type instead of a signed type in a square root function.
  • using id types instead of integers to identify objects. I recently ran into problems in my code, because I violated this rule. I confused the index of a vertex, with the index of an index array into the vertex array. The fix was easy: use a new VertexID type.   
  • using smart pointer classes with the appropriate semantics. E.g. null-checking pointers, deletion prevention pointers, pointers with ownership semantics, etc. 
In this bucket I also include any static contract verification tools like those found in Spec# and Eiffel.  This is because the techniques of type checking and contract verification are closely related, and both based on theorem proving techniques.
 
When the type system can't be used easily, I find that the next most powerful code verification technique is to use assertions to check assumptions, requirements and invariants at run-time. Assertions turn regular system testing into a much more powerful tool for uncovering design errors and potential defects. In addition assertions occur directly in the code, as a kind of documentation that is useful during code reviews.
 
Code reviews are another technique which I find is more powerful than unit testing, if it is done properly. In order to really leverage the power of a code review, code has to be written so that verification is as simple as possible. I will often sacrifice performance and ignore any popular idiom of the week  if it means making my code's meaning obvious and unambiguous. 
  
When I find unit testing to really become valuable as a tool, is when code can't be proven correct by the compiler or fully verified through assertions, and that a code review can't give a high confidence that the code is correct because of inherent complexity. 

 



Comments (6)Add Comment
...
written by Jack Woehr, November 08, 2009
I like the way you think.
In general I agree, but...
written by Nathan Ernst, November 09, 2009
I like the concept of assertions. The problem I have with assertions is that most implementations are done in debug versions of executables/runtimes/vms only. This is great for verifying your code in a development/QA type environment, but what about a production environment where assertions are effectively ifdef'd out?

I know it sucks, but the most effective means I've found is to throw an exception, rather than assert for all but the most trivial of checks. My reasoning: if it's important enough to check in development/QA, it's important enough to check in a production environment and to fail to a known state.

The problem you'll run into assertions in a production, optimized compile of C++, is that the checks are not performed, and when they fail execution is not stopped. Immediately you're into undefined behavior. Now, I'm sure you could argue that this should never happen with sufficient testing, and you'd likely be correct. But, excepting companies where software is the business and profit center, I'll counter that reproducible and extensive testing is not the norm and thus assertions, while well intended, will not catch the errors like they are intended to do.
Throwing exceptions are good
written by Christopher Diggins, November 09, 2009
I am a big fan of throwing exceptions. They make code more robust and tolerant of error.

However, always using exceptions instead of assertions means that the programmer will think twice about how they use them.

They may start to think about performance, or they may say, "I am completely confident that I coded this correctly, and my assumption is true".

The point of assertions is that they explicitly state our assumptions programmatically to make sure we catch silly mistakes, and assure that things don't break when we refactor.

In summary, if you find that your assertions can all be replaced with exceptions, this is exactly what you should be doing. However you probably are not using assertions in all the places where you need to.
Testing is the Ugly Stepchild
written by Michelle Prather, November 13, 2009
"...excepting companies where software is the business and profit center, I'll counter that reproducible and extensive testing is not the norm..."

Hoo, boy, you got that right. My "testers" have other jobs to do. They'll run a few things they know and call it good. It's up to me to try to figure out all the different ways users might try to use the program. I can't seem to convince them of the value of their outsider (at least relative to the code) perspective.
square root?
written by Christopher Yeleighton, November 14, 2009
Why would you implement a square root function? smilies/shocked.gif It should be in the run-time library of your programming language of choice, probably just a proxy to the C library.
Quality comes from design but unit test is a way of assurance
written by Yun Li, November 18, 2009
Initially, I didn't think unit test is helpful for my code quality (even life). But after I took unit test as a way to verify my code on a project. I entirely understood why unit test is so advocated.

For code review, from my point of view the result of it isn't as good as I expected. It depends on the experience of reviewers and attitude. It's a little bit unreliable.

How about assertion? I agree it's a good way for debugging but for verifying the code quality it's not enough. To verify the quality of my code, the essence is I have to make my code being run under ALL test cases. The purpose of unit test is trying to write as more as possible test cases to run to verify the behavior of my code.

I'm a huge fun who believes "Quality comes from design", with good design the chance for making mistake is small. However, I still deem unit test is good to make sure the success of projects. Of course how to balance the effort for unit test is considerable.

Write comment
You must be logged in to a comment. Please register if you do not have an account yet.

busy

Get your FREE Subscription to Dr. Dobb’s Digest today!

Dobbs Code Talk Quick Poll

This time next year, your most important operating system (host and/or target) will be:

Look Who's Code Talking


Mike Firkser
City: Edison

Mike Gualtieri
City: Cambridge

Hai Su
City: Santa Clara

Mark Sellers
City: Colorado Springs

Julie Larson
City: Santa Clara

Mathew Kumar
City: SF

Dobbs Code Talk Tags

.NET abstraction Ada Adobe Agile Ajax algorithm Algorithmic complexity ALM Analogical reasoning Android Anecdotes Apple Application Development AppStore Architecture and Design ARM Artificial Intelligence Artificial Life Assembler Programming Audio files AVX AWK Banking Bazaar Best Practices Blender Books Brain computer interfacing Build C C Programming C Sharp Cartoon Category theory Cellular automata Clojure Cloud Computing Cobol Cocoa Coder Of The Month Cognition as compression Collaboration Common Process/Frameworks Compilers Computational humour Computational narrative Computational politics Computer Science Computers in art computing pioneers concurrency Conferences Consciousness research Contest Contest140 contests CPlusPlus crime CSharp D Programming Data Centers Databases Debugging Delphi Deployment design Design Patterns Digital Signal Processing Distributed Django Documentation DSL dynamic language Eclipse EDA education Emacs Embedded Systems Encryption engineering Erlang Etymology Excel exception handling Facebook Financial computing Five Questions Flash Flash Lite Flex Forth Fortran Fraud FreeBSD Fun Functional Programming gadgets Games Gender Git gnuplot Go Google Graphics GUI hardware Heron High School High-Performance Computing History Holographic reduced representations HTML5 Humanity Humour Hungarian Notation Identity Inkscape Innovation Intel Interview iPhone J2EE Java JavaFX JavaOne JavaScript language engineering Legal lex LINQ Linux Lisp Literate Programming Logic Programming m4 Mainframes Make Mathematica Mercurial Mesh messaging Metaprogramming Microsoft MID Miscellaneous Musings ML Mobile Software Mobility modeling modular programming multicore Music MVC myblog Natural Language Processing Networking Neural networks newspeak Nokia numerical computing Object Rexx ObjectiveC Office Office 2007 Online spreadsheets OOP Open Source Openaccess publishing OpenBSD OpenSolaris Operating Systems Optimization Oracle Pair Programming Parallelism Concurrency Parsing Pascal Patents Patterns Performance Perl PHP Podcast Pop11 Poplog Privacy Processing Productivity Programming Language Implementation Programming Language One Programming language semantics Programming Languages Programming Style Project Management Prolog Psychology Public understanding of science puzzle Python QA Quantum Computing Quotes Rails Realtime recls Requirements Research practice REST Review RIA rich internet applications Robotics Ruby SaaS Software as a service Scala Schadenfreude Science fiction Screencast Scripting SD Best Practices Search Security Semantic Web Silverlight Snobol SOA social Social Networks Society for the Study of Artificial Intelligence a Software Development Methodology and Management Songs and poems Spending Priorities Spreadsheets SQL Startups Statistics Storage String pattern matching Survey Teaching Testing The Business of Programming The Dobbs Challenge The Future Theory Topology Transhumanism Travel on the Job Twitter Types Unix Upgrade Usability Use Cases USENET User Experience User Interface Design Version Control video virtual machines Virtualization Visual Studio Visual Studio Sponsored Post WCF Web Development Windows Windows 7 Windows Live Wireless WOA WPF X Window System yacc

Subscribe to Dr. Dobbs Newsletter

Email:
Dr. Dobb's Update
Delivered twice a week, Dr. Dobb's Update provides unbiased and objective news, commentary and technical features spanning the entire software development marketplace.

Latest Comments

Jonathan's Last Day at Sun
For the 8 years I worked there, it was fantastic. I worked there under McNealy and I have undying admiration for the guy. I only knew Jonathan periphe...
Implementing Thread Local Storage on OS ...
Back in the day, I did a fair amount of work with PThreads. Wonderful design. Some quirks, but basically really, really nice. Although I wrote a lot ...
More Technonecrophilia with Snobol One-L...
Yeah, It's probably identical except for the (embedded) copy number, I would think. Once it became freely distributable, the copy I've been distribut...
More Technonecrophilia with Snobol One-L...
There's a spitbol-3.7-win.exe at http://code.google.com/p/spitbol/downloads/list . I found it via Dave Shield's blog page http://daveshields.wordpress...
Jonathan's Last Day at Sun
Sadness.

The Latest From Our Member Blogs

How To Select Trainees
Written by Joel Wiesen   
01/27/10
Hiring the right trainee can be harder than hiring a trained programmer.  One approach is described at my website: http://www.aprtestingservices.com/business/lpat/
 
Technical Job Interviews
Written by Keith Kerlan   
01/20/10
What is the best way to interview for software developer positions?  I've been on both sides of the job interviewing table, but have been on the interviewee side of some not too  great inter
 
Timers/timeouts in multi-threaded event-loops
Written by Christof Meerwald   
01/03/10
The traditional way to integrate timeout handling (or timers) in (single-threaded) event loops was to just pass the appropriate timeout value to the select/poll/epoll syscall. While this works fine
 
C vs C++
Written by Issam Lahlali   
12/04/09
I think that the debate "C vs C++" will end when the two langages died, and each one have its advantages and inconvenients, the choice of one instead of another depend on the application c
 
Great Jobs at CISCO
Written by Brent Rogers   
11/30/09
Hello! I am a recruiter at CISCO. We have a number of great jobopportunities at CISCO right now. Please take a look at the job links listedbelow and please send me an updated resume if you are interes
 
OK Labs, ST-Ericsson, and the Mobile/Wireless Ecosystem
Written by Steve Subar   
11/17/09
Two weeks ago, OK Labs and ST-Ericsson announced the selection of OK Labs as ST-Ericsson's mobile virtualization partner. To earn this coveted position, OK Labs prevailed in a rigorous evaluation
 
C++ Ninjas Needed in Santa Clara, California
Written by Brent Rogers   
09/30/09
Hello! I am a recruiter at CISCO. Our PostPath teamin Santa Clara is building a new Email SaaS business at CISCO. We are looking forsenior developers with Zimbra expertise to help us accomplish this t
 
Fighting Fragmentation with Mobile Virtualization
Written by Steve Subar   
09/21/09
Last week Motorola and T-Mobile announced the launch of a new and innovative Android-based smartphone, the Cliq. This attractive, feature-rich slider handset happens to build on a chipset and firmware
 
Insights into Router Design: Unit Testing of Networking Protocols
Written by Rajesh Kumar Venkateswaran   
09/07/09
  Unit testing is a software validation methodology through which a programmer tests individual modules or units of source code. If the programmer has been responsible for developing a networ
 
Insights into Router Design: Implementation of Networking Protocols
Written by Rajesh Kumar Venkateswaran   
09/06/09
  Modern data networking consists of a large number of networking protocols, each of which has its own domain of applicability. Some run on end stations (also called hosts), some on enterp
 
Insights and Innovations in Networking
Written by Rajesh Kumar Venkateswaran   
09/05/09
Networking devices such as routers and switches have evolved quite a bit over the past years, both in the service provider network and in the enterprise. It is a challenge to build these devices, bo
 
reddit threads community
Written by Christof Meerwald   
08/30/09
I have just started a threads community over at reddit to cover topics such as multithreading, concurrency and parallel programming. Feel free to join if you are interested. -- cmeerw.org 
 

The Latest From Dr. Dobbs

DDJ