Sunday, 5 January 2014

New Years Resolution Gym Goers; Don’t Join!

I am writing to all the people who’s new years resolution is to “get fit” or “lose weight” and this usually means they think they should join a gym … don’t! Well not initially anyway. If you’re already a member of a gym then I’m sure you can relate to this.

Let me explain why I think you shouldn’t join a gym …

The way this usually works is people think they need to join a gym, so they join at £xx per month and get locked into a 12 month starter contract. They then start to go in January with the aim to go 3 to 4 times a week and do this class and that class. They do it for maybe two to three weeks but then work gets in the way, they remember they want to go to the pub and socialise instead of doing squats and crunches and before they know it they’re paying their membership fees so they can say to their friends “I’m a member of a gym”.

Don’t get me wrong there are people out there who start in January, get fit, get ripped, be happy etc. but a majority flounder and give up.

So people end up paying a lot of money for not going to the gym and for January the people who take it up and stop in February just annoy and get in the way of regular gym goers.

Let me be fully clear I am a member of a gym and have been for many years; although it wouldn’t show looking at me. I dip in for a few weeks/months at a time and then something comes up etc. and don’t go for a while so I look at the issue from both sides depending on where I am.

So what can people do to get fit and save money?

To get fit you don’t need to join a gym although joining eventually can help. You can start off by doing free activities such as running. You can get a number of apps now a days which will help you train from couch to xkm and apps which will track you such as RunKeeper. If you want to run with people there are many ParkRuns world wide which you can sign up for and go to for free.

If you want to be more serious about training then look to get a personal trainer who comes to your house and can train you in the garden or local park. This way you are paying purely for their time and not paying the gym *and* a personal trainer.

If once you get to the point where you want to join a gym and you’re already getting fit and have built in the time into your weekly schedule then please do. When you do try not to feel self conscious about going to the gym if you aren’t model thin or can only lift a couple of kgs people are there for themselves and don’t care what others are doing. So take some music and lose yourself in the exercise.

It doesn’t matter if you train at the gym or not but you do feel better for doing exercise so I encourage you to keep with your new years resolution.

Happy exercising and money saving in 2014!

Thursday, 29 August 2013

Feeling overwhelmed and like a phony? Chill out!

Do you ever feel overwhelmed by the amount of new technology which is coming out all the time? The new framework to do this, and the new improved way of doing that. The new blog posts about this and that, the never ending Pluralsight courses by John Sonmez? It can be too much!

Recently I’ve been feeling this way as well as losing the motivation I use to have to code. I’ve not lost the joy of coding or problem solving but the combination of being overwhelmed by all the bleeding edge technology and information coming out of the developer community and in contrast the recurring day to day coding on brownfield code bases running VS2010 (and every so often VS2005) can get you down.

Recently I’ve got to a point in my life/career where I feel like a bit of a phoney. I’ve worked very hard to get where I am today and at only 30 years old I potentially still get seen by some as the opinionated upstart when I’m not. I know I have a lot more to learn but I think everyone does whether that’s new processes in your day to day life, understanding ways of doing tasks in new positions etc. You should always be learning and adapting.

The realisation of trying to learn everything is just not practical. Reading code is a great way to learn new techniques which you can apply to your day to day developer life but learning the ins and outs of every framework is just not possible. The other aspect of learning is you can run through a Pluralsight course on this or that but if you’re not using it every day all day at work or at least a couple of hours in the evenings each week on a personal project you’ll very quickly forget it. This, I think, is my main frustration.

So as I see it there are a couple of ways to solve this issue which range from minor to life changing. You can ignore all new technology, carry on with your day to day life, not do anything outside of work; essentially put your head in the sand. This will however leave your skills becoming slowly stagnant and make future career progression hard. On the complete other end of the scale you can move jobs, go and work for a company where they are using the latest and greatest, always starting new greenfield projects, this will help improve your skill set and keep it up to date but that will impact your life completely which isn’t always the answer either. Changing jobs, whether forced through redundancy or by choice, is a big change!

So what can you do? Learn every 3rd new technology which appears on the Pluralsight new course listing? This isn’t practical. Maybe try and influence technology at work? Spend time during the day (lunch time, 30mins before heading home) reviewing new technology? Both of these are possible but will depend on personal situation.

I’ve been thinking over this conundrum recently, and the near future birth of my first child has helped my thinking on this subject, the biggest issue is I’ve been putting too much pressure on myself. Too much pressure to learn new technologies, too much pressure to read every blog post about every technology. Also when I do look at a technology and write pet/personal projects such thoughts as “it needs to be production ready code straight away”, “you need to get it done now”, “it needs to be perfect first time” aren’t the thoughts which will aid motivation but in fact demotivate.

So if you find yourself in a similar situation as I have recently and don’t know what the answer is then use the realisation that has only hit home to me recently; chill out! Don’t put yourself under unrequired pressure. Yes, continue to read blog posts. Yes, continue to play with new technologies as/when you can … just don’t pressure yourself into having to do it all the time as it can be harmful as well as beneficial.

Thursday, 18 July 2013

Make your code readable by making it flow with Generics

I’ve seen a couple of examples of code recently which basically have a method which work primarily on a base class but the resultant will always be cast to a concrete implementation. This can make the code a bit clunky as each caller has to cast the resultant to the type it’s expecting. Let me show you want I mean:

public abstract class Base
{
    public string Comment { get; set; }
}

public class Concrete : Base
{
}

public class Update
{
    public static Base AddComment(string message)
    {
        // the type created can be determined by some other means eg db call etc.
        var response = new Concrete();
        response.Comment = message;
        return response;
    }
}

And then when it is called it needs to cast to the required type:

var concrete = (Concrete) Update.AddComment("update the comment");

This code snippet doesn’t read that badly however once the system gets bigger or this technique is used for more complicated types/systems then it can start to look clunky. As you know what types you’ll be working with and what you will expect returned when calling the code then you can make the code clearer and flow by using generics.

public class Update
{
    private static Base AddComment(string message)
    {
        // the type created can be determined by some other means eg db call etc.
        var response = new Concrete();
        response.Comment = message;
        return response;
    }

    public static T AddComment<T>(string message) where T : Base
    {
        // in this example the call is into the original method
        // but this does not have to be the case
        return (T) AddComment(message);
    }
}

Notice I’ve made the original AddComment method private as I don’t want to allow any callers access to it directly. The example calls into the original private method but this does not have to be the case.

Now when the same functionality is called in the main program flow it looks like this:

var concrete = Update.AddComment<Concrete>("update the concrete");

Updating the API in this way makes the calling code clearer to read and makes the API signature developer friendly so a potential cast is not missed out.

Sunday, 19 May 2013

Asp.net MVC Output Caching During Development

During some Asp.Net MVC development for a public website recently I have been looking at caching. The content of the site has minimal churn so I looked to use OutputCache. This works fine once it’s been finished and released. However it causes frustrations during development when you want to change something, compile, refresh and nothing happens.

One option is to comment out the OutputCache attribute, either on each action or on the specific controller, during development but that seems a bit crazy and isn’t sustainable. So what can we do about this?

A Preprocessor Directive is one potential answer; especially the #if and using DEBUG value for example:

#if !DEBUG
    [OutputCache(Location = OutputCacheLocation.Any, Duration = 36000)]
#endif
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

Now when you build in debug mode it will disable the caching and then once you’re happy and ready to release, change the build to “release” and it will be included ready to deploy to the production environment.

Tuesday, 7 May 2013

Tournament – Results and Calculating Scores with RavenDB Indexes

This is the 4th part of a series that is following my progress writing a sporting tournament results website. The previous posts in this series can be found at:

In the previous post I explained the basic CRUD operations and interesting routing issues which I found to get the setup I was looking for.

What do I want to achieve?

By the end of this post I will have shown you how I have started the process off of saving match data, how I have chosen a jQuery plugin to aid with the user interface when entering results and my first run at a calculated index to calculate the scores of the matches so far.

Match up details

The arguably most important part of a result stats website is recording the match ups between players and the outcomes. Once this is done the accumulation of the result scores can be implemented. How they are linked to Events is a small issue compared to recording the actual results.

Let’s start with the first part and see how it goes.

So let’s take a look at some of the potential scenarios which could happen and how we will deal with them.

  1. Single and Doubles match ups with home and away players
  2. Players could play for the other team due to number match ups
  3. Players could move club between events
  4. Ringers could play for any club at any time

To address these issues for each match up there needs to a be a collection of home players and away players. These will be the player records at the point in time at which the match up takes place; the assumption here is the match details won’t be changed after any player changes are made for future events. As we’re using a document database for this and the root is the match then each match will have an instance of the player record at that time point when it occurred.

public class Match : RootAggregate
{
    // todo: link to leg
    public Classification Classification { get; set; }
    public Result Result { get; set; }
    public Team WinningTeam { get; set; }
    public Team HomeTeam { get; set; }
    public Team AwayTeam { get; set; }
    public ICollection<Player> HomePlayers { get; set; }
    public ICollection<Player> AwayPlayers { get; set; }
    public ICollection<Comment> Comments { get; set; }
}

As we can see above we also want a reference to both the home and away teams as well as the winning team. With these details by themselves it would work fine and store the data as required. I have decided to include a Classification enum to make it easier to distinguish between Singles or Doubles match ups (the doubles classification will also be used for 3 on 2 match ups). Due to the issue of 3 on 2 scenarios I’ve kept the players as collections and not explicitly player 1 and player 2. In addition to this I’ve added in an associated “Result” enum value. 

public enum Result
{
    Incomplete = 0,
    Draw,
    HomeWin,
    AwayWin
}

Having this result value will aid with determining the scores without having to do comparisons between different properties (and potential sub properties) with the aim to make the score index calculations cleaner to read.

Chosen

Chosen is a jQuery plugin to aid with making dropdowns and multi selects more user friendly. I first came across this about 12 months back when it was introduced at work to aid with large dropdown selectors. I decided to use this because I would be selecting individual teams from dropdowns but mainly I would be selecting multiple players from a multi select form input and wanted to make it keyboard friendly to speed up result entry.

image

As you can see from the small screen shot above it aids with single selection and makes the multi select look cleaner by hiding the “noise” around a default vanilla multi select input form control.

I’m not completely sold this will be the final solution for this issue however it performs as required for now. When I get to working on the UI then I will decide if Chosen is the best way to go or to find an alternative solution.

Score calculations

I had read multiple blog entries on how to do a Map / Reduce index in Raven DB. The general concept of this is to map from a document collection into a simple form with a counter set to 1 which can then be collated and grouped on a property and the counter value can be aggregated to get the full result. This would be fine however I want to count Wins, Losses, Draws and eventually Extras per player in one index. I knew there had to be a way but what was it?

This is when I discovered AbstractMultiMapIndexCreationTask. It works in a similar way to the more basic AbstractIndexCreationTask<T> however instead of having a specific type it “maps” - as defined by T – it allows for a generic method called AddMap<T>. AddMap allows the document type to be defined and then to map into a separate result type (as per the AbstractIndexCreationTask) however you can call this as many times as you like (although I’d imagine there was a limit somewhere either implementation wise or coding standards wise) on any number of document collection types.

Using the AddMap method I added in a “map” for Home wins / losses, Away wins / losses and Draws irrespective of if the player was playing at home or away. I will look to build on this in the future to do more stats for points such as “performs better on home soil” type scenarios.

AddMap<Match>(matches => from match in matches
                    from player in match.HomePlayers.Select(x => x)
                    where match.Result == Enumerations.Result.HomeWin
                         select new Result
                         {
                              PlayerId = player.Id,
                              Wins = 1,
                              Losses = 0,
                              Draws = 0
                         }
                );

Above is one of the AddMap calls. Looking at this you can see how we can determine, using a combination of HomePlayers and Result value, that the home players have a win. After another internal code review I have noticed that I didn’t need to do the Select(x => x) however this was left over from earlier development when I was looking at extracting out just the player id and will be updated.

I now had the “mapped” part of the implementation. At this point I have a collection of Result objects with each entry being the result of an individual match per player in that match.

The Reduce part is a simple aggregation using the PlayerId as the group key. This can be easily established using the code below.

Reduce = results => from result in results
                    group result by result.PlayerId
                    into r
                    select new Result
                        {
                            PlayerId = r.Key,
                            Wins = r.Sum(x => x.Wins),
                            Losses = r.Sum(x => x.Losses),
                            Draws = r.Sum(x => x.Draws)
                        };

This will give you a result record per player, who has played at least one match, and their “record” for all events.

At this point it got me the data I wanted but I also wanted to display the player information as well as the results. I first started off looking to do a “join” between the index results and a Player query although I realised I was still thinking too “relational” and needed to find another cleaner option; enter TransformResults.

TransformResults is another function on an index which you can access much like AddMap and Reduce. The tooltip description is a bit cryptic “The result translator definition” but if you allow Visual Studio to work its magic to set out the signature it makes a bit more sense …

TransformResults = (database, results) =>

What this gives you is a delegate in the form of a function expression which takes in IClientSideDatabase and the IEnumerable<T> of your results set which is the outcome of the Reduce we did earlier. The IClientSideDatabase interface, and it’s associated implementation which gets passed in by RavenDB at run time, is purely a lightweight data accessor. As per the documentation the methods are used purely for loading documents during result transformations; perfect! Using this mechanism I was able to Load the player record for each of the result values to be able to access the additional information.

TransformResults = (database, results) => from result in results
                            let player = database.Load<Player>(result.PlayerId)
                            select new Result
                                          {
                                              PlayerId = result.PlayerId,
                                              Player = player,
                                              Wins = result.Wins,
                                              Losses = result.Losses,
                                              Draws = result.Draws
                                          };

Conclusion

In this post I have gone over how I’ve decided to model match information, used a jQuery plugin called Chosen to aid with the user experience when adding / editing a match data and how I used a AbstractMultiMapIndexCreationTask derived index in Raven DB to calculate the scores for each player, returning their scores along with their player data.

As always you can follow the progress of the project on GitHub. Any pointers, comments, suggestions please let me know via Twitter or leave a comment on this blog.