Category Archives: Whatever

#CodeRetreat at the office!

About a week ago we hosted the first ever Code Retreat at the office! We were about 15 happy devs who sat for an entire day contemplating over good code and good practices. To help us out we had Adrian Bolboaca who flew in to facilitate the sessions for the day and guide us.

We had before hand decided to split the day in two; the first part being deliberate practice for clean code, and the other part on refactoring legacy code fast and safe.

In the coding dojo before lunch we sat down with the very basics of coding. Doing things from scratch, thinking deliberately about why we do something, how we do it and how to name it. The purpose was not to finish, but to come up with something really good and try to work in a way that might not be what everyone is used to doing daily. Think. Deliberate. Leave nothing for coincidence.

One of the things that I think most of us took away from this part was “The Boyscout Rule”. It states that whereever you go, leave the place in a better state than when you got there. It applies to code as well. “It works, so don’t touch it” is not a good solution, that does not evolve and improve the code meaning it will go stale and fragile in time. Constant change improves and hardenes it along with the change of time.

In the second part we got to work with an existing piece of code where the objective to be able to change it without some of the risks involved when there are no unit tests and the code might be fragile. So we focused on end-to-end testing, and getting a feel for how to write these tests without impacting the code first. Then, when some basics are in place, refactor the code to be able to write more and better tests, always improving in small steps and see how it all evolves from a pile of crap into something not that bad.

So why did we do this again? Sit down for an entire day and not getting anything *real* done? Well, in order to constantly improve you must practice, like any other professional athlete. For us this was a test shot to see whether we liked the form as a group and see how we can go further with it, making sure that we all get better at what we do and strive for a better place for ourselves.

Really felt like a retreat due to the use of external conference room, reinvigorated the feeling of being an actual coder” -Participant

Tagged , ,

Today let’s celebrate #endregions!

Yes, I do have an issue with them. They are extremely annoying and they rarely add anything, but on the contrary obscures and hide things. I’ve seen uses range from empty ones, to wrap one method or sometimes several classes, but also the creative use of collapsible commenting to explain steps 1-2-3 within a method. WHY?! What is wrong with methods?!

Anyway, this post lays it our very well why we should #endregions. And there is even an action group – The Anti-Region Legion! Get involved.

Tagged

Obey your rules #cleancode

What are your rules? What makes your code good and readable? What you leave to the ones after you is quite important depending on the app you are writing.

I have a few simple rules I try to follow, to keep the code quite clean and understandable:

  • 10 loc per method
  • Only 1 statement (if, loop..) per method
  • 2 parameters in a method
  • Max 5 methods in a class, after that it gets messy and harder to get a quick overview. It also increases the risk of handling to much in a single class
  • Always program against an abstraction, never an implementation

There are some nice benefits that comes out of this. It is easier to structure the entire code base when things aren’t entangled and does lots of things. Naming is so much simpler. Even if you don’t do TDD or write your tests, your code (almost) automatically becomes testable. If something sneaks up from behind and attacks you, just sit back, check the code, write a couple of tests which proves the scenario and you shall see it will surface if you can’t spot it right away.

Heaps of other benefits there are too. Can you figure them out?

I’d love to hear what you constrain yourself with to not get carried away with large pieces of code at the end of the day! Tell me on twitter already.

Further reading

Tagged

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