Review: Swift for the Really Impatient

I’ve recently finished reading Swift for the Really Impatient. It was a really good book; I’d give it 4 out of 5 stars.

I had previously read Scala for the Impatient by Cay S. Horstmann. I’d like to note that, despite the similarity in title, Swift for the Really Impatient is not written by Cay S. Horstmann. I found the writing style to be noticeably different, but in neither a good nor a bad way. I just wanted to mention that Swift for the Really Impatient is written by Matt Henderson and Dave Wood, in case you’re a Horstmann devotee.

I’d like to make one thing clear for future readers. This book will not teach you to write your first functional OS X or iOS application; it assumes you’re an experienced Objective-C developer wanting to learn Swift’s syntax quickly. It differs in this way from Horstmann’s books, the style of which the authors have attempted to mimic. For example, after reading Scala for the Impatient the reader will be be able to write parsers, perform file and network functionality, as well as design and implement a minimal (yet powerful) distributed event bus using actors. Swift for the Really Impatient won’t teach you any of these types of things. Again, it’s related to Horstmann’s books only by similarity in title.

The book flows very well and very quickly. I read the entire book in my spare time, spanning only a few days. At only about 140 pages, compared to The Swift Programming Language book written by Apple (~600 pages), Swift for the Really Impatient is by far the easiest and quickest book to digest if you want to gain an understanding of Swift. If you’re familiar with Scala, you’ll breeze through this book.

One thing that kept throwing me off in the book was how it really feels targeted toward developers who were previously familiar with Objective-C. This isn’t a bad thing, considering you’ll need to at least understand Objective-C to really dig into OS X and iOS development using Swift. It’s also not a prerequisite for reading and understanding this book. The reason it threw me off is because the book doesn’t really ever explicitly define the target audience as having prior Objective-C knowledge, so sections explaining that “…the syntax of Swift should look familiar to Objective-C developers…” offer very little to developers without Objective-C backgrounds. It is fair to mention that the description on the Amazon product page for the book does clearly define the target audience as experienced Objective-C developers. If you pick this book up having had no prior experience on Apple’s platform, you’ll probably see some of the Objective-C code and think “what the…?!” Good news, though! You should be able to easily glance over the Objective-C parts and still fully understand the syntax of Swift.

I would actually take the authors’ references to Objective-C and expand them a little. Much of the Swift syntax would be familiar to someone with Java, C#, Groovy, or even JavaScript experience. The only places I think some developers may have a hard time are with the sections on Optionals and pattern matching. I felt like the authors excellently explained these concepts, but I’ve experienced first-hand in Scala how Java developers have struggled with these concepts. If you find yourself struggling one these sections, take your time and maybe reread the section (be less ‘Really Impatient’).

I loved how well the authors explained closures. If you have a JavaScript background, the section on closures will make a lot of sense. A book I previously read on Swift application development using Cocoa did a comparatively terrible job explaining closures, so it was refreshing to see the subject clearly and concisely presented in Swift for the Really Impatient.

The book definitely delivers the material you need to quickly understand the capabilities and syntax of Swift. The reason I’ve given it 4 stars instead of 5 is because it doesn’t explain how to execute Swift code. There’s no mention that XCode 6 is required to build and compile Swift. XCode is mentioned only on one page, less than 20 pages from the end of the book. The section mentioned XCode explains how to bridge Swift and Objective-C code which took me a couple of tries to figure out when I attempted this while following Apple’s official documentation. I’d imagine that a truly ‘Really Impatient’ developer would get frustrated with the short explanation of the process.

Swift for the Really Impatient should absolutely be the starting point for any developer hoping to code for Apple products. It is quick, concise, and (most importantly) accurate. I may even go so far as to suggest the book to any engineers who are interested in learning the syntax of different languages.

Flattr this!

Create configurable Angular services using providers

With Angular 2 on its way, it seems like a lot of developers are now afraid of Angular 1.x. I have nothing bad to say about Angular. Sure, some things could be made easier but that’s why Angular 2 is on its way. I’ve played with Angular 2 a bit, and it only works in Chrome. I’m fairly confident Angular 1.x will be around for quite a while.

In that light, let’s talk about creating configurable services. One reason why AngularJS is so popular is because you can easily create modular, reusable code. This code can encapsulate logic, directives, extensible services and factories (via decorators), as well as configurability. I’ll talk about creating directives and decorators in future articles.

This example will be a simple URL constructor for placekitten.com. Any AngularJS service can be written to be configurable (if there’s reason to configure the service, of course).

First of all, let’s see how this service will be used.

.controller('View1Ctrl', ['$scope', 'kittyService', function ($scope, kittyService) {
    $scope.kittycat = kittyService.getUrl();
}])
  <p>How about a kitty cat?</p>
  <p><img ng-src="{{kittycat}}"/></p>

Pretty simple. We’ll call kittyService.getUrl() and use the string returned from the service as the src for an image.

To create a configurable service, we’ll use an angular provider instead of a service or factory. The structure I use for a provider is this:

(function () {
    'use strict';
    var module = angular.module('myApp.services', []);

    module.provider('serviceName', function ServiceName() {
        // use `this` for configurable properties or functions

        this.$get = [function () {
            var service = {};
            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
        }];
    });
})();

This structure is only a little different from a service or factory. Rather than return an object or constructor function, you use this.$get to create your reusable code. What you assign to this property is the array injector for your service definition. You’ll feel comfortable with this syntax if you define your services using the array-based dependency injection:

angular.module('myApp')
.service('serviceName', [function (){
            var service = {};
            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
}]);

You can use instance properties and methods on the provider definition to configure your service, then use the private context of your provider to share the configuration with the service. Here’s the full code for the kittyService:

(function () {
    'use strict';
    var module = angular.module('myApp.services', []);

    module.provider('kittyService', function KittyServiceProvider() {
        var height = 100,
            width = 100;

        this.setHeight = function (h) {
            height = h;
        };
        this.setWidth = function (w) {
            width = w;
        };

        this.$get = [function () {
            var service = {};

            service.getUrl = function () {
                return 'http://placekitten.com/g/' + width + '/' + height;
            };

            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
        }];
    });
})();

The provider has two private variables: height and width. The two methods on the provider object allow you to update these values, but only during the config phase. After your application’s config function has completed, your provider’s functions are no longer accessible.

One problem with this service is that placekitten.com shows the same image for a given combination of height and width. In the config phase of our application, the service’s height and width can be configured randomly:

.config(['kittyServiceProvider', function (kittyServiceProvider) {
    var widths = [200,300,400,500,600];
    var heights = [300,400,500,600,700];
    kittyServiceProvider.setHeight(heights[Math.floor(Math.random()*heights.length)]);
    kittyServiceProvider.setWidth(widths[Math.floor(Math.random()*widths.length)]);
}]);

The name injected into the config phase is kittyServiceProvider and not kittyService. This is important. AngularJS knows that when you request kittyServiceProvider in the config phase, you want the object containing your service definition (the KittyServiceProvider function in the example above). Once the config phase completes, the $injector service will prepare your service from the this.$get definition of your service.

If you load the example code, refresh the page a few times and you’ll receive a new kitty image.

NOTE: The heights and widths may not always combine in a way that retrieves an image. Just refresh for another example.

Why not do this in a service?

True, you could do this directly in the service if this was just your code. The benefit here is when you want to share a service with other developers, perhaps on a different project within your company or publicly on GitHub. What if your team wants a 200×300 kitty and HR wants a 500×500 kitty? In these situations you can’t just modify the code with your hard-coded values. True, in this example you could use constants or values instead but then your service would have a dependency on the consumer (this is bad).

A service that dumps a string for displaying a cat image is probably not that useful in the real world. Consider other possibilities. I’ve used providers for creating a reusable notification display which allows you to define whether a notification will automatically close and how long notifications will be displayed if they auto-close. Suppose your application often receives 40x errors when users leave their browsers unattended long enough for an authenticated session to time out; you could create a provider which caches failed requests and retries up to X (configurable) times before giving up. Or, you could create a configurable service which caches those failed requests, displays a login dialog, then automatically retries the failed requests X (configurable) milliseconds after logging in successfully. Those examples would require the use of an http interceptor, and would have been quite a bit more complex than a kitty image linker.

Code

Sample code for this blog post is available on github at jimschubert/blogs.

Further Reading

If you really want to dig into the guts of Providers (versus services, factories, constants, or values), check out Adrian Castillo’s blog post, AngularJS Providers under the hood.

For reference to each recipe, check out AngularJS Provider Recipes on the official docs.

Flattr this!

Review: Microsoft .NET – Architecting Applications for the Enterprise, 2nd Edition

I’ve recently finished reading Microsoft .NET – Architecting Applications for the Enterprise, 2nd Edition by Dino Esposito and Andrea Saltarello. This book caught my attention for two reasons. First, I really enjoy software architecture. Second, I’ve read lots of work by Dino and always found them enjoyable.

The book gives examples of a few architectural patterns like Domain Driven Design (DDD), Command Query Responsibility Segregation (CQRS), and Event Sourcing. It starts with a pretty heavy focus on DDD and seems to assume that you’ve read *The* Domain Driven Design book by Eric Evans. I’ve only skimmed through that book, but it was enough to get many of the references. This book does cover the high level definitions of DDD in a way that the reader can jump right in. The accompanying source code even provides the same example in DDD and CQRS (the two main architectures being discussed).

There were two major things I liked about this book. I really enjoyed how the book isn’t presented as ‘this is the best software architecture, so you should use it.’ Things are presented in a way that clearly states the authors’ position on each architecture. For example, DDD is discussed as a the typical go-to architecture for enterprise systems. It’s a proven pattern that ‘just works’ in many cases. The discussion of CQRS clearly identifies some weaknesses in DDD and supplies an alternative with the explicit caveat that a CQRS-based architecture will change how you think about data.

The other main point I liked about the book is how real-world the discussions are. I usually get that feeling from Microsoft Press books. Early on the authors say, “To design a system that solves a problem, you must fully understand the problem and its domain.” In one of my previous positions, one of the first things I asked when joining the team was, “How have you documented what we’re trying to build?” I received a weird non-answer from the team’s senior developer. I went to the team’s manager and asked the same thing so I could understand the requirements gathering and technical design analysis that went into the product. He said, “We don’t have any of that — we’re Agile.” I thought he was joking, but he wasn’t. Obviously it would strike a chord with me when the authors said, “Agile architecture is sometimes presented as an oxymoron, like saying that if you’re agile you don’t do any architecture analysis, you just start coding…” Elsewhere they described the businessman-developer disconnect that occurs when requirements are incomplete, which is exactly what happened on the previous team I mentioned. It’s like I always say, “If you don’t know where you’re going, how will you get there?”

Another aspect of the book that I think can get buried in reading is the point about developing for a task-based user experience. Too often do developers start coding at the database and work their ways up to the user interface. Without a clean architecture, this can lead to situations where a column in your relational database has to change all the way to the UI. That’s silly. With a good architecture that clearly identifies boundaries in code, you inherently create more reusable and more maintainable code. I think this should be everyone’s main goal while writing code.

I also thought it was cool how the book and accompanying example code demonstrate using a NoSQL database (RavenDB) for an event sourcing application. While I don’t know where I’d ever use Event Sourcing over a more common architecture (mainly because I have to account for the expertise of other developers), I really like the Event Sourcing pattern. Now that Akka.NET is gaining traction, I wonder if Event Sourcing will become the way of the future.

One minor issue I had with the companion content was that it didn’t run as-is. There was a problem with the NuGet packages and MVC5 for which I found a solution at https://naa4e.codeplex.com/workitem/1.

I would definitely recommend this book for senior developers and engineers. It provides concrete examples and guidance from experienced architects toward more solid enterprise application design.

You can download the companion code for the book at https://naa4e.codeplex.com/

Flattr this!

Tips for debugging a WiX MSI

WiX is an excellent technology that simplifies the creation of MSI files using an XML abstraction on top of the Windows Installer APIs. WiX doesn’t change the underlying MSI architecture and it can be a huge pain in the ass sometimes. I thought I would share some tips for debugging what’s going on with an MSI. These tips aren’t specific to WiX, that’s just the technology I’m familiar with.

Logging

The first thing you should try is to add the log switch when you run your installer. To do this, open a command prompt in the directory where your MSI file is located and run it with the following parameters:

msiexec yourinstaller.msi /L*v install.log

The /L*v says to log verbose messages to a file.

For a full list of msiexec switches, check out MSDN’s documentation for msiexec.

Re-cache MSI

If you think your package was somehow corrupted or you’ve made a simple such as changing a file’s guid or a feature condition, you can re-cache the package with the following command:

msiexec /fv yourinstaller.msi

This is generally used when you install a product and then thing “oops, I forgot something…”. You don’t want to create a whole new release, so you can update the installed/cached MSI.

Be careful to read the documentation. With the /f parameter, you can’t pass properties on the command line.

Increased Debug Messages

You can actually increase the amount of messages exposed to MSI logs by setting a machine policy for Windows Installer.

Open regedit and go to HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer (you may need to create this key). Add a DWORD key called Debug with a value of 7.

The value of 7 will write all common debugging messages to the log as well as command line information. If you’re passing sensitive data to the installer on the command line, be warned that this information gets dumped via the OutputDebugString function. This means that anyone with physical access to the machine or access to the machine via TCP/IP may be able to read these messages. The documentation for the policy settings warns that this setting is for debugging purposes only and may not exist in future versions of Windows Installer.

For a full list of available settings, check out Microsoft’s Windows Installer Machine Policies.

System Debugging

Passing the logging switch and log file name to an MSI every time you run an MSI can be annoying. You can set the Logging machine policy to have Windows Installer write a log to a temp file, but then you have to track down the temp file.

Instead, you can run Sysinternals’ DebugView. This utility allows you to catch debugging information exposed by the Win32 OutputDebugString function on local and remote machines. This doesn’t just gather information from MSIs. For example, you can open a TFS query editor in Visual Studio 2013 and inspect the queries made via TFS.

Orca

Lastly, the Windows SDK contains a file called Orca.msi. Orca is a tool to inspect the contents of an MSI. An MSI is essentially just a database of tables and fields with values. You can open an existing MSI, edit a condition, and save it. This can make investigation a little easier. For instance, if you’re trying to figure out why a condition on a custom action doesn’t seem to be passing, you can edit the MSI and modify the condition instead of rebuilding the MSI. It’s also helpful if you’re trying to figure out how another MSI implements some logic.

I’m sure there are plenty of other techniques for debugging MSI files.

Flattr this!

Your IDE’s font matters: Fantasque Sans Mono

A good development environment is crucial to your productivity, there’s no question about it. The phrase ‘good development environment’ is subjective. For example, I’m pretty efficient using WebStorm and VisualStudio. I use vim pretty often but I’m nowhere near ‘efficient’. Matias Niemelä, on the other hand can easily manipulate text in vim.

A year or two ago, I read a blog post somewhere that suggested a font is just as important as your tool of choice. I thought, “yeah, right!”, but downloaded the font anyway. After a day of using the font, I realized how much more quickly I could read through code and how much easier it was to visually identify code blocks. I know that sentence sounds trivial, but after two years of using what I consider a better font I definitely notice a difference when I’m not using the font.

My font of choice these days is called Fantasque Sans Mono.

Here’s a screenshot comparison of Arial and Fantasque Sans Mono, both at 14pt.

Atom: arial 14pt
Atom: arial 14pt
Atom: fantasque sans mono 14pt
Atom: fantasque sans mono 14pt

The first thing to notice is how uncluttered letters are in Fantasque. On line 17, the word ‘function’ feels like it runs together in Arial but the letters clearly stand out in Fantasque. Also notice how the letter ‘g’ is unmistakable on line 18. On line 21, the kerning between parentheses, braces, brackets, and vertical pipes all make the line of code slightly easier to read. On line 23, the zero in Arial and many other fonts often resembles the capital letter ‘O’. For literals, this is obviously a number but it can be an easy typo to overlook within a string. In Fantasque, a zero has a line through it to clearly differentiate the number from the letter. Line 25 is easily consumed in the Arial screenshot mostly because the Atom editor clearly distinguishes between patterns and operations in the regex literal. Take a look at the difference without JavaScript syntax highlighting:

Atom: arial 14pt plain text
Atom: arial 14pt plain text
Atom: fantasque sans mono 14pt
Atom: fantasque sans mono 14pt

The actual code tends to be wider than other fonts. In the Arial screenshot, the image stops at the 80 character vertical indicator, which can easily be seen in the Fantasque screenshot. I actually like to use a 12pt or 13pt font size with Fantasque, which gives me a little more code on screen.

Although these points may seem trivial, I challenge you to at least give a few different fonts a try. You’ll be as surprised as I was to find that subtle differences in your font can improve productivity.

Download Fantasque Sans Mono from OpenFontLibrary.

Flattr this!

Review: From Mathematics to Generic Programming

 

(This is a repost of my Amazon review) I’ve been out of college for a while. I did well in math classes in high school and college, but I’ve been recently feeling rusty. I wanted to read this book to combine something I love (generic programming) with something I feel is missing in my daily life (mathematics). I wasn’t at all disappointed.

The book covers a lot of interesting historical stories of advancements, discoveries, and progressions in mathematics. It starts with the cravings of the Greeks to learn and how the study of the world around them incorporated arithmetic, geometry, astrology and other teachings. The book presents many different abstractions via axioms, theories, and proofs. These are then seamlessly related to generic programming.

Although the programming pieces of the book don’t stress this enough, the examples are a guidance toward functional programming concepts. Stepanov covers monoids, groups, semigroups, rings, etc. I was surprised by the amount of ground covered in this book. He even discusses how mathematics can be applied to social networks to do something like find friends of friends of friends (graphs).

The code examples in the book are written in C++. This may be intimidating for some developers. Don’t worry, the code isn’t overly advanced. If you’ve worked with another language that has generics, traits, mixins, or macros, you should be fine. These are the level of abstractions you’ll encounter in this book. There’s an appendix to introduce the C++ concepts, if needed.

There are plenty of exercises in the book. These are actually the only the only negative thing I have to say about the book. There are no solutions, no hints, and no companion code for the book’s exercises. Maybe when the book has been around for a while, you may be able to find a github repo where someone has worked through the tasks. I was sad to see nothing like this existed.

I would highly recommend this book to anyone with an interest in mathematics and an interest in generic programming. I felt like the book was a little heavier on mathematics than generic programming. However, I also feel like most developers I’ve met don’t feel comfortable with the application of mathematics concepts.

Flattr this!

io.js 1.0.1 (unstable) is out. ES6!

A team of developers, including some core node.js developers, forked node.js a while ago into a project called io.js. They’ve just released version 1.0.1 (Unstable) and it brings ES6 natively to server-side JavaScript applications.

To test drive, you can download io.js. Be warned, it will completely replace your node and npm system links. Some people have complained about this or reported unexpected behavior after compiling io.js from source.

“Why io.js?” you ask? Joyent was a little stingy with node.js progress (it’s the basis for a huge money-maker for them). The io.js team’s goal is to make io.js more of a community-driven project. It seems to have worked, judging by the progress they’ve made.

Version 1.0.0 of io.js ships with V8 3.31.71.4, which includes ES6 features well beyond version 3.26.33 that will be shipped with joyent/node@0.12.x.

No more –harmony flag

With io.js, you can now start using some ES6 features natively (e.g. no transpiling using Traceur or 6to5). Here’s the fibonacci example using an ES6 iterator taken from 6to5’s tour:

// fib.js
var fibonacci = { };
fibonacci[Symbol.iterator] = function*() {
  var pre = 0, cur = 1;
  for (;;) {
    var temp = pre;
    pre = cur;
    cur += temp;
    yield cur;
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000) {
    break;
  }
  process.stdout.write(n + '\n');
}

You’ll notice that I’ve had to change how an iterator is constructed and how the output is written. Run this with node fib.js (remember, io.js will overwrite the system node).

While this is excellent news, you’ll need to be aware of what ES6 features are currently supported. For example, io.js does not yet support classes. This won’t work in io.js:

class Animal{
  constructor(legs) {
    switch (legs) {
      case 2:
        this.locomotion = 'bipedal';
        break;
      case 4:
        this.locomotion = 'quadrupedal';
      default:
    }
  }
  move() {
    process.stdout.writeln("I'm a %j animal!", this.locomotion);
  }
  static getTypeName() {
    return "Animal";
  }
}

class Bird extends Animal {
  constructor(){
    super(2);
  }
}

class Lion extends Animal {
  constructor(){
    super(4);
  }
}

var bird = new Bird();
bird.move();

var lion = new Lion();
lion.move();

This will, however, work via transpilers:

These examples are on github.

Flattr this!

Software Abstractions take Skill.

I recently read Adaptive Code via C# and posted a review on Amazon:

This book is a new favorite of mine. I’ve always prided myself on writing clean and concise code. I’ve always been fond of SOLID principles. I wanted to read this book to keep my understanding of SOLID principles fresh. It also covers design patterns, although be aware that it’s not an in-depth design patterns book.

The book is broken into three sections. The first section is an introduction to Scrum and SOLID. Before I had even finished the first section, I was already recommending this book to colleagues. This leading content isn’t necessarily targeted toward developers. I think many managers or team leaders could benefit from reading the basics of Scrum and understanding the terminology for SOLID programming.

I already had a pretty solid (sorry for that) understanding of SOLID principles, so I felt like the second section was more of a refresher. In that vein, I think it’d be hard for me to definitively say how easily digestible this section will be for beginners. I think it will greatly help intermediate or expert engineers to gain a new understanding of software architecture. The book’s audience is meant to be intermediate and expert engineers, but I think beginners could get the content. It’s so well written and clearly explained that I think anyone who might struggle a little with the concepts presented in the book could easily substitute any gaps in understanding with Wikipedia or blogs. Though, I honestly felt like there were no gaps. This section may be boring for non-developers, although I know project managers, program managers, and directors that would find this section interesting. The biggest thing to keep in mind is that SOLID principles are not rules; they’re guidelines.

I thought the last section was excellent. It is split into three chapters in which you’re presented with somewhat realistic dialog (‘fortnight’) that follows a small team through the first two sprints for a chat application. I’ve read a few books on Agile and Scrum methodologies and this section was probably the most fun to read on the topic. It could just be that it’s written as a script with code examples, but it was refreshing and easy to follow.

This book does a great job at explaining technical debt. While reading the book, I realized nobody at my current job has ever said the term ‘technical debt’. I asked around and found that it was a new term to most. The concept of technical debt is one thing I know I had problems understanding as a beginner. As developers become more mature, they begin to understand that the field is usually roughly equal parts business and technology. It’s really important to understand these ‘trade-offs’ and the last section demonstrates pretty well how technical debt occurs.

If you’re on the fence about purchasing this book, you should buy it. It’s a quick read and an understanding of the subject matter will improve your software. I’ve never regretted purchasing a Microsoft Press book.

I gave a short presentation at work recently about SOLID principles, so I was stoked to have a chance to read this book. One of the biggest takeaways I hope anyone has from this book is the ability to abstract software in useful ways.

I recently solved an issue using techniques such as those presented in this book. Specifically, this solution included the Open/Closed Principle, Dependency Injection, and Single Responsibility Principle as well as the Decorator pattern. The issue was simple, one I’m sure many people have encountered in their time with C#; a dataset’s DataRow does not inherent from IDataRecord in the same way something like SqlDataReader does.

Suppose you have a domain model of some kind that you need ‘mapped’ from your database into a single object.

Here’s a demonstration of the problem. I use a csv of cars from Wikipedia and instead of mapping to a domain object, I write out to the console.

First, an example using a DataReader:

using (var connection = new OdbcConnection(connectionString))
{
    connection.Open();
    using (var cmd = connection.CreateCommand())
    {
        cmd.CommandText = "select * from Cars.csv";

        using (var reader = cmd.ExecuteReader())
        while (reader.Read())
        {
            OverloadedDumpRow(reader);
        }
    }
}

Now, an example using a DataRow:

using (var connection = new OdbcConnection(connectionString))
{
    connection.Open();

    var adapter = new OdbcDataAdapter("SELECT * FROM Cars.csv", connection);

    DataSet ds = new DataSet("Temp");
    adapter.Fill(ds);

    foreach (DataRow row in ds.Tables[0].Rows)
    {
        OverloadedDumpRow(row);
    }
}

Aside from the implementation of data retrieval, OverloadedDumpRow should look exactly the same for both examples:

Console.WriteLine("A {0} {1} {2}", 
    row["Year"], row["Make"], row["Model"]);

The problem is that, since these two implementations don’t share a common base type of any sort (DataRow derives from nothing). This isn’t really an issue in a small example like this, but if you have a complex domain and you want to return data from your database and parse that data consistently. Think about what you’d have to do for each and every domain model just to parse resultsets from IDataRecord and DataRow. How do you determine whether or not you’ll even *need* both implementations? To be DRY, you’d need to pull your data from the following methods into variables or directly into your target domain object:

static void OverloadedDumpRow(IDataRecord row)
{
    Console.WriteLine("A {0} {1} {2}",
                    row["Year"], row["Make"], row["Model"]);
}

static void OverloadedDumpRow(DataRow row)
{
    Console.WriteLine("A {0} {1} {2}",
                    row["Year"], row["Make"], row["Model"]);
}

Obviously, this isn’t reusable. What we’d need is an interface. Something like this:

public interface IStringIndexed
{
  object this[string key] { get; }
}

Then, we could implement the redundant methods above in a single method:

static void DumpRow(IStringIndexed record)
{
  Console.WriteLine("A {0} {1} {2}",
    record["Year"], record["Make"], record["Model"]);
}

To get from IDataRecord and DataRow to this target interface, you’ll need an adapter. An adapter decorates a target type and exposes some new interface for that type. This can be a little confusing in our case because IDataRecord and DataRow have the same functionality (returning an object by string index), but they don’t have a consistent interface allowing us to write abstractions on top of these two types.

Our simple interface follows the single responsibility principle (implementations can only get an object by key) as well as the open/closed principle (you can now write extension methods against IStringIndexed).

Writing an adapter to use the interface from above is ridiculously easy. Here’s one of them:

internal class DataRowStringIndexedWrapper : IStringIndexed
{
    private readonly DataRow _row;

    public DataRowStringIndexedWrapper(DataRow row)
    {
        _row = row;
    }

    #region IStringIndexed Members

    object IStringIndexed.this[string key]
    {
        get { return _row[key]; }
    }

    #endregion
}

You would wrap an IDataRecord in exactly the same way.

Here are the two updated examples (notice both of these dump the record to console using the same method):

using (var connection = new OdbcConnection(connectionString))
{
    connection.Open();
    using (var cmd = connection.CreateCommand())
    {
        cmd.CommandText = "select * from Cars.csv";

        using (var reader = cmd.ExecuteReader())
        while (reader.Read())
        {
            DumpRow(new DataRecordStringIndexedWrapper(reader));
        }
    }
}

using (var connection = new OdbcConnection(connectionString))
{
    connection.Open();

    var adapter = new OdbcDataAdapter("SELECT * FROM Cars.csv", connection);

    DataSet ds = new DataSet("Temp");
    adapter.Fill(ds);

    foreach (DataRow row in ds.Tables[0].Rows)
    {
        DumpRow(new DataRowStringIndexedWrapper(row));
    }
}

This is the power of following SOLID principles and studying design patterns. This example isn’t taken from the book, but you’ll learn these skills and more in the book.

Code

A console application of this example is available on github.

You can purchase Adaptive Code via C# from informIT or Amazon.

Flattr this!

Decorating directives with isolate scope in Angular 1.3

A question from reddit excited my interest. Angular 1.3 apparently has broken the ability to decorate isolate scopes.

I tried version of Angular between the 1.2.26 known working version to the 1.3.0 broken version and found the issue was introduced in 1.3.0-rc.2.

The way to get around this is hacky:

app.config(function($provide) {
    $provide.decorator('mycustomDirective',['$delegate','$controller', function($delegate, $controller) {
        var directive = $delegate[0];
        directive.$$isolateBindings['othervar'] = {
          attrName: 'othervar',
          mode: '=',
          optional: true
        };
        
        return $delegate;  
    }]);
});   

Here’s a working example: http://plnkr.co/edit/CRxhX6?p=preview

Flattr this!

Developer James Schubert shares his code and his thoughts.