Thursday, January 28, 2010

UnitTesting made easy with the power of TypeMock

I want to test the persistence layer of my code. One of the recently added requirements for the persistence layer is that it accepts a domain class that wraps around the user name to ensure consistent handling throughout the application of a username. This is because currently the decision is to strip the Windows Domain name off of a userName before using it or storing it. Should the decision be reversed, there's a central configuration alteration to make, without having to recompile the application. How nice are changes that require a simple text file to be changed?

So the call would be:

var result=repository.GetAssociate(new UserName(DependencyContainer.GetAssociate()));
Which you can't call from the persistence layer because
  • The Dependency container is defined in an assembly not referenced by the persistence layer 
  • The UserName constructor is internal to the domain assembly
So to make the method repository.GetAssociate testable, we would have to alter the OOP design of the code to make it testable in most frameworks( because there is no public constructor for UserName).

You could of course messy up your code by using dependency injection on everything that needs testing. This concern does partly fall down if you centralize the coupling between your domain and external dependencies, but remains when you try to test individual methods inside a class, or anything internal, private, or that accesses static methods(most testing frameworks can not handle mocking out static methods, constructors, or factories, as I understand it TypeMock can)

You could make your code messier and more prone to issues in dependent code by changing username to a public interface and changing the persistence layer to accept that interface, but then automatic business logic enforcement goes out the window. If an object outside of the domain assembly can not create a copy of a domain object it has no reason to create, then it's tougher to accidentally not pass things through the proper domain classes/methods.

So how do I test this method?

Thursday, January 14, 2010

Tools for the mobile developer

I like to have the freedom to be have access to pretty much any application/functionality wherever I happen to be. In light of that here are several useful free websites, webapps, and small downloads that make that possible:
  • Project Management/bug tracking - PivotalTracker
    • Collaborative native
    • automatic emailing
    • allows you to use the same login to manage work vs personal projects
    • API so that you could write a webapp that reported bugs straight into your project tracker.
  •  Version control
    • ProjectLocker
      • Subversion/Git
      • Also project management via wiki, trac, build locker, document management
    • GitHub 
      • I had some speed issues uploading via their web interface through the corporate firewalls
      • Have not tried it with a client app
  • ToDo list -
  • LinqPad
    • linq to sql test bench
    • speedy code testing bench
    • free for all features except intellisense
    • Purchase license to enable intellisense (even for sql server 2005!)
  • Developer forums -
  • Regular expressions
    • RegExr - Online expression testing tool
  • UML/flowcharting
  • Mind mapping
  • OCR
  • Collaborative
      • White board
      • live audio
      • text chat
      • image collaboration
  • Personal music library webapp

Wednesday, January 13, 2010

T4 Generates my business objects for me

I have finally started understanding/applying Oleg Synch's T4 code generation tutorials. I'm at least to the point where I've made something useful. My goal was to design a business object generator that would be reusable between persistence and ui changes (actual code changes, or swapping out to a completely different layer) without recompiling, or making any changes what-so-ever in the business module. It consists of a Template that defines what a business object class should look like, and related scripts for particular business object details.

The main difficulties were:
  • validation 
    • centralized validation model
    • being capable of providing multiple field specific error messages, instead of just the first one that is discovered
  • mapping objects
    • looking for a way to cope with Linq-To-Sql's entities, while maintaining persistance indepdendence
What remains:
  • Validation
    • Investigate ways to push validation logic out to the client-side
  • Decide on an extensibility option
    • Partial classes
      • Would this allow someone to implement additional functionality in another assembly? That would be against the design.
    • Inheritance
      • Everyone nowadays is avoiding inheritance in favor of interfaces
    • Direct Script (not the generic template, the script specific to a business object type) modification 
    • Make the class generic so it can hold another object for additional functionality
The template and script are included.

Thursday, January 7, 2010

The Fallacy of ReUse

I've read The Fallacy of ReUse and while it presents very good arguments against reusing things. Clearly there is a path to reusable code, otherwise why would we have frameworks or .net? Why would we have so many code snippet web sites and webapps? Microsoft wrote a book on this type of reusable code and I'm in the process of reading it. Design patterns are some of the best examples of reusable code that shines or perhaps has been through it's lifecycle and was retired for a better pattern. I'd hardly call a 3-5 yr life cycle something that wasn't reusable.

I think, like most concepts in programming, there is a time and a place for code reuse, designing for reuse, and refactoring/reworking code for the purpose of reuse.

Most businesses, concepts, inventions and products don't happen magically, they are born of failure after failure. Look at how many times Thomas Edison failed to invent various things.

If your position/team/manager leaves you no time for experimentation on tools, concepts, add-ins, macros, frameworks architectures that might improve your overall work speed or team productivity, then reuse attempts/ideas/experimentation is probably not appropriate. However, I don't imagine there's a team out there that couldn't benefit from allocating time for trying alternate ways of doing things, reviewing each others' ways of doing things, or brainstorming for reusable solutions to common problems.

I also don't imagine it's something everyone can do or excel at. Most people give up on most challenges in life, that's what leaves room to strive for excellence and get there (or enjoy the time spent chasing that elusive goal).

There's code that's valuable merely because it's called in 2 places in a class. Isn't this the heart of refactoring and Don't Repeat Yourself? Code reuse to me is shooting for DRY on a slightly higher level than simple class method refactoring, although I work hard at that as well.

It's to see how far out can this reusable code scale?
Many methods in a class can make use of this code? Nice. Many classes in a project can make use of this class? Cool. Many projects in a solution can make use of this code? Sweet. Some of my reusable code is useful in projects outside of my company? Awesome.

Or perhaps I'm just passing along code I found on the web that I believe to be useful. I enjoy that too. I enjoy being someone that might have a corner or edge-case solution that other developers seek me out for.

I enjoy pretty much anything I can do to lure developers into talking code with me and I think this is a valuable niche. So maybe I'm too biased. Either way I enjoy the pursuit, your mileage may vary.

The Most reusable code in my libraries

  • First and foremost I think is the Member class  
    • No more binding using brittle string literals. 
    • Compile time member access name safety.
  • BDictionary
    • Allows for reference of a an item by key or by the index
  • String Transformations
    • Can take comma separated values,CR/LF, excel copied, SSMS results column copied  and transform them into
      • a SQL in clause
      • an array initializer
      • a string array initializer
  • bThread(of T)
    • Threading implementation with strongly typed result value
    • Wraps processing in try/catch so the thread doesn't throw an exception
  • bMacros - originally named bVbMacros but the snippet section does C# now
    • takes a partially formatted string and creates a code snippet for use in Visual Studio
    • Takes a VB object constructor and automatically generates backing fields and public readonly properties to expose those values
  • DebuggerWriter:System.IO.TextWriter
    • Wrapper to allow you to stream output to the Debugger
  • XmlFont
    • Makes serializing a System.Drawing.Font simple
  • Windows Forms specific:
    • TextBoxWriter:System.IO.TextWriter
      • Wrapper to allow you to stream output to a WinForms Textbox
    • Control Extensions
      • Extension methods for thread safe operations on the UI
      • Extension methods for nullable value binding
      • An extension for populating a comboBox with an enum Type's values
    • ErrorProviderManager
      • Wrapper for the ErrorProvider class
      • Centralized repository that takes a control, a Func delegate and the associated error message.
      • hooks into the control's validating event to run all the Func associated error conditions, if it fails validation, the ErrorProvider is updated accordingly, and vice versa
That's a fairly small amount of really reusable code. To me, whether or not the reusable code I wrote gets reused much is important, but so is what I learned from aiming for framework-worthy code and learning from the failures.

Wednesday, January 6, 2010

Good reading

Another web app based IDE

It runs code as somewhat like a console app and doesn't appear to allow command line style arguments.
Input can be fed in via Console.ReadLine, etc...

A sample including input is here where I reflect on the current or calling method name:
Sample reflection

It supports C#, Vb,  3 different types of Javascript, Ruby, Python, Perl, Lua, and many more.

Unit testing reference

The parts of unit testing I'm trying to commit to memory but keep referring back to are as follows:
  • Good unit test properties
    • automated and repeatable
    • easy to implement
    • once written, should remain for future use
    • anyone should be able to run it
    • should run at the push of a button
    • should run quickly
  • Is it a good unit test?
    • Can I run and get results from a unit test written weeks,months, years ago?
    • Can any member of the team run and get results from unit tests written weeks,months, years ago?
    • Can I run all the unit tests I've written in no more than a few minutes?
    • Can I run all the unit tests at the push of a button?
    • Can I write a basic unit test in no more than a few minutes?
  • TDD overview:
    • Write a failing test to prove code or functionality is missing
    • Make the test pass by writing production code that meets the expectations of the test
    • Refactor your code
    • [blogger's note: I would run the tests again after the refactoring]
  • Definitions
    • Integration test
      • testing two or more dependent software modules as a group
      • If the method you are testing has external dependencies (filesystem, sql server, OS, etc..) that you are not able to provide fakes for then it is an integration test
    • Unit test
      • a piece of code (usually a method) that runs another piece of code (usually a single method/function in isolation) and checks the correctness of some assumptions afterward. If the assumptions are wrong, the unit test is failed.
    • SUT - system under test (sometimes CUT - class under test)
      • when we test something, we refer to the thing we are testing as the SUT.
    • Regression
      • a feature that used to work and now doesn't
    • Naming conventions
      • Project
        • [ProjectUnderTest].Tests
      • Classes
        • For each class, create at least one class with the name [ClassName]Tests
      • Method
        • For each method, create at least one test method with the following name:
          • [MethodName]_[StateUnderTest]_[ExpectedBehavior]
            • StateUnderTest
              • The conditions used to produce the behavior
            • ExpectedBehavior
              • What you expect the tested method to do under the specified conditions
          • example: IsValidFileName_validFile_ReturnsTrue
    • Typical test method body
      • Arrange objects, creating and setting them up as necessary
      • Act on an object
      • Assert the expected results
    • Types of unit tests
      • State based testing/state verification
        • you act on something, assert the state after acting on that something or its collaborators(dependencies)
      • Interaction testing
        • tests how an object sends input to or recieves input from other objects
        • how that object interacts with other objects
    • Stub
      • a controllable replacement for an existing dependency(or collaborator) in the system.
      • By using a stub, you can test your code without dealing with the dependency directly.
      • Can not fail a test - not asserted against
    • Mock
      • a fake object in the system that decides whether the unit test has passed or failed. It does so by verifying whether the object under test interacted as expected with the fake object. There's usually no more than one mock per test.
      • Asserted against
    • Fake
      • generic term for mock or stub
  • Things to look out for
    • Why are we doing multiple asserts in a single test? How hard would it be to separate them into separate tests
    • Complicated hand-written stubs or mocks should be overcome with a Isolation (Mock) framework

Tuesday, January 5, 2010

My first go at Unit Testing

I've picked up "The Art of Unit Testing  with examples in .net" and I'm almost halfway done reading it. It has provided a very good walkthrough of unit testing and based on what I understand from straight reading, I've implemented some tests using Visual Studio 2008 professional's built in test functionality and RhinoMocks.

public void IsValidCopyDictionary_IncludingIdentifier_EqualsReflectionCount()
var source = Rhino.Mocks.MockRepository.GenerateStub<IAmAnAssessment>();
var destination=Rhino.Mocks.MockRepository.GenerateStub<IAmAnAssessment>();
var dictionary = ModelAssessment.ActionDictionary(destination, source, true);
var modelProperties=typeof (ModelAssessment).GetProperties();
Assert.AreEqual(dictionary.Count, modelProperties.Count(), "CopyDictionary:include is invalid");
public void IsValidCopyDictionary_ExcludingIdentifier_EqualsReflectionCount()
var source = Rhino.Mocks.MockRepository.GenerateStub<IAmAnAssessment>();
var destination = Rhino.Mocks.MockRepository.GenerateStub<IAmAnAssessment>();
var dictionary = ModelAssessment.ActionDictionary(destination, source, false);
var modelProperties = typeof(ModelAssessment).GetProperties();
Assert.AreEqual(dictionary.Count, modelProperties.Count()-1,"CopyDictionary:exclude is invalid");