# Friday, October 31, 2008

I had a situation where I needed to temporarily modify some read-only files on disk that were under source control (TFS).  Basically what I wanted to do was:

  1. If the file is read-only, make it writable.
  2. Modify the file.
  3. Set it back to read-only if it was originally read-only.

You could just put an if then for steps 1 and 3, but that's ugly IMO.  Here's what the originally looked like before I refactored it:

bool isReadOnly = IsFileReadonly(webConfigPath);
FileAttributes originalFileAttributes = File.GetAttributes(webConfigPath);

if (isReadOnly)
{
	File.SetAttributes(file, FileAttributes.Normal);
}

File.Copy(backupWebConfigPath, webConfigPath, true);

if (isReadOnly)
{
	File.SetAttributes(webConfigPath, originalFileAttributes);
}

So here's my refactored solution using a DisposableAction which wraps a delegate that is invoked on dispose.  Inside the using statement the file is ensured to be writable, but at the end of the using statement its original attributes are set back on the file.  All the if statements in the code above get replaced with the following concise using statement:

using (FileAsWritable(webConfigPath))
{
	File.Copy(backupWebConfigPath, webConfigPath, true);
}

I think that's much cleaner, what do you think?  The rest of the supporting code if you're interested:

private static DisposableAction FileAsWritable(string file)
{
	if (!IsFileReadOnly(file))
	{
		return new DisposableAction(/* no-op */);
	}

	FileAttributes originalFileAttributes = File.GetAttributes(file);
	File.SetAttributes(file, FileAttributes.Normal);
	return new DisposableAction(() => File.SetAttributes(file, originalFileAttributes));
}
namespace Sneal.JsUnitUtils.Utils
{
    /// <summary>
    /// Wraps a delegate all that is called on Dispose, used for wrapping
    /// an action from a method call.
    /// </summary>
    public class DisposableAction : IDisposable
    {
        private Action action;

        public DisposableAction() {}

        public DisposableAction(Action action)
        {
            this.action = action;
        }

        public void Dispose()
        {
            if (action != null)
            {
                action();
            }
        }
    }

    public delegate void Action();
}
Friday, October 31, 2008 5:39:47 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, October 18, 2007

It seems I keep running into situations where I want to mock or stub a class that is responsible for saving something out to disk.  The problem is that using a StreamWriter (or similar) is the lifetime of the writer object is shorter than the containing class, which makes it impossible to mock effectively.

Often the way around this is to implement an interface with three method calls: Open, Write, Close - so you can reuse the writer instance for multiple files thus changing the lifetime of the writer to the same as the containing class thus allowing you to mock the writer.

I've never liked this solution, it always has felt like a workaround for testability.  Instead, how about splitting the two parameters (contents and file path) into separate fluent method calls and having the Write auto-close the file like this example:

keyWriter.Write(exportKeys).To(destinationFolder);

 

...

 

public interface IExportKeyWriter

{

    IExportKeyWriter Write(ImageExportKeys keys);

    void To(string destinationFolder);

}

 

I like it because its very readable and more importantly its mockable.  I can inject a single instance of the IExportKeyWriter into my class under test.  When Write is called, the object is queued for writing to disk, and when To is called the destination file is opened, written to (using the queued object), and finally closed.

The only Problem I can think of is that it may not be obvious that you need to call the To method to have the file actually written out.

I'm hoping for some feedback on this, so I ask dear reader, what do you think?

Thursday, October 18, 2007 1:29:09 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, January 12, 2007
A conversation in a not so distant universe...

Golly, why would anyone follow the Law of Demeter and produce an orthogonal system design?  There's a reason I can call select * from table directly from my aspx page.  It's far less code and my wizard completely supports it.  TDD just slows you down, and is only for developers who write a lot of buggy code; so much code they need a computer to test their app.

What do you mean the 3rd party database has changed to a new schema that now uses a web service?  We'll luckily I can crank out an entirely new application using my wizards in a month or two, we'll just have to line of some resources to test it after I deploy it to production.

Friday, January 12, 2007 11:44:38 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, December 07, 2006
I finally found out there's a name to a design pattern I've used previously.  The open closed principle: a class should be open for extension, but closed for modification. 

A co-worker was working a fairly complex presenter class that was originally difficult to test, had way to many responsibilities, and would need to be modified each time a new area of the application was completed.  After extensive refactoring it now is testable and passes the open closed principle.  Basically the presenter class was broken down into 6 other classes which implemented a strategy pattern.  Much more maintainable and easier to understand!

Thursday, December 07, 2006 6:47:44 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, October 10, 2006

OK, you’ve finally built up your beautiful platform agnostic and persistent ignorant business domain layer.  It solves all of your business requirements and is elegant and maintainable – too bad the model doesn’t fit nicely into your user interface!

This is about the time a non-domain driven developer says, “ha, I told ya that domain model was a waste of time!  You should have modeled your objects after the user interface!”  Was it really a waste of time?  Of course not!  Well then how do we slap a UI on top of a domain model?  Chapter 11 of Jimmy Nilson’s Applying Domain-Driven Design and Patterns to the rescue.

Basically you have three options when hooking up a user interface to your domain model:

  1. The domain model hooks up directly to the UI, and it just happens to be a good fit.
  2. You wrap the domain model with a presentation specific object.
  3. You map data from the domain model to a presentation specific object.

Of interest here are options 2 and 3.  To keep the domain model clean and pure, it may make sense to create a presentation specific object that transforms a domain specific object into a user interface friendly one.  The example given in Jimmy’s book is the one where the domain model represents a name, first and last, as separate fields.  In the UI, the first and last names are placed together in a single textbox. 

Below I’ve provided an example of option #2, wrapping.  In this example ResourceWrapper in the presentation layer wraps a domain model Resource object.  One thing that makes the UI easier to work with is to flatten out object graphs like in this ResourceWrapper example, specifically the resource’s manager.

 

public class ResourceWrapper
{
    private Resource resource;

    public ResourceWrapper(Resource resource)
    {
        this.resource = resource;
    }

    public string Name
    {
        get { return resource.FirstName + " " + resource.LastName; }
        set
        {
            string[] names = value.Split(" ".ToCharArray(), 2);
            resource.FirstName = names[0];
            resource.LastName = names[1];
        }
    }

    public string ManagerName
    {
        get { return new ResourceWrapper(resource.Manager).Name; }
        set { new ResourceWrapper(resource.Manager).Name = value; }
    }

    public decimal Salary
    {
        get { return resource.Salary; }
        set { resource.Salary = value; }
    }

    public Resource GetDomainObject()
    {
        return resource;
    }
}

I have to write more code?  Yes, but you may be able to get around a lot of this by creating a generic object to object framework that sets properties via reflection and/or code generation.  In the end, wrapping or mapping domain objects sounds like a good idea when they just won’t fit nicely into the UI.

Tuesday, October 10, 2006 4:57:09 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  |