Category Archives: Whatever

Good riddance – if-statements

TL;DR; A lot of your if-statements are unnecessary and makes you violate the open/closed principle (open for extension, closed for modification) among other things. Make sure to identify those and get rid of them a soon as possible. They are the ones which checks a type or parameter and then decide what to do in that case.

Open/closed principle

The O in SOLID principles. What it actually means is that a method and in extension, a class, should not be open for modification but only extension. The exception being if the rules actually have changed. Following this principle makes you and your fellow coders avoid changing the behavior by accident.

You could regard this as an extension of SRP (Single Responsibility Principle), where a specific piece of code have one and only one purpose. And the open/closed principle forces you even further in that direction, aswell as making your code DRY and encourages reuse and readability.

An ugly example

While it is easy to think of this for green field projects, it is probably even more useful in brownfield applications in the progressive work of cleaning up and make heads and tails of things. A not uncommon scenario is some kind of Init() method which takes care of some in data validation and checks for a type or enum to then decide what to do.

public class MyInitClass
{
  public void Init (string accomodationType) {
    //do some stuff
  
    switch (accomodationType) {
      case "apartment":
        //do stuff
        CalculateApartmentFare();
        //do stuff
        break;
      case "house":
        //do stuff
        CalculateHouseFare();
        //do stuff
        break;
      case "room":
        //do stuff
        CalculateRoomFare();
        //do stuff
        break;
      default: throw new ArgumentOutOfRangeException("Invalid type provided.");
    }
  
    //do even more stuff
  }
}


It looks innocent and perhaps not that intimidating. But what if the contents weren’t in methods? Even worse, there might be twenty accomodation types. And you can count on that there will be more in the future. You will have to make modifications to this piece of code each time, which might be cumbersome depending on what it looks like aswell as adding a bit of risk of not changing anything else. Who knows what might be hidden underneith or inbetween? There is also the impending doom of this if-statement being copied all over and not knowing all places to change.

The remedy

Don’t fear, there is something fairly easy you could do in several steps. One small baby step at a time. If the contents aren’t in methods. Do that first, make sure to stream line it so they behave as expected for each type and does only one thing.
After that perhaps you could break out the entire switch-statement into a method of it’s own. Is it copied else-where? Put the brand new method in a class and point all of the others to that class as well.
Still not satisfied, but coming closer. Even though it is now isolated in a class of its own, there is this ugly switch-statement. Not a fun thing to update each time and it is bound to the fare calculations of all the accomodation types. Break away the calculations to new classes for each accomodation type. Since all of the methods being called are of the type Calculate(), make them implement and interface with that single method on it.

Now it’s time to get rid of the pesky switch-statement, the foundation is there. Put the type-names in a dictionary with their corresponding calculation class as the value. Since they inherit the same FareCaluculator interface you can call Calculate() on all of them! It is more loosely coupled and you can safely add new ones without fear of disturbing others.

public class MyInitClass
{
  private readonly AccomodationCalculationConditioner _accomodationCalculationConditioner;

  public MyInitClass()
  {
    _accomodationCalculationConditioner = new AccomodationCalculationConditioner();
  }

  public void Init(string accomodationType)
  {
    var calculator = _accomodationCalculationConditioner.GetCalculationConditionForType(accomodationType);
    var fare = calculator.Calculate();
    //do more stuff
  }
}

public class AccomodationCalculationConditioner
{
  private readonly Dictionary _conditions;

  public AccomodationCalculationConditioner()
  {
    _conditions = new Dictionary
    {
      {"apartment", new ApartmentCalculator()},
      {"house", new HouseCalculator()},
      {"room", new RoomCalculator()}
    };
  }

  public IAccomodationsFareConditions GetCalculationConditionForType(string accomodationType)
  {
    if (_conditions.ContainsKey(accomodationType))
    {
      return _conditions[accomodationType];
    }
    throw new ArgumentOutOfRangeException("accomodationType", "Invalid accomodation type provided");
  }
}

public class RoomCalculator : IAccomodationsFareCalculation
{
	public double Calculate()
	{
		throw new System.NotImplementedException();
	}
}

public class HouseCalculator : IAccomodationsFareCalculation
{
	public double Calculate()
	{
		throw new System.NotImplementedException();
	}
}

public class ApartmentCalculator : IAccomodationsFareCalculation
{
	public double Calculate()
	{
		throw new System.NotImplementedException();
	}
}

public interface IAccomodationsFareCalculation
{
  double Calculate();
}

Now that wasn’t so hard was it? And even more, almost all of the SOLID principles are in there or are at least possible to apply if the need arises. But these are just bonuses, what it all boils down to and is the important point here, is if you consider the understandability of the Init() method. Is it hard to read? Is it hard to understand? Can you figure out what it does fairly easily? How about testability? And, would it be hard to change something in there? Would you consider it riskful to change something and not knowing what else might get affected? This is called orthogonality, that is something good.

Wrap up

Now, this is not _the_ way, it is only _a_ way. Which other ways do you know of? How do you approach dragons and other beasts out there luring in the code jungle? Hit me up on twitter to let me know!

Further reading

Tagged ,

Rage vs inertia

To me, they are two completely different things. The first is the act of passion, and what drives you is the motivation of making things more wonderful. The latter is where you just accept the things around you, in essence you’ve given up.

Google defines them as following.
Rage, a vehement desire or passion.
“a rage for absolute honesty informs much western art”
synonyms: craze, passion, fashion, taste, desire, craving, appetite, trend, vogue, fad, enthusiasm, love, obsession, compulsion, weakness, fondness, fixation, fetish, mania, fascination, preoccupation.

Inertia, a tendency to do nothing or to remain unchanged.
“the bureaucratic inertia of the various tiers of government”
synonyms: inactivity, inaction, inactiveness, inertness, passivity, apathy, accidie, malaise, stagnation, dullness, enervation, sluggishness, lethargy, languor, languidness, listlessness, torpor, torpidity, idleness, indolence, laziness, sloth, slothfulness;

Both passion and inertia are contagious. While one is awesome to have and spiral upwards, the other spirals downward and needs to be broken ASAP. There is always a way. Pave the way. Or, a bit harsch but as Dan North once put it; Change organization or change organization. Not everyone wants to change, or your paths are completely different.

If you are in a state of inertia, you really really need to do something about it. Although, being in the middle of it and it might (probably) have been a downward spiral, you might not even know about it. But if you think actively, are you passionate? Do you have that driving force and hunger? Do you do your utmost to make things more wonderful? Both for yourself and those around you.

Tagged

.gitignore

I don’t think it matters, any tool you use will create a bunch of support files for whatever reason it has. Settings, tracking, state… There is always something. Especially if working with Visual Studio and Git-TF or Git-TFS, make sure your .gitignore file is in order. Realizing what that means, you probably do not want to write your own, so there is one created for almost all environments.

.gitignore on GitHub saves your life.

Update: I got a tips on an additional gitignore resource called GitIgnore.io which generates .gitignore files according to your spec. Perhaps you need to include both Windows and OS X and several editors? This is the tool for you! Thanks @sodper.

Tagged ,

Alert general!

At work we recently started decoupling our services a bit more than previously. It is an older system which has been around a few years and haven’t got much love. We quite quickly identified that work being done was done on the same thread as the request, in sync, so the user had to wait for all work to complete until they were released into freedom again.

Grabbing the beast by the horns my colleague started looking into and learning NServiceBus which we already use at the office for other systems. This way we could decouple the workload off of IIS and letting the user continue to work, instead of waiting half an hour for the import to finish, or a spritemap to completely regenerate. But, on the other hand the user didn’t get any response as when the job finished, or if it did finish.

Now what…? Signal it! RRRR!

This signaling/notification system can quite easily and nicely be achieved with todays techniques. Since we are more or less bound to Microsoft platform, we went for SignalR to solve it.

Now, out of the box SignalR don’t scale very well. But they do have a nice scale out technology which scales out via a backplane that might consist of almost any technology you choose. They ship support for SqlServer, Azure Servicebus and Redis. We have SqlServer in place so the choice was already made. This way any message sent via SignalR will be sent to the backplane, via which all other clients on other machines listens to and publishes messages to its users.

So with this in place we could handle our environment of loadbalancing and fail over. The last piece is the worker service described at the top, which will want to send an update when it finished or if it failed. This is achieved by adding it as another client to the equation.

To the code!

This example uses the canonical SignalR chat example. There are two web apps which could run on separate machines, and a console app which acts as the worker service and connects to one of the web apps as a client.

There is actually extremely little code involved to achieve this. What you do is this:

  1. Add both the SignalR and SignalR SqlServer backplane packages to your web apps from NuGet.
  2. Set up the backplane like so in the Startup class for each web app:
            public class Startup
            {
                    public void Configuration(IAppBuilder app)
                    {
                            GlobalHost.DependencyResolver.UseSqlServer(ConnectionStringProvider.SignalRPubSub());
                            app.MapSignalR();
                    }
            }
    

    Notice that the backplane itself will set up all required tables and stuff, so all you need to do is provide a connectionstring and a database.

  3. Make sure to add the SignalR Client package to the worker service, the one that will “call in” with additional messages.
  4. Then, calling in is simply as easy as just connecting to one the web apps, doesn’t matter which one, create a local hub proxy with the same name as the one you want to communicate with, and upon message sending – call the server side method of the hub.
            class Program
            {
                    static void Main(string[] args)
                    {
                            const string name = "Console";
                            var conn = new HubConnection("http://localhost:55566/");
                            var proxy = conn.CreateHubProxy("chatter");
    
                            conn.Start().Wait();
                            proxy.Invoke("Notify", "Console", conn.ConnectionId);
    
                            string message;
                            while ((message = Console.ReadLine()) != null)
                            {
                                    proxy.Invoke("Send", name, message).Wait();
                            }
                    }
            }

  5. Then… done!

The entire working code is available on GitHub for your pleasure. There is however some irrelevant code commited which fetches history. It’s not done in this example but it doesn’t affect the demo, so I just left it there. Might fix it in the future. What is left is to read the data back from a byte array in correct order.

Further reading

Tagged , ,

Do not miss this! #imtellingyou

Just a quick update, since there is something you do not want to miss this week. Marcus Hammarberg is doing a series this week on what he has been up to for the last decade(?) or so, before retiring the material in current form. Brilliant guy and it is all free, so if you have the time – make sure you go to at least one of the sessions.

Read more on his blog about “I’m telling you for the last time“.

A new traveler

Also, there is a new globetrotter. A guy from UK is adventuring Corey Haines style around the globe to see places, meet people and code to learn and master his profession. Follow him and check it out. Or even, could you help him help you? Check out Andy Waites blog for more info. At the moment he is poking around North America.

Tagged , ,

Pondering, my thoughts on drafts. Or really – Think!

I love to ponder stuff. Just walk around in my own little bubble and think about things. Annoyances, happiness, problems to solve, how to approach things, and just stuff like that. A lot of soft subjects.

At the moment I have at least five drafts unpublished which will probably never make it out the door to the open world on these topics. They are named things like “Procrastination and me and you”, “Thinking processes part 1: what and why”, or “What is wonderful? [insert unicorn]“.

Drafts

The first one being about how we procrastinate in different situations and what kind of work we have (or do not have) at hand. A lot circuling around focus and how we do it and get things done.

The second one, being the first in a series where there is also one about “conflict clouds” and another on “logical trees”, is more about how we can structure our thinking and come to better decisions. Perhaps not always try to combine two different ideas to satisfy all needs to a certain extent, it might be better to surface the underlying assumptions and see how they point toward the common goal. Or logically try to find out where we are, where we want to be, and how to transition from where we are to the new happy place. Among these things were also the bold claim I made on twitter about being able to prove that scrum is wrong, depending on your situation. Still believe in my idea, but perhaps a bit more nuanced now a couple of weeks later.

And the last one, about what makes things wonderful. This one I started thinking more about, in terms of wonderful, after my encounter with Woody Zuill. A wonderful person which I would just love to have had more time to spend with and talk about these kind of life events and stories. His warmth, passion and humbleness really shows that if we approach things in certain ways, things can be truly wonderful. To find out, we need to think about what makes wonderful for us and make sure we create that kind of environment all around us.

Not having finished any of these and probably never will have bummed me a bit. Why can’t I finish them? Why don’t I get them published? There is so much goodness in them!

Think!

But then it just hit me – to me they are important to just get as drafts, because that makes me Think about these topics. Thinking about them makes me consider my environment which in turn makes it possible to improve. IBM had an old company value, which I actually remember, that was simply “Think!”.

If we conciously thinks about what we do, what we have, and why we do things in a certain way in order to improve. Imagine what we can achieve and where we can be when we are 60.

So this is a shout out to me and you alike. Don’t be bummed about all the drafts just lying there; they are one of your tools to think more precisely about how to improve. If more get to share the thoughts, that’s even more awesome, but consider that a bonus.

Further reading

PS. If you are in my vicinities these are all available for borrowing :>

Tagged ,

Asus bloatware guide

For some reason I had to borrow my wifes computer the other day. I was just stunned at how slow it was and took a peep what programs might be installed. It’s a fairly standard Asus, preinstalled and been around for a couple of years but not used that much.

Anyway, she is not the type that installs a program, so I was blown away by the amount of crap that was in there. I didn’t know all of the stuff but the names gave me a pretty good hint. Then there were some that I had to know more about and that’s when I found this list:

Asus bloatware guide

A neat list, not exactly up to date but most is still relevant. Once I got rid of all crap things just started flying on her computer as well!

Tagged

Git-TF vs Git-TFS

TLDR; While both offers a bridge to TFS they do it slightly differently. Git-TF is the only choice if you plan cross platform use. Git-TFS is written for Windows and on top of the TFS-SDK. More on these differences here on StackOverflow. After that their biggest difference is in how they make use of branches and checkins. While Git-TFS can respect and sync a branch-tree from TFS, that is not possible in Git-TF. On the other hand Git-TF provides the –deep option which makes each commit a TFS checkin aswell, which I haven’t found in Git-TFS.

Cross platform

If your need is cross platform, then you don’t really have a choice, Git-TF is the only way to go. Built on Java it runs pretty much anywhere. Git-TFS is built on top of the TFS SDK, which means nearly Windows only. Saying nearly, because I’m unsure weather or not it can run under Mono but I’m guessing not.

Performance

Because Git-TFS is built on the TFS SDK it has very nice performance. Connections are quick and swift. Git-TF is notably slower, especially when connecting. Though, in my opinion, it is still not slow enough to be disturbing.

Branches

Branching is one of the main differences between the two. Still being quite a n00b in the Git space, but learning, I get the feeling Git-TF respects the Git-way of working with branches more. Not that Git-TFS hinders you to do anything, more that it uses some automagic I’m not comfortable with.
In Git-TF you always push your changes, as well as pull, from the master branch, there is no other way. This also encourages you to keep the master-branch clean if something else comes up.
In Git-TFS you can push from any local git branch. It then also automatically downloads anything from TFS you do not currently have, and merges it in. Git-TFS can also keep your TFS branch tree in sync and keep track of it, which is not available to my knowledge in Git-TF. This is done with the --with-branches flag.

TFS checkins

This is the other point where they really differ from each other. In Git-TF you can use the --deep option to make each commit a checkin in TFS. While this is very nice and preserves all history between the two systems, it does put some contraints on how you work. If you have gated checkins activated on your TFS project, this will not work. Either you have to use --shallow which takes all commits and makes a single TFS checkin, or --deep --bypass which bypasses the gated checkin. This may not be what you want.
Git-TFS on the other hand does not have any option to make each commit a checkin in TFS. But it does have a nice checkin-tool (git tfs checkintool) which takes all your commits and builds a massive (depending on number of commits) comment of all your commit messages since last push. Git-TFS does not have any trouble with gated checkins, I’m guessing this is due to all commits are checked in as a single checkin instead of preserving them. The problem probably being that it would be hard to tell the user everything happening with a gated checkin on every single commit.

Further reading

Tagged ,

Getting started with Git for the TFS dev (and quick reference)

This post is aimed at those totally inexperienced with Git and what it is. So it is very basic, but also covers some useful tips and tricks I’ve picked up along the way.

Git(Hub) vs TFS (pre 2013)

The significant difference between Git and TFS to begin with is that Git is a version control system while TFS is mainly a central code repository system with some version abilities. Then there is GitHub which is a code repository running on Git. The following will not cover GitHub.

The tools

Since I want to lower the bar for trying all this out I will not point you to a bunch of websites and tell you the order to install things. Just use Chocolatey! If you haven’t used it before, just run the command on the frontpage and you are set.
After that you need Git, so run: cinst git
And then, you probably want Git-TF or Git-TFS: cinst Git-TF or cinst gittfs, or both if you want to give both a shot.
To make command line life easier with tab-completion support, and visualise your work a bit better I suggest PoshGit: cinst poshgit
If you are a heavy mouse user and not comfy with the command line you probably want to get GitExtensions, which is a graphical tool to help you with most (if not all) commands. I prefer this when heading down a nasty merge. cinst gitextensions
And last but not least, for those of you quick with the mouse there is a Visual Studio plugin to handle alot of tasks.

Working order

Using Git locally gives you some nice opportunities. Firing up a project and get started is very easy and it can help keep you sane when a large chunk of work is ahead which you do not want to check-in to TFS, yet regularly want checkpoints. Jimmy Bogard has a nice post on how to perform day to day operations. Follow these simple steps and for the most part you will be fine.

The big difference

What you must know when working with Git, is that a folder, any folder, can be a repository. This also means that when you switch branch, the current working folder will change its contents. This is important, because what happens when you have a file open and switch branch? Not to worry, nothing gets lost.

The other difference is that you do not explicitly check out anything. If it is on your machine, you have it accessible and it is never write-locked. Just code away.

The commands, quick reference

  • git init, initialize a new git repository.
  • git checkout myFeatureBranch, switch branch.
  • git checkout -b myFeatureBranch, creates a new feature branch.
  • git add -A, stage all files you want to commit, modified, new files and deleted files alike.
  • git add ., stage all modified and new files, no deleted files.
  • git add -u, stage all modified and deleted files, no new files.
  • git commit -m "Your descriptive commit message", commits all staged files with given message.
  • git rebase branchName, applies and fast forwards work from “branchName” on top of your current branch. Sort of a merge in TFS.
  • git checkout -- <filename>, if, god forbid, you made something wrong, reverts to last HEAD (commit).
  • git reset --hard HEAD, reverts entire branch to last commit undoing anything not commited.
  • git tf clone http://tfs-server:8080/tfs/DefaultCollection $/Path_In_SourceControl, initializes a new Git repo from an existing TFS path. The –deep flag is optional and clones each TFS changeset and vice versa.
  • git tf configure --deep http://tfs-server:8080/tfs/DefaultCollection $/Path_In_SourceControl, configures an existing Git repo to communicate with a path in TFS. The –deep flag is optional and clones each TFS changeset and vice versa.
  • git tf pull, fetch everything from TFS you don’t currently have on your local git repo.
  • git tf checkin, checks all your commits in to TFS. If you’ve used the deep option, each commit will be a TFS checkin as well.
  • git tfs quick-clone http://tfs:8080/tfs/DefaultCollection $/some_project, performs a quick clone letting you keep working from latest changeset.
  • git tfs fetch, fetches latest work from TFS to your local repo.
  • git tfs checkin -m "Did stuff", checkin all your work to TFS with a comment.
  • git tfs checkintool, checkin all your work to TFS using a graphical tool and builds a checkin comment consisting of all your git commits.
  • And then…

    And then you get started! Pull it down, play around with, get a feel for what you like. I really like the commandline for just staging and commiting, as well as performing basic merging where everything goes smoothly, and also pushing commits to TFS. It takes less of my focus away from what I’m currently doing and I don’t have to let go of the keyboard. But then if there’s a hairy merge coming up or a rebase gone wrong, to me the overview and messages are clearer in GitExtensions.

    Speaking of merging, as a last note I want to point out that Git performs mergings much smoother than TFS and can handle 3-way merges. So alot of pain is taken away directly. Then GitExtensions uses KDiff by default to handle the merges (still 3-way) which visualizes it all very well. I can’t remember a single merge having gone totally bonkers with this approach. And if you still don’t like git, consider setting KDiff as your standard TFS merging tool, it will help a lot.

    Further reading

Tagged ,

All brands should have a death metal logo!

This one is swirling around Twitter right now. As a death metal fan, I can’t do anything but agree. They are all great, but I really like the Yahoo and Microsoft ones, hope they adopt them – I’d buy the t-shirt!

See them all at FastCoDesign: http://www.fastcodesign.com/3020926/innovation-by-design/11-famous-companies-re-branded-as-black-metal-bands

Tagged