Caffeine-Powered Life

Data Access Still Matters

This blog post was inspired by Bill Karwin’s book SQL Antipatterns:Avoiding the Pitfalls of Database Programming. I read this over Thanksgiving weekend. If you are a developer, and you do database work, this is on the must-read list.

I agreed with just about everything in his book except a few little details. In Chapter 4, “ID Required,” Mr. Karwin lays out two antipatterns.

  1. The primary key is always an autoincrementing column named id.
  2. The primary key is not necessary when there is another unique restriction present naturally in the data.

Regarding the First

The first condition is something like this.

1
2
3
4
5
6
7
8
CREATE TABLE employees (
  id INT NOT NULL IDENTITY(1, 1),
  last_name VARCHAR(64) NOT NULL,
  first_name VARCHAR(64) NOT NULL,
  department_id INT NOT NULL,
  -- ...
  CONSTRAINT [pk_employees] PRIMARY KEY CLUSTERED ([id] ASC)
);

I agree that not every table requires a primary key named id. There are lots of situations where not using id or not having autoincrementing values is helpful. However, understand that with technologies like NHibernate with fluent mapping or Rails’ ActiveRecord, it is terribly damn convenient for the developer.

NHibernate with explicit mapping won’t much matter, since you must define the exact purpose of each and every column. It’s only when you’re using some of the implicit mapping magic that this comes into play.

Also, if you’re using PostgreSQL, there is some syntactic sugar you can use when joining tables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- Using id
SELECT e.id AS employee_id, e.first_name, e.last_name, SUM(te.total_hours) AS sum_total_hours
FROM employees e
  INNER JOIN time_entries te ON e.id = te.employee_id
WHERE te.entry_date = N'2013-06-16'
GROUP BY e.id, e.first_name, e.last_name

-- Using table-specific columns
SELECT e.employee_id
SELECT e.id AS employee_id, e.first_name, e.last_name, SUM(te.total_hours) AS sum_total_hours
FROM employees e
  INNER JOIN time_entries te USING (employee_id)
WHERE te.entry_date = N'2013-06-16'
GROUP BY e.id, e.first_name, e.last_name

In the above example, you can use the USING keyword to join two tables on columns when the names match. If you’re explicit about calling the Employee ID employee_id instead of id, you can take advantage of syntax.

Consider your data access. If you think you’ll be handcrafting a lot of SQL, then maybe this syntactic sugar is worth it. Are you using a database where this even matters? Are you using a data access tool (NHibernate with fluent mapping, ActiveRecord) that takes advantages of the primary key being called id? There’s a lot to consider here beyond, “Don’t do it.”

Regarding the Second

Mr. Karwin also describes the following as an antipattern.

1
2
3
4
5
6
CREATE TABLE users (
  user_id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
  username VARCHAR(64),
  -- ...
);
CREATE UNIQUE INDEX [unique_username] ON [users] ([username]);

He says that this table has two unique identifiers, since both user_id and username unique identify a row. So I tried this in my Portfolio project. I have the ability to create tags and apply these tags to events. The slug for these tags are each unique. So I tried dropping the id column in favor of just using the slug column as the primary key. I made sure to turn on cascading updates every place a tag was referenced. Imagine my surprise when I saw this error message when I tried to edit a tag.

OK, I wasn’t surprised. I knew this would happen. But only because I’ve been burned by it before.

NHibernate won’t let you change the primary key of a loaded record. As it turns out, neither will Entity Framework or ActiveRecord. So I would offer up just one little addendum to the second snafu. It is fine to use a real-valued column if that value isn’t going to change, depending on what kind of data access technology you are using in your application. Are usernames allowed to change? Are tag slugs going to be modified? Are you sure employees never get the social security numbers wrong? If so, I wouldn’t recommend using those as primary keys — with or without cascading.

Fixing allowDefinition=MachineToApplication Build Error

Just a quick fix for this build error.

It is an error to use a section registered as allowDefinition=‘MachineToApplication’ beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

If you look in your project’s obj folder, you will probably see multiple outputs. If you haven’t made any changes to the default build configurations, then you will have both Debug and Release folders. This is the cause of this error.

The fix is simple, we just need to get rid of these folders. We’re going to add a pre-build event that will get rid of all obj folders except the one we are building. Paste the following into your Pre-build event command line.

rmdir /s /q $(ProjectDir)\obj
mkdir $(ProjectDir)\obj
mkdir $(ProjectDir)\obj\$(ConfigurationName)

Like so…

I need this on every project I work on. Time to put it out here instead of looking it up from scratch each time.

Using Modernizr to Detect HTML5 Support

Just a little something I wrote yesterday. I had an issue of adding a datepicker to a UI. Being the developer I am, my first response was, “Get a better browser. Chrome and Firefox both native support <input type="date"/> tags.” I guess that didn’t fly. So, this is what I wrote instead.

I use the Modernizr library. I also take advantage of the following lines doing the exact same thing.

1
2
3
var now = new Date();
now.getFullYear();      // => returns the current year
now["getFullYear"]();   // => returns the current year

That’s all!

Anemic Domain Models: Blame Complexity

This is a reply to Steve Wilkes’ post on I See Anemic Domain Models. I was going to write this as a reply, but then it got way too long.

I also dislike the Anemic Domain Model antipattern. I love the idea of nouns and verbs. Our models, or classes, are nouns. The actions those models can take, or verbs, become methods. You end up with a wonderful programming grammar.

Keep it simple.

Let’s start with a really simple domain model. We have a task. We can complete that task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Task
{
  public virtual int Id { get; set; }
  public virtual string Description { get; set; }
  public virtual DateTime CreatedAt { get; set; }
  public virtual DateTime? CompletedAt { get; set; }
  public virtual bool IsCompleted { get; set; }

  public virtual void Complete()
  {
    if (!IsCompleted)
    {
      IsCompleted = true;
      CompletedAt = DateTime.UtcNow;
    }
  }
}

The above it truly some beautiful code. I wish everything I worked on looked like that.

To use the above method, we will probably do something like this.

1
2
3
4
5
6
7
8
9
using (var session = sessionFactory.OpenSession())
{
  using (var txn = session.BeginTransaction())
  {
    task = session.Load<Task>(id);
    task.Complete();
    txn.Commit();
  }
}

Wow! That was so easy!

It doesn’t always get better.

When an object is simple and well-defined, this is great. So let’s make it a bit more complicated. What if instead of a simple IsCompleted flag, we now have user-defined statuses? Not only do we want to trak the current status of a task, we want to maintain a status history.

1
2
3
4
5
6
7
8
9
create table task_statuses (
  task_status_id int not null identity(1, 1),
  description varchar(256) not null,
  is_default bit not null,
  is_completed bit not null,
  trigger_emails bit not null,
  trigger_chart_regeneration bit not null,
  constraint [pk_task_statuses] primary key clustered ([task_status_id] asc)
);

We should also check that we’re not setting a status twice. There’s nothing completely awful if this happens, so there’s no need for an exception, probably a race condition in the UI or something like that. However, we do want to know about it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Task
{
  public virtual TaskStatus CurrentStatus { get; set; }

  public virtual IList<StatusHistory> StatusHistories { get; set; }

  public virtual void SetStatus(TaskStatus newStatus)
  {
    if (this.CurrentStatus == newStatus)
    {
      log.Warn(string.Format("Attempting to set task {0} from status {1}:{2} to status {3}:{4}. Someone should really write a better UI to prevent this scenario from happening.", Id, CurrentStatus.Id, CurrentStatus.Description, newStatus.Id, newStatus.Description));
      return;
    }

    var statusHistory = new StatusHistory
    {
      Status = newStatus,
      AssignedTo = newStatus.AssignedTo,
      Task = this,
      CreatedAt = DateTime.UtcNow
    };
    this.StatusHistorys.Add(statusHistory);
    this.CurrentStatus = newStatus;
    this.AssignedTo = newStatus.AssignedTo;
    this.IsCompleted = newStatus.IsCompleted;
  }
}

While we’re adding complexity, let’s introduce a task workflow. You’re only allowed to pass from certain statuses to other statuses given conditions stored in a database table. The simple version of this table would look something like the following.

1
2
3
4
5
6
create table status_workflows (
  status_workflow_id int not null identity(1, 1),
  from_status_id int not null,
  to_status_id int not null
  constraint [pk_status_workflows] primary key clustered ([status_workflow_id] asc)
);

Our method signature would need to change to include these workflows. The

1
2
3
4
5
6
7
8
9
10
11
12
13
public virtual void SetStatus(Status newStatus, IEnumerable<StatusWorkflow> statusWorkflows)
{
  bool isAllowedWorkflow = statusWorkflows
     .Any(sw => sw.FromStatus == this.CurrentStatus && sw.ToStatus == newStatus);

  if (!isAllowedWorkflow)
  {
    // We've written a custom ApplicationException to handle this scenario.
    throw new InvalidWorkflowTransitionException(CurrentStatus, newStatus);
  }

  // etc.
}

This method is public, so we should probably take care of some null checks. FxCop is going to warn about that.

1
2
3
4
5
6
7
public virtual void SetStatus(Status newStatus, IEnumerable<StatusWorkflow> statusWorkflows)
{
  if (newStatus == null) throw new ArgumentNullException("newStatus");
  if (statusWorkflows == null) throw new ArgumentNullException("statusWorkflows");

  // etc.
}

What if we also need to trigger emails? We know better than to create a new SmtpClient instance in our class because that’s not going to be unit-testable. That means that we need to create a wrapper class for SmtpClient and pass in the adapter via method injection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public virtual void SetStatus(
    Status newStatus,
    IEnumerable<StatusWorkflow> statusWorkfows,
    ISmtpAdapter smtpAdapter)
{
  // etc.

  // Fetch the correct email template from ???
  Template mailTemplate = ...;

  // Set the task for mail template.
  mailTemplate.Task = this;

  // Create a new email message and send it.
  string mailBody = template.TransformText();
  MailMessage mailMessage = ...;
  smtpAdapter.Send(mailMessage);
}

Oh, we also have burndown chart regeneration. It turns out, I need to know a lot more info from the database to regenerate that burndown chart. Now I’m passing around my database session.

1
2
3
4
5
6
7
8
9
public virtual void SetStatus(
    Status newStatus,
    IEnumerable<StatusWorkflow> statusWorkfows,
    ISmtpAdapter smtpAdapter,
    IBurndownChartGenerator burndownChartGenerator,
    ISession session)
{
  // Really?
}

As you see, as our application complexity grows, our method continues to add more and more parameters, and our method grows longer.

This is why double dispatch exists.

Screw it. This is getting way too complicated for a domain model. Let’s just go with what we learned from Eric Evans in Domain Driven Design instead. We’ll just use the double dispatch pattern.

1
2
3
4
public virtual void SetStatus(Status newStatus, IStatusSetter statusSetter)
{
  statusSetter.SetNewStatus(this, newStatus);
}

Wow! We have finally cleaned up that code! It looks a lot better now. And I didn’t even get into assigning a task to a user. (Is the user active? Is the user on this project? Can the user be assigned tasks with this task type? Are you doing any type of capacity planning?)

But now what’s the point of the SetStatus() method? All the work is now being done by our IStatusSetter logical service. Let’s look at the next two pieces of code that do the exact same thing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Version 1:
IStatusSetter statusSetter = ServiceLocator.Instance.GetService<IStatusSetter>();
ISession session = ServiceLocator.Instance.GetService<ISession>();
using (var txn = session.OpenTransaction())
{
  task = session.Load<Task>(id);
  nextStatus = session.Load<TaskStatus>(nextStatusId);
  task.SetStatus(nextStatus, statusSetter);
  txn.Commit();
}

// Version 2:
IStatusSetter statusSetter = ServiceLocator.Instance.GetService<IStatusSetter>();
ISession session = ServiceLocator.Instance.GetService<ISession>();
using (var txn = session.OpenTransaction())
{
  task = session.Load<Task>(id);
  nextStatus = session.Load<TaskStatus>(nextStatusId);
  // We skip the double dispatch and just call SetNewStatus directly.
  statusSetter.SetNewStatus(task, nextStatus);
  txn.Commit();
}

I write services because our models are complicated. I never get the simple music library, blog, or to-do list apps to work on any longer. This leads to the Single Responsibility Principle. If any class is handling both setting statuses and assigning tasks and sending emails and updating burndown charts, I’m instantly going to ask, “Who threw up all over this code?” That is plainly too much going on inside one class.

Honestly, service methods are just better ways of handling this kind of stuff. What would you rather see in your Task object? All of that stuff up there or none of it?

ActiveRecord is too busy by default.

If you’re used to using Rail’s ActiveRecord, I’m going to stake this claim right away: ActiveRecord has enough going on already. Please, do not add business logic to your ActiveRecord models. Between the finders and validators, these classes already have enough going on. Adding any business logic to them just makes them even more complicated.

This is an ActiveRecord object that has only minimal logic for validations and a few custom finders. I even tried to keep this class small by using helpers and concerns where I could.

episode.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require 'textacular/searchable'

class Episode < ActiveRecord::Base

  include ActiveModel::ForbiddenAttributesProtection
  include EpisodeValidations
  include NewEpisodeBehavior
  include MarkdownBehavior

  # Add support for PG full text search
  extend Searchable(:title, :summary_markdown, :content_markdown)

  # Active record relations.
  has_and_belongs_to_many :tags

  # Named scopes.
  scope :free_to_view, lambda { with_tag('free') }
  scope :published, lambda { where('status = ? and published_on <= ?', 'published', Date.today) }
  scope :order_by_published_on, lambda { order('published_on desc') }
  scope :with_tag, lambda { |slug| joins(:tags).where('tags.slug = ?', slug) }

  # Callbacks
  before_validation :ensure_video_path_leading_slash, :render_html

  def free_to_view?
    self.tags.collect(&:slug).include?('free')
  end

  def published?
    self.published_on <= Date.today && self.status == 'published'
  end

  def to_param
    self.slug
  end

  private

    def ensure_video_path_leading_slash
      if self.video_path
        self.video_path = '/' + self.video_path unless self.video_path[0] == '/'
      end
    end

    def render_html
      self.content_html = markdown(self.content_markdown)
      self.summary_html = markdown(self.summary_markdown)
    end

end

We still end up with 50 lines of code, and this class doesn’t even perform any real business logic.

Let’s start drawing some lines.

Not all software is easy. But that doesn’t mean it’s going to be difficult.

Your service classes should NOT be static.

There’s a big difference in testability between the following lines of code…

1
2
ITaskCompletionService taskCompletionService = ...; // get the service
taskCompletionService.CompleteTask(123);

…and this…

1
TaskCompletionService.CompleteTask(123);

The latter version is nearly impossible to test the myriad scenarios that you may encounter. Also, it means that everything that is used by TaskCompletionService is also going to be a static reference. That means that those are going to be nearly impossible to test, as well.

Your data model is not your domain model is not your view model.

It doesn’t take very much complication before we run into a scenario where what we store in the database is not the same as the object that we manipulate in code. Frequently, this business object isn’t what I want to show the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class EmployeeDataRow
{
  // This is what the employee record looks like when serialized
  // in our database.

  public int EmployeeId { get; set;}
  public string SSN { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public IDictionary<string, string> Properties { get; set; }
}

public class Employee
{
  // This is our domain model that we work with in our
  // code. We have created an actual SSN type.

  private readonly EmployeeDataRow data;

  public Employee()
    : this(new EmployeeDataRow())
  {
  }

  public Employee(EmployeeDataRow data)
  {
    this.data = data;
  }

  public int EmployeeId { get; set; }
  public SSN SSN
  {
    get { return new SSN(data.SSN); }
    set { data.SSN = value.ToString(); }
  }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public MailAddress WorkEmail
  {
    get { return GetPropertyValue<MailAddress>("work_email"); }
    set { SetPropertyValue("work_email", value); }
  }
  public DateTime DateOfHire
  {
    get { return GetPropertyValue<DateTime>("date_of_hire"); }
    set { SetPropertyValue("date_of_hire", value); }
  }

  // etc. with more properties...
}

public class EmployeeViewModel
{
  // This is what we'd actually display to users, which probably
  // won't be the same as what we store in the database or the
  // domain model that we actually work with in code.
  //
  // SSN will be a string masked as XXX-XX-1234.
  //
  // Date of hire will be a string formatted as dd-mmm-yyyy.
  //
  // Work email will only show the part before the '@'.
  //
  // Salary estimate needs to be computed for hourly employees, based on
  // 40 hrs per week, 48 weeks per year.
}

Yes, these object are all very similar. However, what we store, what we work with, and what we display to users is not the same object.

We also need to realize that the objects that we work with (our domain models) can have a lot more layers to them than our data objects will. For example when a user shows up to your web site that user is a Guest. Once they log in, that person is a User. You might even distinguish between a FreeUser and a Subscriber. Yes, all of these objects will be serialized to a users table. However, it should be clear that different types of users would have different methods available to them.

Conclusion.

There are reasons that domain models end up anemic. Our rules are complex. Our classes are too big. If I store everything that a Task can do, that will be a plain and clear violation of the Single Resonsibility Principle. Writing software is about making choices. I would much rather have clear domain service that does one thing than have one Task class with too many built-in features.

Unit Testing a Controller Action

This is one of those sore subjects that never seems to get any easier. There’s a lot more MVC stuff out there, and most of it is junk. Let’s review a few simple rules.

What Should a Controller Action Do?

  1. Do any web-specific interactions. This may mean handling Session or Request variables, as necessary.
  2. Call into a service layer, as necessary.
  3. Return an ActionResult.

That’s it. If your controller is doing more than that, then your controller is doing too much stuff.

What About That Service Layer?

I see a lot of code that looks something like this. There’s nothing technically wrong with code that looks like this.

EventsController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class EventsController : ApplicationController
{
  private readonly IEventsService eventsService;

  public EventsController(IEventsService eventsService)
  {
    this.eventsService = eventsService;
  }

  public ActionResult Index()
  {
    var e = eventsService.GetEvents();
    return View("Index", e);
  }

  public ActionResult Show(int id)
  {
    var e = eventsService.GetEventById(id);
    return View("Show", e);
  }

  [HttpGet]
  public ActionResult New()
  {
    var model = new Event();
    return View("New", model);
  }

  [HttpPost]
  public ActionResult New(Event e)
  {
    eventsService.CreateNewEvent(e);
    return RedirectToAction("Show", new { id = e.Id });
  }

  [HttpGet]
  public ActionResult Edit(int id)
  {
    var e = eventsService.GetEventById(id);
    return View("Edit", e);
  }

  [HttpPost]
  public ActionResult Edit(Event e)
  {
    eventsService.UpdateEvent(e);
    return RedirectToAction("Show", new { id = e.Id });
  }

  [HttpDelete]
  public ActionResult Delete(int id)
  {
    eventsService.DeleteEvent(id);
    return Json(new { success = true });
  }
}

Honestly, if every MVC application I ever looked at was structed like that from now on, I would be mostly satisfied. My one gripe with this is that I can tell, without even looking, that your IEventsService implementation is going to be just as ugly as your EventsController would have been. You’ve just moved the ugly down one layer. Sweeping dirt under the rug doesn’t get rid of the dirt!

Still, this is testable now.

Writing The Test

Since we’ve made our controllers so thin, writing the test is actually really easy now.

EventsControllerTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[TestFixture]
public class EventsControllerTests
{
  public class EventsControllerTestContext
  {
    public void InitializeContext()
    {
      Controller = new EventsController();
      Event = new Event();
      MockService = new Mock<IEventsService>()
      {
        DefaultValue = DefaultValue.Mock
      }
    }

    public EventsController Controller { get; set; }
    public Event Event { get; set; }
    public Mock<IEventsService> MockService { get; set; }
  }

  public class GetIndex : EventsControllerTestContext
  {
    [SetUp]
    public void Before_each_test()
    {
      InitializeContext();
    }

    [Test]
    public void It_fetches_events()
    {
      Controller.Index();
      MockService.Verify(x => x.GetEvents(), Times.Once());
    }

    [Test]
    public void It_returns_a_view()
    {
      var actionResult = Controller.Index();
      Assert.IsInstanceOf<ViewResult>(actionResult);
    }

    [Test]
    public void It_has_the_expected_model()
    {
      var actionResult = Controller.Index();
      object model = ((ViewResult)actionResult).Model;
      Assert.IsInstanceOf<IEnumerable<Event>>(model);
    }
  }
}

What is there to test?

  1. Was the correct service called?
  2. Is the expected output returned?
  3. Does the model match?

That’s it. Repeat as necessary.

I Still Love/Hate CoffeeScript

The Love

  1. It’s a lot less code and syntax noise.
  2. It creates really pretty JavaScript and does all the “nasty stuff” for you.

Examples are fun, so let’s look at something I wrote this week.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class MultiSelect

  constructor: (options) ->
    defaults =
      checkboxSelector: ".multi-select-checkbox",
      onSelector: ".multi-select-on",
      selectAllSelector: "#multi-select-all"
    @options = $.extend(defaults, options)
    console.log("MultiSelect: constructor finished")

  hide: ->
    console.log("MultiSelect: hide()")
    $(@options.onSelector).hide()

  initialize: ->
    @hide()
    @listenForCheckedEvent()

  listenForCheckedEvent: ->
    # Be sure to call .bind() on the callback, otherwise the callback
    # will have the context of the checkbox, not the class definition.
    $(@options.selectAllSelector).on("click", (->
      isChecked = $(@options.selectAllSelector).is(":checked")
      console.log("MultiSelect: select all was clicked. isChecked: #{isChecked}")
      @toggleChecked(isChecked)
    ).bind(@))

  setChecked: (value) ->
    console.log("MultiSelect: setChecked(#{value})")
    $(@options.checkboxSelector).prop("checked", value)

  show: ->
    console.log("MultiSelect: show()")
    $(@options.onSelector).show()

  toggleChecked: (isChecked) ->
    if (isChecked)
      @setChecked(true)
    else
      @setChecked(false)

There’s nothing too difficult. All I want to do is have a “Select All” checkbox on a web site that selects everything when checked. I also need to the ability to show/hide these checkboxes. 40 lines, including whitespace, comments and console logging.

Here’s the generated output of that class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
window.MultiSelect = (function() {
  function MultiSelect(options) {
    var defaults;
    defaults = {
      checkboxSelector: ".multi-select-checkbox",
      onSelector: ".multi-select-on",
      selectAllSelector: "#multi-select-all"
    };
    this.options = $.extend(defaults, options);
    console.log("MultiSelect: constructor finished");
  }

  MultiSelect.prototype.hide = function() {
    console.log("MultiSelect: hide()");
    return $(this.options.onSelector).hide();
  };

  MultiSelect.prototype.initialize = function() {
    this.hide();
    return this.listenForCheckedEvent();
  };

  MultiSelect.prototype.listenForCheckedEvent = function() {
    return $(this.options.selectAllSelector).on("click", (function() {
      var isChecked;
      isChecked = $(this.options.selectAllSelector).is(":checked");
      console.log("MultiSelect: select all was clicked. isChecked: " + isChecked);
      return this.toggleChecked(isChecked);
    }).bind(this));
  };

  MultiSelect.prototype.setChecked = function(value) {
    console.log("MultiSelect: setChecked(" + value + ")");
    return $(this.options.checkboxSelector).prop("checked", value);
  };

  MultiSelect.prototype.show = function() {
    console.log("MultiSelect: show()");
    return $(this.options.onSelector).show();
  };

  MultiSelect.prototype.toggleChecked = function(isChecked) {
    if (isChecked) {
      return this.setChecked(true);
    } else {
      return this.setChecked(false);
    }
  };

  return MultiSelect;
})();

We’re up to 51 lines, mostly for a lot of closing } and junk like that. Also, since CoffeeScript generates prototypical classes, there’s a whole lot of MultiSelect.prototype.* going on. Look at all those times you have to type out the work function. That’s fun in a functional language. Finally, my friendly comments were stripped out of the compiled CoffeeScript. Hey! I put those comments there for a reason!

The Hate

The hate boils down to two simple pieces.

  1. Just write better JavaScript.
  2. Debugging is a bitch.

As mentioned above, CoffeeScript just generates JavaScript. CoffeeScript doesn’t run anywhere. Debugging goes something like this:

  1. Get a JavaScript error on line ##.
  2. Look at the compiled JavaScript.
  3. Find that line in CoffeeScript that generated line ##, since you’re all but guaranteed that it won’t be the same.

The Conclusion

I write better JavaScript because I know CoffeeScript. Seeing and reading good JavaScript output has been incredibly beneficial for me. There are plenty of bad JavaScript examples out there. I long for languages like CoffeeScript, where conciseness and clarity are first-class citizens.

Solving the Problem Isn’t Enough

I found myself saying the following way too often in the past three weeks. So, I’m putting it on my blog. Maybe someone will read it, and I won’t have to have this conversation in the future.

  1. How do I solve the problem?

  2. How do test my solution?

  3. Is my solution written in such a way that allows for isolated and automated testing?

If you know me and my projects, it’s been a rough few weeks. I’m coming in on the tail end of a project that is late, not meeting client expectations, has a very poor quality, little quality, and no technical leadership. We’re doing the best we can in a short time to rectify the problem, but the damage is done.

Do you remember high school math class, when your teacher told you to, “Check your work?” That’s what testing is all about. The answer shouldn’t be, “We’ll run the application in production and see if we can get the right answer.” That’s unacceptable in any business environment. The good news is that we do have shared development and staging environments, but the data in these environments is constantly changing as other developers and testers work. No, the right answer must include test isolation. How do you verify your solution is correct is a sustainable, repeatable way, where the work of other developers won’t affect your ability to produce a desired result?

Solving the problem is not enough.

Manually testing the solution to the problem is not enough.

Your solution must allow for isolated and automated testing. If it doesn’t, go back to the drawing board. You’re not done working the problem.

First Steps on Linux Mint

It’s no secret that I love my Mac. Until very recently, I did all of my Windows stuff in VMware Fusion. My “Windows stuff” usually means programming in Visual Studio. I have a pretty good MacBook Pro. So when I build out a VM, I usually give it 2 cores and 4 GB of RAM. It’s not a ton of resources, but since it’s all SSD, it still does pretty darn well.

Until I decided to upgrade everything. I went from Windows 7 + SQL Server 2008 R2 + Visual Studio 2012 to Windows 2012 R2 + SQL Server 2012 + Visual Studio 2013. My Macbook started this weird combination of crying and laughing at me.

So that means it’s new computer time! Even though I’m working in Windows, I’m still completely addicted to my Linux-based host environment. Let’s just say that now when I run my Windows environment, I’m giving it 4 cores and 16GB of RAM, and that still isn’t all of the available system resources.

Install Linux Mint

First download the OS from linuxmint.com. I went with the 64-bit XFCE, just because I don’t need that much of a desktop environment.

Get Rid of Sudo Passwords

Look, I know what sudo does. If I need to sudo something, I’m going to do it, and asking for my password is just going to annoy me. We’ll use visudo to edit the /etc/sudoers file.

$ sudo visudo

To this file, add the following line.

jm ALL=NOPASSWD:ALL

Update Everything

This one might take a while, even on a really fast machine.

$ sudo apt-get update
$ sudo apt-get dist-upgrade

Install A Lot of Things

Because.

$ sudo apt-get install build-essential git libssl-dev ruby1.9.3 vim-nox

Other Installations

  1. Grab rbenv, following the instructions at https://github.com/sstephenson/rbenv.
  2. Install ruby-build. Instructions are at https://github.com/sstephenson/ruby-build
  3. Go crazy with Tim Pope’s VIM pathogen. Install those scripts!
  4. Install Virtual Box from virtualbox.org.

Go have some fun on Linux!

Using Stored Procedures With Dapper

I’m currently working with one of the those clients: one who requires all data access to go through Stored Procedures. All of their .NET code uses IDataReader and IDataWriter stuff, even though this is 2013. They have the internal philosophy that dictates, “It’s how all our other projects are written, so why would we ever change?”

Well, because time marches on, for one, even if you choose not to.

Never mind that the application requires filtering, sorting, and paging. Never mind that there are hundreds of thousands of database records. Never mind that this requires us to write dynamic SQL inside of a stored procedure and then execute that stored procedure. Never mind that any compilation advantage you used to have will be completely lost. Never mind that building out dynamic SQL in C# is much easier than doing it in T-SQL.

Needless to say, I lost this battle. For whatever reason, I respect data folks enough to actual grant this concession. I’m not sure why this is, but I keep going back and forth in my mind about databases. Ultimately, I really do believe that your application is its data.

1
2
3
4
5
6
7
8
9
10
11
12
while (reader.Read())
{
  string stringValue = GetValue<string>(reader, "string_column", "");
  int intValue = GetValue<int>(reader, "int_column");
  decimal decimalValue = GetValue<decimal>(reader, "money_column");
}

public static T GetValue<T>(IDataReader dataReader, string columnName, T valueIfNull = default(T))
{
  object columnValue = dataReader[columnName]
  return (columnValue != DBNull.Value) ? (T)columnValue : valueIfNull;
}

However, even though I am willing to write your stupid stored procedures, I’m not going to worry about that common junk of mapping the result back to an in-memory object. I’m more than happy to let Dapper do all that for me. It turns out, Dapper does this quite easily. Simply set the commandType parameter when sending a query.

1
var employees = conn.Query<Employee>("dbo.GetAllEmployees", commandType: CommandType.StoredProcedure);

And that’s it!

Are Bad MVC Examples Creating Bad Programmers?

Two days ago, I was brought in a project that is already month behind. I don’t want to go into a bunch of blame game stuff, but let’s just say that everything isn’t rainbows and unicorns at this particular client. Many of the problems has to do with things well outside the developers’ control: infrastructure, environment, and corporate IT rules. All the common players.

I was told that the biggest issue is that developers haven’t been able to even start writing the front-end application because the database schema is still changing. Furthermore, they are having problems with progress on the back-end processes because of the same issue.

What do I care about your schema?

The UI for the application has been set for quite a while. There’s no reason a developer can’t start writing it. So, that’s the first thing I did. It’s HTML, CSS, and JavaScript over some simple forms. It took me less than a day once I got everything in place. The MVC project is just a bunch of stuff returning a ViewResult, there is no database behind it, and I don’t really need one.

We even know what should happen when various buttons are clicked in the application. So we can name our MVC actions accordingly, we know what data needs to be passed into the action, and we know what values needs to be added or modified.

The only thing we really don’t know is how the various property updates will be resolved in the database.

Every MVC example I see in the wild involves someone creating a table, using an ORM to pull those tables into as objects, perhaps putting validators on those objects, and then dropping those objects straight onto the screen. That’s great when all you really need is basic forms-over-data CRUD.

That’s not the case here. Here, we have a very large database with multiple consumers. We are writing new functionality. Assuming anything close to typical ORM-like functionality is a bad premise.

Check out my earlier piece on functional core/imperative shell. We should be encapsulating the business logic free from the data. Use interfaces, or at least database-free DTOs instead of your actual entities. The entities created by Entity Framework or NHibernate or ActiveRecord already have enough going on without you adding business logic to them. Do you really want a small, maybe insignificant change to the database affecting your entire application because of tight coupling?

We’re probably going to end up with a lot of DTOs if we program like this. That’s fine, because tools like Automapper make this no longer a problem. We can easily create a map that gets us from one layer to another very easily. All a data layer, business layer, or UI layer should care about is the shape of an object. Sometimes, these three layers are all the same, but we have to allow for the times that they either are not the same, or the times when decoupling is favored over drag-and-drop programming.

I understand that developers want simple. Simple is great when simple works. Just remember that simple rarely works in large organizations with big, multi-system databases.