Tag Archives: clean code

Friday coding contemplation

I haven’t really been to roads end with this one, so bear with me if it doesn’t quite make sense.

When coding, I usually like to keep my objects as immutable. But on the other hand I really like the verbose way of initializing objects with Object Initialization. Of course there are ways around this, like named parameters, or just the good old naming variables correctly.


  var p1 = new Person {
    FirstName = "Monkey",
    LastName = "Business",
    Age = 42
  };

  var p2 = new Person(
    firstName: "Monkey", 
    lastName: "Business", 
    age: 42
  );

  var p3 = new Person()
    .SetFirstName("Monkey")
    .SetLastName("Business")
    .SetAge(42);

Where the Set-methods looks like the following.


  public Person SetFirstName(string firstName)
  {
    FirstName = firstName;

    return this;
  }

  public Person SetLastName(string lastName)
  {
    LastName = lastName;

    return this;
  }

  public Person SetAge(int age)
  {
    Age = age;

    return this;
  }

While this doesn’t make the objects immutable at all, it does open some other benefits. From time to time I tend to really dislike properties because they are easy to misuse. I myself don’t have a right or wrong answer, but to me they should be lightweight accessors and not perform a whole slew of stuff. If you are in that position a method might be good.

I guess the gist of this is that there are ways of doing things which we might forget. And while we love our fluent APIs, we are quite crappy at actually creating and using them for ourselves when not served via a library, framework or something. But all we really have to do is return this;.

What’s your flavour?

Tagged , ,

Friday afternoon #coding #goodie

After our code retreat a couple of months ago I got some inspiration for improving code and specifically number of parameters. So instead of passing parameters all over the place and polluting methods creating long long long long long long long lines of unreadable stuff, there are now just 2 params for this particular method.

Before:

_contentRepository.List(request, marketFilter, showExtended, paging);
...
List(ReadMarketContents request, IEnumerable marketFilter, bool showExtended, IPage paging) {
  //do stuff
}

After:

_contentRepository.List(request, options);
 
List(ReadMarketContents request, dynamic options) {
  //do stuff
}

Since “options” is a dynamic expandoobject I can assign and read data from it as I please with the usual dot-notation without the reflection-crap making things unreadable, since the compiler handles it for me.

dynamic options = new ExpandoObject();
options.MarketFilter = base.Request.GetMarketFilter();
...
var marketFilter = options.MarketFilter as IEnumerable;

And all this goodness without getting a class explosion for each and every request case like in this example. Think it might be a good fit for these kind of optional parameters where scope is limited, since knowledge is required.

Tagged , ,

#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 , ,

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 ,