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.

Advertisements

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:

http://programmers.stackexchange.com/questions/275646/is-the-single-responsibility-principle-applicable-to-functions

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);
            default:
                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.

virtual

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.

interface

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:

indirect

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 http://stephenwalther.com/archive/2015/02/24/top-10-changes-in-asp-net-5-and-mvc-6 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: http://blogs.msdn.com/b/vbteam/archive/2014/12/09/new-language-features-in-visual-basic-14.aspx

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?

http://programmers.stackexchange.com/questions/2777/what-are-the-key-points-of-code-complete

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.