Mapper Function Using Reflection

One step forwards, one step back.  Such is the situation jumping between development shops.  Different teams evolve differently based on pain points, needs, and managerial support, and while a team may be lightyears ahead in one aspect (IE high performance asynchonous code) they can be lagging behind in other areas.

One of the things I *loved* about my last position, especially being a team lead on a relatively small team, was that I could easily get agreement and introduce new technologies.  Two of the most beneficial ones I’ve had the pleasure of implementing were Ninject and Automapper, the former being an excellent dependency injection tool to aid in unit testing, and the latter being an excellent tool to save you the pain of writing all that plumbing code between your database entities, DTOs.

Anyways, I found myself in a situation earlier where I found myself tired of writing line-by-line (believe me, after using AutoMapper you really don’t want to go back) so I came up with a little solution that uses generics and reflection:

        private void MapGlobalConfigData(T source, object dest)
            var sourceType = source.GetType();
            var destType = dest.GetType();

            var sourceProps = sourceType.GetProperties();
            var destProps = destType.GetProperties();

            var commonProps = from sp in sourceProps
                                   join dp in destProps on new { sp.Name, sp.PropertyType } equals
                                       new { dp.Name, dp.PropertyType }
                                   select new { sp, dp };

            foreach (var property in commonProps)
                property.dp.SetValue(dest, property.sp.GetValue(source, null), null);


The function itself is pretty straightforward. Using reflection, it looks for properties with common names and data types between your source and destination object, and pushes a reference to the corresponding properties in a collection.

I’m still battle-testing it, but thus far it looks like a quick and simple alternative to AutoMapper, as long as you’re *verY* careful about how you’re using it.

Why not use AutoMapper? It’s a hard sell to the architecture team 🙂 This is a great interim solution.

New Gig!

Big news!  I’ve got a new gig. I’m now a senior software developer with a cloud company.  What does this mean for this blog?  People development and personal/professional growth of software developers is still one of my passions and something I hope to get back to in the future, but for the time being I’ll be shifting gears away from that a little bit and continue to to talk about more conceptual-type problems and opinion pieces.
I’m also starting a new little pet project involving mo-cap, and I’ll try to chronicle that between here, my Twitter, and perhaps even my Twitch account!  Stay tuned!

SEWP – Is the Single Responsibility Principle applicable to functions?

As it turns out, I don’t peruse the Programmers StackExchange quite as much as I initially thought.  However, after much ado, I’ve finally decided to target a post for my second StackExchange Writing Prompt. Here’s a relatively simple question in my eyes that shows how a simple problem could have multiple solutions.

I won’t directly quote the initial post, but I will point you to the link here:

What we’re looking at is a CalculatePay() method that uses a switch statement to call another method depending on the employee type. The question here is how exactly this breaks the Single Responsibility Principle. It’s believed that a clear violation of the SRP is that there is more than one need for this method to change.
While I don’t intend to go too deeply into why this is incorrect and would rather talk about ambiguity in creating a better solution, I’d first like to talk a little bit about its incorrectness and violation of the SRP.  First off, this method acts as a routing mechanism for all unique types of payable employees.  Every time you need a new employee type (let’s say a contractor) we would need to write a new pay method and modify the CalculatePay() method to .  Furthermore, if our enum changes, we now have to come back and modify this method.

Writing code like this is a surprisingly common pitfall for the junior developer. I myself am guilty in the past of using switch() statements against enums to perform logic.  In a bind it is a quick and dirty method to handle that type of polymorphic logic and lends itself perfectly to the competent new developer who has mastered flow control.  It’s a prime example of code that works correctly but does not scale well.

So this of course begs the question: how could we design this better?  Is there a clear-cut way to make this objectively superior?  Is there only one true way to accomplish this? We don’t have enough information here to make a truly informed decision, but we can at least take a first stab at it.  Let’s rewind for a second and look at how we’re defining employees:

    public Money calculatePay(Employee e) throws InvalidEmployeeType {
        switch (e.type) {
            case COMMISSIONED:
                return calculateCommissionedPay(e);
            case HOURLY:
                return calculateHourlyPay(e);
            case SALARIED:
                return calculateSalariedPay(e);
                throw new InvalidEmployeeType(e.type);

Of course we have very little to work with which makes things complicated, but just looking at this implementation I can already think of six questions to ask that may lead you to an optimal solution?

  1. Are there any classes in the system that inherit from Employee?
  2. Does the Employee class expose the CalculatePay() method?
  3. Where are the other CalculatePay() methods held?
  4. Is there one predominant (AKA default) payment method?
  5. Are there employees who don’t get paid (IE unpaid interns)?
  6. Could two employees of the same type have different payment methods?
  7. (Bonus) Could there be a situation where an employee has multiple pay methods (IE salaried and commissioned)

Let’s knock the easy one out of the way first.  If you have two employees of the same type who can be paid differently, I would question your underlying decision-making in what warrants a derived classes vs what warrants a type property. For example, if you were breaking your employees down by Manager vs Analyst but you had Analysts who could be salaried or hourly, you might want to consider using a type parameter as there is no significant change in the way they’re processed by your software system based on those derived classes.

If you’re in a situation where you want a default implementation, it might make sense to have a Employee base class containing a CalculatePay() method with a default implementation that others could then override.  Alternatively, you could provide an abstract/virtual method with no implementation that the derived classes would then be forced to implement.


Assume for a moment that not all employees get paid in our unpaid intern situation.  Should the Employee class even house a CalculatePay() method?  Perhaps it may make more sense to have payable employees to implement an IPayable interface for which they could provide their own payable implementation.  This then of course begs the question as to how your employees are stored in the database, especially given that each payment type would likely need access to different data fields.  I’m on the fence about this type of implementation in practice.


How about a scenario where employees can have multiple payment methods?  If we only had one such case (IE someone who is salaried with commission) I might be tempted to create an indirect subclass of employee that inherits from one of Employee’s subclasses.  If, however, we started running into multiple combinations of these (IE hourly and revenue sharing, salaried and revenue sharing, salaried and commissioned with revenue sharing) you might lean more towards something else entirely like the Decorator pattern, which would allow you to incrementally apply that logic:


Coming back to the point I intended to derive out of this question, we have now seen multiple potential implementations to solve a problem that appears quite simple on the surface but can encapsulate many complexities.  To say that one answer is right would be incorrect because we have multiple things to consider. I’m all for the principle of YAGNI, but at some level a business-aligned development team should be able to reasonably predict what potential cases may come down in the future.  Implementing something like a Decorator pattern to resolve item 7 would certainly be overkill in a situation that didn’t actively require it, however having the foresight to know that unpaid interns could very well be part of the system and having the foresight to choose the appropriate design up-front can save plenty of hours of re-work and reduce long-term complexity.

Changes to the ASP.NET Ecosystem

For any of my fellow developers on the Microsoft technology stack, you’ve probably heard about the big changes coming to the .NET ecosystem.  The .NET framework itself is going through a big revitalization project, and one of its biggest frameworks is certainly not immune to some much-needed change.

I’ll skip over listing and detailing some of the bigger changes, which have been very succinctly described by others (see for a great rundown) and instead talk about the impact this is going to have — at least from my team’s perspective — as a means of providing insight into some of the challenges and changes that this will bring.

Be Prepared for a Mentality Change

Let’s stray from ASP.NET and even .NET itself for a second and talk about the “new” Microsoft.  In many ways Microsoft, for better or worse, has retained its reputation and the monopolistic company seeking to “embrace, extend, and extinguish” in every market they enter.  In my eyes, that Microsoft is dead. Under the new leadership of Satya Nadella the organization is taking massive strides to be a company that works with the technology ecosystem rather than trying to dominate the technology ecosystem.

This has permeated throughout the organization.  We’ve seen it trickle down to the .NET world.  Did you ever think you’d see a Microsoft product on GitHub?  Several key .NET projects have been open-sourced.  The new compiler platform, ASP.NET 5, EntityFramework are all open source.  With NuGet acting as a package manager it’s now easier than ever to use 3rd party libraries in our code.  The mentality of a .NET developer is no longer to simply “do it the Microsoft way”.  We have to be ready to embrace and accept 3rd party frameworks across our entire codebase, from projects like Ninject and Automapper to AngularJS and Grunt.  Sure, Microsoft may still be offering their own solutions in the same problem domain that these frameworks cover, but more and more we’re seeing them not only make those projects available but actually endorse them.

It’s a new world for Microsoft developers (albeit one that’s existed in the open-source community for eons by technology standards) and we’re going to have to be ready to adapt!

Say Farewell to Visual Basic (with ASP.NET)

Scary times huh?  Out of the box, ASP.NET 5 will not support Visual Basic, thought they have promised CLR support for other languages in the future. Personally I think this is long overdue as .NET itself has several non-CLS compliant structures and features simply because at the time of writing the language didn’t support things C# did (a great example being unsigned types).  To Microsoft’s credit, VB.NET was a great idea at the time to help enterprise Visual Basic programmers transition, but the ASP.NET world has trended towards C#, seen far more maturity in that language, and now it’s time to change.  I still feel like C# is the best language available in its domain today.

Edit:  It’s worth nothing that VB.NET is still very much alive and well.  Take a look at VB14:

Goodbye WebForms; Long Live MVC

Speaking of transitional technologies, it’s time we said goodbye to Web Forms too.  Web Forms is not part of ASP.NET 5, however support will still be provided by targeting .NET framework 4.6 or lower.  You’d be hard-pressed to sell any developer on WebForms over MVC (with the exception of some edge cases) in this day and age, but now it seems like Web Forms is seeing a much needed retirement.  Though I was never a fan of the technology myself, it did  serve its purpose of giving old WinForms developers a way of building applications for the web while hiding them from the scary stateless world they now lived under, but the ecosystem has changed dramatically and unless you’re building an LOB CRUD app with ZERO regard for user experience or future growth, you’re likely best off with MVC.

Will Web Forms apps disappear entirely?  I highly doubt it.  15 years from now you’ll still see Web Forms apps in the wild, much in the way that you still see Classic ASP in the wild today.  However, if you’re managing an application that’s going to require future enhancement and growth, you’ll definitely want to consider a WebForms to MVC re-write, much in the way that you have (hopefully) done with your Silverlight apps!

One Love – MVC and WebAPI

Perhaps one noteworthy point not to overlook is the fact that ASP.NET MVC and WebAPI are being unified.  In previous versions of .NET your MVC and WebAPI controllers were different.  They now all inherit from a universal class.  While small, I think this is a big change that embraces the fact that more and more controllers in our applications are acting as web services returning JSON results for client side frameworks.  This, of course, brings me to my last point:

Client Side MV* is Here

AngularJS, Backbone.js, Ember.js… so many of these new client-side MV* frameworks have popped up lately.  While they do add some complexity and learning curve for developers, they do a fantastic job of simplifying front-end development.  We now have templating, patterns, two-way databinding, and can now finally express front-end code in terms of our problem domain the same way we’ve done on the server-side.  More and more it seems like our ASP.NET controllers are simply feeding JSON results to our front-end frameworks for processing.

I don’t think this is inherently a bad thing.  In fact, AngularJS seems like a very cozy new home for WebForms developers who may feel like they’ve been left out in the cold as part of the new changes.  However, it’s a new trend in the industry and certainly a new set of technologies and ideas we have to deal with.

The Future is Bright

Fragmentation issues aside, I believe that the future is very bright for us ASP.NET developers.  Microsoft is accepting the lay of the land and embracing the open nature of web development for what it is.  They’re making substantial changes to their technologies — perhaps the largest they’ve made since the inception of .NET itself — but it’s all in the interest of building a brighter tomorrow.  Many legacy features and technologies are being left by the wayside, but it is all in the interest of long-term gain and progress.  I can’t fret with a single change they’ve made, and quite frankly I can only hope that you’re as excited as I am to enter this brave new world.

For those who haven’t yet, I strongly implore you to dive deeper.  I’ve glanced over several big changes at best and skipped others outright (did you know that .NET is going cross-platform?).  Trust me when I say that it’ll be worth the read.

SEWP: “What are the key points of Code Complete”, or The Hidden Message in Code Complete

Our inaugural StackExchange Writing Prompt stems from a topic close to my heart as a developer:

I have heard a lot of people mention Code Complete as a book worthwhile reading. Unfortunately, I am so busy that I don’t have time to read it, so can anyone tell me what the key points of the book are?

In all honesty it’s not a bad question to ask.  In my eyes  Code Complete is one of the quintessential books for an intermediate developer to read in order to move forward as a senior developer.  Much of its advice is very practical and deals with topics we encounter on a daily basis as programmers, ranging from how to write clean, maintainable, and readable code to topics like refactoring, continual testing and improvement, and my personal favourite topic, software craftsmanship.  Based on my own experience with the book, I feel that any intermediate dev. reading the book will discover that they’ve been doing a lot of things right, and a lot of things wrong.  What it really helped reinforce for me was how much the right attitude and work ethic play into becoming a better developer.  However, if you read between the lines (hey-oh!) you’ll find the real hidden point of Code Complete nested underneath.

The issue lies in the frame of mind that this type of post indicates.  Upon reading a question like this one can assume that the poster wants a Cole’s Notes version of the 800+ page book, distilled down into a single page for painless consumption because the poster can’t be bothered to read the book.  Now I’m not one to judge — we all need a life outside of work and if the time isn’t there for one reason or another then there’s not much you can do.  Really what this book encompasses are two overarching topics:

  1. Quality Coding Habits/Practices
  2.  Correct Developer Attitudes

The accepted answer does a fantastic job of at least covering off habits and practices, such as showing sound judgement, committing to iterative development, and others at a high level.  You’ll miss the lower-level specific advice (IE passing booleans to parameters) but after all, this is a condensed response.
However, what the poster calls out to some extent and what I’d like to elaborate on is Chapter 33: Personal Character.  This chapter rather vehemently discusses the mentality of a good developer.  This really talks about the pursuit of self-improvement as it pertains to development and how to get there.  The principles themselves I won’t get into, but this does raise a question that I would love to ask to anyone who seeks to read a summary of Code Complete without actually reading the book:

By refusing to read a book by an author whose key message includes having the diligence and discipline to actively seek self-improvement, haven’t you missed the point of the book entirely?

The fact that you’re even asking the question is a great start, but you’ve missed the message behind the chapter on Personal Character, which in no uncertain terms reinforces the point of having that level of discipline and curiosity to make the time to learn and improve.

Thus, what is the key point behind Code Complete?  The key point behind Code Complete is that you should read Code Complete. 

StackExchange Writing Prompts

While taking a break during a slow Friday morning an obtrusive thought entered my head — I have a development blog!  Clearly I’ve been doing a less-than-stellar job keeping pace with posting my updates. Between my normal work, my hobbyist projects, my other non-development hobbies, and life in general, I’ve just been too busy to sit down, think up, and actually write a coherent and useful blog post.

With that in mind, I’ve decided to err on the side of laziness and let others generate ideas for me!  Introducing a new (and hopefully regular) feature, Stack Exchange Writing Prompts.  Seeing as how I spent a fair chunk of my research and learning time on the Programmers StackExchange, I figured I could use fascinating questions there as writing prompts, perhaps providing insights and perspectives either not suited to answering the original question directly, or simply not in accordance with that particular StackExchange’s posting guidelines.

In any case, I hope this is an interesting foray into more regular updates.  Stay posted.

DO Judge a Book By Its Cover (Letter)

As a team lead, one of the most interesting new avenues I’ve been able to explore is the hiring process.  I’ll start off by saying this:  interviewing is infinitely easier than actually hiring a good candidate.  There’s a lot to think about when you’re bringing a new person on and challenges are plentiful.

At a 10 000 ft level the process itself is fairly straightforward. The hiring manager puts up a job posting, the candidates apply, and the hiring manager picks the person who is objectively the best.  On paper it seems so simple.  As a software development interviewee you just have to be the best candidate and you’re in, right?  Well, partially.

The trickiest part of the process for both the hiring party and the potential candidate is the initial screening.  All you really have to judge each candidate by is a laundry list of skills and experiences packed into a resume and a covering letter.  Many candidates know that medium-large sized companies use keyword-based searches to screen out resumes.  The best way to get yourself past the pre-screening process is to pack your resume full of buzzwords so that it’s not thrown out before it’s even read.  It always makes you wonder how many potentially great candidates may have been given the boot before

Sadly, the aforementioned means that many software developer’s resumes quickly become dense, exaggerated, and at times unreadable.  I’d say that on average, and based soley on my own experience, that about 30% of a candidates resume will be TLAs (three-letter acronyms) and buzzwords.  Synergy this, efficiency that, Agile over here, paradigm shift over there.  Once you strip it all away you’re left with what’s effectively a timeline of your work history and a brief glance into what you’ve done in the past.

As a candidate, how do you set yourself apart from the rest, especially if your timeline is shorter or less diverse than others?  As an interviewer, how do you evaluate a person based on two sheets of paper?

The answer is the cover letter.  A quality covering letter is your ticket to the big leagues.  It tells a story not only about your work history, but also about YOU!    It speaks volumes about your writing skills and your communication style.  In fact, it’s quite easy to pick up on tidbits of a person’s personality just from the covering letter.  Did they over-sell themselves as a rockstar developer from out of this world?  Did they under-sell themselves or under-value something that an objective observer might consider an important tidbit?  The most important thing to note is that it puts YOU in control of the story.  It gives you a chance to portray yourself however you wish.

When I’m evaluating a candidate I will look at both equally.  Generally my pre-interview rankings can be hit or miss based on resumes, but the quality of the cover letter tends to correlate much more tightly with non-technical interview performance.

Of course, that’s not to say that great covering letter guarantees that you’ll be hired.  Ultimately the interview is the largest determining factor in whether or not you get the job.  In addition to technical acumen, the process attempts to evaluate your attitude, communication skill, your ability to co-operate with the personalities on the existing team, and where this position may fit into your overall career goals.  One thing candidates may not always consider is that the interviewer has to evaluate his or her OWN team every time a candidate is hired to ensure that an incoming candidate can balance out any skill gaps that exist.  It’s very possible to be an outstanding candidate but still be the wrong candidate for the job.

That discussion is for another day, though.  Landing an interview is very challenging and, as a candidate, is a process largely out of your control.  However, with keyword-friendly resume, a strong development timeline, and a great story to tell in a covering letter, you’ll be well on your way to getting a chance to show your skills in person.

How to Learn How to Program

Here’s a common question I see all the time when scouring my favourite forums: “how can I learn to program?”

20 to 30-odd years ago the answer was “go to school” or “buy a textbook + software and try it out”.  The development ecosystem has obviously changed then.  Developing software has permeated across various industries and the practice as a whole has become very easy to get into.  Almost everybody has access to a computer with the Internet.  Almost everybody can download piles upon piles of free software to use to get started and numerous guides.  With web and mobile applications being exceedingly popular, the tools to get started right at your fingertips, and the news of lucrative salaries and an ever-increasing shortage of quality developers, the idea of becoming a self-taught developer is very tantalizing.  The only real investment required now is your time.

With that being said, there are many resources out there that range from less-than-deal to just plain bad.  Software development bootcamps are terrible.  Sites like Codecademy and W3Schools, while helpful for learning syntax, don’t really teach you how to program.  Instructor-led courses ultimately leave you at the mercy of the course syllabus and the quality of the instructor.

I still believe that a very talented developer can be self-taught provided that they don’t circumvent the process.  Some people just want to learn how to make websites, so they’ll learn some basic HTML markup, some CSS, jQuery without ever actually learning Javascript, and probably use WordPress as their base to minimize the amount of PHP they really need.  I don’t think there’s anything wrong with that.  I think it’s a great gateway.  However, until you go back and fill in the gaps you’ll know how to build web software, but you won’t really know how to program.  This is a classic case of putting the cart before the horse and I see too many developers fall into this trap only to have it backfire on them when they start running into difficult problems.

Perhaps one of the most important things you can do for yourself is to nail down your fundamental programming skills before you focus on building software.

Here’s my list of fundamental skills a “novice” developer needs before (s)he can start building things:

  1. First Language Syntax
  2. Variables and Functions
  3. I/O
  4. Flow Control
  5. Looping
  6. Recursion
  7. Data Structures/Algorithms
  8. Persistence
  9. (Optional) Object Oriented Programming

With these basic tenants down a programmer can theoretically build anything from scratch.  Assume you were developing in a world with NO frameworks, NO libraries, NO protocols, and NO markup languages or stylesheets.  This is everything you would need to get off the ground.  As they say, “to create an apple pie from scratch, you must first invent the universe”. Once you’ve got these fundamentals down, you can go invent the universe… if you want.

If you’re a sane person, you’ll look into things like frameworks, protocols, libraries, and whatever else you need.  If you want to move over to the web, you’re going to need HTML, CSS, Javascript, and likely a server-side language in addition to knowledge of HTTP.  That’s a protocol, a markup language, a stylesheet language, and two new languages (client side Javascript and server side whatever), most of which will require you to apply the same nine concepts above. Suppose you want to build a mobile app.  Chances are you may or may not be learning a new language for the app, and on top of that you’re learning whatever framework the provider offers.  You’ll be using that framework in conjunction with the nine tenants above to build whatever you need.  Want to build a videogame?  Chances are you’re learning a whole bunch of APIs and likely writing in C++, but you’re still applying the same nine tenants above.


Where you go and what you learn next depends largely on the avenue you venture into.  If you’re a freelance web developer building small websites/applications for your clients, you’re going to be entrenched in the client side and spend a lot of time working with service APIs.  If you’re an enterprise web or application developer you’re likely dealing with large databases and large amounts of data.  As you mature you’re going to start learning some less trivial tenants:

  • Optimization
  • Caching
  • Design Patterns
  • Asynchronous programming
  • Multithreading
  • Software Architecture and Design
  • Security
  • Debugging
  • Refactoring

The list goes on and on and on.  To elevate yourself to an intermediate and senior developer, you’re going to have to nail these down too.  For now though, let’s get back on track.

The next question that always comes up is “what language should I learn first?”.  The language you learn isn’t as important as the concepts you learn.  With that being said, there are several good “learner” language options out there, many of which are driven by a particular language’s popularity.  It does make sense — if you want to be an *x* developer, learn the fundamentals in *x* and you’ll be productive much faster because you won’t have to learn another language.

Every starter language is going to have its pros and its cons.  I still like C as a good first-timer language to learn at least your first seven tenants because it teaches you a bit about the nitty-gritty underlying concepts that will help you later on.  If your first language is something like Java or Python you would never know that strings are tricky.  You might learn that strings are immutable but never really understand the significance of that.  You might learn that a variable stores data in memory but you won’t get hands-on experience using pointers/references and working with memory addresses, nor would you understand the significance of the fact that Java passes references to objects by value. You might know that there’s a garbage collector running to free memory, but you won’t understand the beauty (and difficulty) of it until you’ve had to use malloc() yourself.
C does have two problems.  It’s not object-oriented so you’ll never learn those concepts, and it’s rather uncommon to have a C application that connects to a database for persistence.  When you reach this stage in the game, I would move on from C.  Python is a great utility language to learn.  It does a lot of things very well and it’s used across a wide range of programming applications.  Java is a pretty solid language to learn as well thanks to sheer popularity, very good libraries, and near-strict enforcement of OO.  You can, of course, use those languages from the start and skip C altogether, as any thumbs-up I give to C as a learner language is just a result of my own experience.

Once that’s all said and done, you can pat yourself on the back.  Chances are you’ve experienced first hand the joys of getting your first “Hello <name from input>” program running and the sheer frustration of a segfault (had you gone the C route) or at least the trouble of hitting a large bug.  You know how to control the flow of your application, how to delegate repeatable pieces of code to functions, how to iterate across loops, how to recursively solve problems, how to read/write data from a variety of sources (incl. flat files, databases, console), and how to structure code in a logical manner.  You have a taste of what development is all about and you have the skills to build everything.  NOW you can go ahead and pick the stream you want to pursue, be it web, mobile, server side, client side, embedded, game development, or any other stream of programming, and start learning how to build real software of whatever type you choose!