Tag Archives: functional programming

Using delegates for loose coupling and easy unit testing

In a typical ASP.NET MVC or WebApi project, controller actions often do nothing more than make a service call, map the returned domain object to a view model, and either render a view with the model or simply return it for the framework to serialize as JSON. Using AutoMapper, a simplified WebApi controller action may look something like

public EmployeeViewModel GetEmployee(string employeeName)
{
  var employee = _employeeService.GetByName(employeeName);
  var viewModel = Mapper.Map<EmployeeViewModel>(employee);
  return viewModel;
}

This is a pretty common but difficult to test pattern because of the static Mapper dependency. You can’t actually unit test the controller action without having a properly (or at least minimally) configured static Mapper. New versions of AutoMapper provide different ways to solve this problem, like the injectable IMapper interface, but I want to demonstrate another method to reduce coupling and ease unit testing.

In this entry, I’ll demonstrate how to get rid of the static Mapper dependency without using the IMapper interface, which exposes several overloads to map one data type to another, or creating your own interface that serves a similar purpose. Instead, we’ll inject a delegate whose signature is very expressive.

public delegate TDest MapperFunc<in TSrc, out TDest>(TSrc source);

Read more »

Two reasons your MarkLogic code is failing silently, part 2

Silent failures are a programmer’s worst nightmare, and in a world where first class debuggers are few and far between, those silent failures are sure to drive us crazy.  In the first half of this article, we discussed silent failures in MarkLogic due to XML namespace issues.  XML namespace issues are going to crop up in any implementation of XQuery, though, so there are many resources to reference in addition to my article.

In the second (and last) part of the article, we’ll discuss a feature specific to MarkLogic’s XQuery implementation.  This feature is called function mapping.

Read more »

Convert an integer to a sequence of digits in Xquery

I am new to the functional programming paradigm and Xquery. As part of a larger exercise, I wanted to sum the digits of an integer.  The first part of that problem is to solve the smaller problem: convert an integer to a sequence of integers that I can then pass to fn:sum as a parameter.

(: I've declared the function in the nwnu namespace for testing purposes :)
declare function nwnu:number-to-seq($num as xs:integer)
as xs:integer* {
  if($num gt 9) then
    (
      nwnu:number-to-seq(xs:integer(math:floor($num div 10))),
      xs:integer(math:floor($num mod 10))
    )
  else
    $num
};

Read more »