Thursday, September 26, 2013

FizzBuzz Adventures in Golang

Before I get into Go Routines and Channels (which are both really cool), I thought I'd do some more direct C# to Go translation.  So, I took a FizzBuzz project that I had written in C#(here) and converted it to Go(here).  Here's a play by play over the main differences.  Some of it is obvious with only slight syntax differences.  But other parts are pretty different from C#.  That's what I'll focus on in this post.  Again, if I get something wrong please let me know in the comments or send me an email.

First up is the .go file(below) that contains the package main and the function main.  I'm creating an executable (.exe) with this file so I have to use the main package and have a function called main.  Very similar to a console application in .Net.  The import keyword denotes the packages I'm importing, "fmt" for formatting and writing text to the console and the line to my package that contains code for my Go implementation of FizzBuzz.

The program gets started with the func main on line 9.  The first thing I do is declare a variable and assign it a value.  The value is returned from a function called GetItems which is local to this file.  One thing you'll notice is the := syntax for variables.  This is similar to implicit typing that you can do in .Net.  In go, I'm saying create a variable called fbp and assign it a value of whatever is returned from the GetItems function.

If I wanted to declare an int and give it a value of 40, I would write agesoon :=40.  In C# I would write var agesoon = 40; and in VB it would be Dim agesoon = 40.  In all cases, the type of the variable is not stated explicitely but it is inferred based upon the value assigned to it.  In Go, if I wanted to change the value later I'd just write agesoon=41.  If I tried to use agesoon:=41 I would get an error because agesoon has already been declared once.

Line 11 starts a simple for loop.  The syntax is almost exactly what one would expect in C#.  The fmt.PrintF on line 13 is doing basically the same thing as Console.Writeline.  That's our main function.  The program begins and ends here, with a few detours of course.

Let's take a look at line 19.  I'm creating a variable of type FizzBuzzNumberOnly.  Line 20 looks a little strange.  var _  = fbpno is odd.  Why is that here?  In Go, if you declare a variable and don't use it, you get a compile time error.  Not a warning.  An error.  Same thing happens if you import a package in a .go file and you don't use anything from that package.  You get a compile time error, not a warning.  This is by design.  One of the reasons for this is that compile time speed was important to Go right from the start.  Files containing un-referenced variables and packages slow down compile time and provide...nothing.  As you can expect, there are some differing opinions on this.  The _ character allows me to use the variable by assigning it the blank identifier.  The blank identifier does not create a binding.  If I want to keep this variable in my program, I have to assign it to something or Go won't let my project compile.

Let's move on to the type FizzBuzzProcessor.

This file contains some of our code for the FizzBuzz library.  This isn't an executable, so there's no package main.  It's designed to be used by other Go programs.

The only package we import is the built in strconv so that we can convert things to strings.  First look at lines 11 through 13.  We are creating an interface called IFizzBuzzItem.  I used I for the first letter of the interface to keep with the convention that is widely used in .Net.  After the name we specify that this interface contains one method called GetResult.  It takes in a single int parameter called num and returns a string.

What's cool about interfaces in Go is this:  Any type that has a method called GetResult with an int parameter called num that returns a string automatically implements the interface IFizzBuzzItem.  We don't have to manually tell our other types to use the interface.  How cool is that?  It works kinda sorta like the poor man's interface I described in this post.

On line 15 we make a type called Items that is a slice of types that implement IFizzBuzzItem.  See the article arrays, slices and maps for more info.

See, I didn't name it anything.  Often times in a struct you have a name and then a variable type like, maxnum int or lastname string.  But you can also just create a field and call it a type.  So, my FizzBuzzProcessor has one field, that's a slice of IFizzBuzz items and one method called GetResult.  You'll notice that the method GetResult is declared separately from the struct type.  It's a part of the FizzBuzzProcessor type because it accepts a pointer to a FizzBuzzProcessor variable.  So any FizzBuzzProcessor type will have access to this method.  This is one of the things that will throw a .Net developer.  We're used to having fields and methods that belong to a class all in one place (even if it's split across files using partial classes).  Not so in Go.  However, if you are familiar with Extension Methods in .Net, you'll see some parallels.  If you're not familiar with extension methods in .Net, now we be a good time to read up on that.  If you use Linq you're using them all the time.

GetResult is going to accept a number, loop through all the instances in Items and see if the num parameter meets any of the conditions.  Let's look at the conditions themselves to see how this works.

There are several types that can be used, but I'm just going to cover the FizzBuzzDivisor type since it meets the requirements for the classic FizzBuzz problem.

I define three instances (covering Fizz, Buzz and FizzBuzz) like this:

fbdiv15:=sfb.FizzBuzzDivisor{15,"FizzBuzz"}
fbdiv5:=sfb.FizzBuzzDivisor{5,"Buzz"}
fbdiv3:=sfb.FizzBuzzDivisor{3,"Fizz"}

Here, I'm declaring and assigning three variables.  I'm also setting the properties after it variable is instantiated.  This isn't a constructor, it's assigning property values after the fact.  C# sharp allows the same thing.  For example, you can do:

var person = New Persion(){LastName = "Smith"}

Go doesn't need me to name the properties (although it's allowed) since I'm matching the order and type of how the are declared in the type.

Again, the GetResult method that meets the requirements for the IFizzBuzzItem interface resides outside of the type definition.  In this case, I'm passing a value to the instance and not a pointer.  I don't know enough yet about pointers to know why I'm doing it one way here and another way with the other type, but I'll figure that out.  I just know I had to do it this way to get the code to compile.  The main thing is, methods are declared outside of the types they belong to.  You get used to it pretty quick.

So that's about it.  I have a few other types that make use of the IFizzBuzzItem interface so that I can test for the ultimate answer, palindromes and perfect squares.  I make sure to add them in the order that I want them to be checked and that's that.  If a number meets more than one condition, only the resulting string of the first match will be returned.

So, that's my FizzBuzz in Go.  I learned a lot about the Go as I wrote it.  I like how it's teaching me new things about software development.  I still like C# a lot, but I hope to get better with Go, get up to speed on Postgresql and be able to write complete applications that aren't on Windows or Azure (yes, I know about Mono/Xaramin, it's great stuff).

So there you have it.  I have a few more programs in mind that I'll write in Go, one of which will help me check code as I write it.  It's fun stuff.

If you want to get started with Go yourself, read this and get...uh...going.
http://golang.org/doc/install

Friday, September 20, 2013

I'm going to learn Go

I'm going to give it a shot anyway.  I've read enough about Go to find it really interesting.  I want to learn something outside of the .Net world so I can actually call myself a polyglot programmer.  I'm sure I'm going to get lost at times, but I'll start small and see where this takes me.  I do think it's important to learn to think about code differently and Go seems different enough to help with that.

So for the first several Go posts, I'll just write some C# code and the equivalent Go code.  I'm sure I'll be "doing it wrong" since the languages are so different, but it's frustrating to start working in a new language and get stuck on, "how do I this simple..."?  I want to know how to build types, make function calls, do loops and if/else type things.  I'm sure it'll be obvious that I'm using Go with a C# mindset, but that will change with time.

I have several posts in the hopper that I was going to do with C# code, but I'm going to push those back and re-write them in Go.  This will help drive the "C to Go" posts and help me to learn more about the language.  I imagine I'll get in over my head pretty quickly.

Three things I like about Go already.


  • If you bring a package from one go library into another, it's included so you don't have to have access to the source package once you compile to an .exe.  I remember way back when I was getting started with .Net, I was frustrated that in order to have an object that inherited from a base object, my final program had to have access to both the base object and the new object.  Now, Go doesn't have inheritance like C#/VB but it does have dependencies and it's nice how those dependencies are brought into the final .exe.  You can take that .exe, deploy and not worry about bringing all the dependencies with you.
  • You can take your final .exe and copy it to another computer with the same OS and it just runs.  You don't have to have any Go stuff installed.  I know this is a "duh" for lots of programmers but for .Net developers, it means there is no need for the right .Net Framework or any .Net framework for that matter.  No Java run time stuff.  Again, I know this is a no brainer for lots of developers but for me, it was a reminder that there are ways of writing code that don't require pre-installed frameworks.  Other than an operating system.
  • My favorite thing is that, the entire Go spec is fifty printed pages.  You can read all there is to know about Go in an afternoon.  That gives me the hope that I can understand and really use Go.  This podcast goes over the reasoning behind Go and specifically mentions that you can become productive in Go in a weekend and get really good in a few months.  This is one of those opportunities to get in on the ground floor with a language.  As it grows and changes it'll be much easier to understand what those changes bring since it's possible to hold the entire language in your head.  Well, possible for some, we will see if it's possible for me.
Next up, Go FizzBuzz.

Tuesday, September 3, 2013

Object Mapping With ConvertAll

Sooner or later there will come a time when you have a collection of one type of object that you want to map to another type of object.  There might be a user object that contains many properties about the user but when displaying a list of users, you might only need the user name, real name and  userID.  I mean, <snort> why would you return the user's credit card in the JSON if you didn't really want to display it?

You can use tools like AutoMapper (which is great) but for simple one off conversions you can make use of .ConvertAll.  Keep in mind that ConvertAll is a method on the List class itself.  It is not an extension method on IEnumerable.

One scenario I've come across is when two different methods return objects that describe the same data, but in slightly different ways.

Let's say you have a Person class and a Human class.


These two classes are essentially the same, but there are a few nagging differences.  Human has a LastName and a FirstName property while Person just has a Name property.  Human stores height in inches while Person stores height in centimeters.  Lastly, Human stores the date of birth as a string in a property called BirthDay while Person stores that information in a DateTime property called DOB.

How does one convert a typed list of one kind to the other with ConvertAll?  Like this:


We could refactor this further so that we can directly map just one Person to a Human and vice versa in cases where we aren't dealing with a List.  These functions allow us to pass either type to the method and get back the other type:


Now the lines of code are adding up.  And if you want to run unit tests that make sure converted objects really are equal, you'll have to overload the Equals operator AND the GetHashCode method to get that to work. The more you write this code by hand, the better looking a tool like AutoMapper becomes.

So, if you are dealing with typed Lists and you only need a basic one off type conversion, it might be quicker to roll your own.  You can do the whole thing in the ConvertAll statement.  If the objects are more complex or you have several different mappings to worry about, you can still roll your own but, there are libraries out there to make life easier.

Source code for the entire project can be found here:
https://github.com/genghisjahn/ConvertAllExample

Thursday, August 29, 2013

Poor Man's Interface With the Dynamic Keyword.

While creating a demo application for an upcoming blog post, I found myself with a method where I copy pasted the same code to work with three different types.  I looked at the code and thought, "I should just create an interface for these small classes and rewrite this as one method that's called with three different types."  But, one type was a reference to an asp.net 2.0 web service type, one was to a local type and one was a dictionary return from a call to a ServiceStack REST call.  If there's  a way to have those classes implement an interface after the fact, I don't know about it.  But without even google/bing-ing a solution, I realized I could make this work by using the dynamic keyword.  If all three types had the same method of interest and same signature, I could get away with passing them to the general use method even though they did not implement a common interface or inherit from the same base class.

Let's illustrate with some code:



I know, I know. It's bad code, but the save button isn't a lock button, so we can refactor. Furthermore, by using the dynamic keyword, we can refactor to this:

Much better right? And now you can call each the method like this:
Keep in mind, none of these objects inherit from the same base class or implement the same interface.  By convention I made sure that the AddThis method would be called the same way every time.

Nothing magical here, but it might get you out of a bind.  I'm not sure that I'd want to put this in production code, at least not for every long, but it works.

Wednesday, July 24, 2013

C# is Case Sensitive...Right?

Well...yes, of course.  It's well known that C# is case sensitive(interesting discussion on this can be found here).  If you declare a variable like this...

string name = "John";

...it will be different than a variable declared this way...

string nAme = "Smith";

One of the easiest ways to tell if your variables are spelled correctly is to try to compile your project. If your case is off, you'll get an exception at compile time and your code will not run at all. This is different from VB.Net, where variable names are not case sensitive in the VB.Net IDE.

Dim name as string ="John"

and

nAME as string="Smith"

is allowed because the  VB.Net IDE ignores the case difference between "name" and "nAME". In VB.Net land, they are the same variable and you can't declare a variable with the same name in the same scope more than once.  Note that the IDE allows you to get away with different cases in VB.Net.  The compiler/CLR take care of case issues later(more here).

But while I was using Dapper, I noticed something odd.  Sometimes the case between a class type<T> and the table column matched and sometimes they didn't but Dapper didn't seem to care at all.  But if I called the .Query method without a <T> parameter, then case did matter.

If you call .Query in Dapper without a <T> parameter the method will return IEnumerable of type dynamic.  I didn't know much about dynamic at the time but I assumed this would let you play fast and loose with property names.  But that's not what happens.  Dapper allows mis-matched case when referencing a Type property but if you don't specify a Type and you are dealing with IEnumerable of dynamic types, you have to match case or you get run time exceptions (not compile time exceptions).  This is counter intuitive but that was obviously how it worked.

In this example I specify Type:

List players = cn.Query<Player>("select * from player");

Console.Writeline("Player ID: {0}",players.FirstOrDefault().PlayerID);

This works fine even though the column name that the PlayerID is referencing is "playerID".  Column names are not case sensitive in MS SQL, but we're in that twilight zone where  database types are mapped to CLR types.  On the CLR side case sensitivity is going to make itself known.  But it doesn't matter here.  I can rename the column name to pLaYeRiD and it will still match to the property name PlayerID in my Player object.

But in this example, case does matter even though we are returning IEnumerable of dynamic.

var players = cn.Query("select * from player");

Console.Writeline("Player ID: {0}",players.FirstOrDefault().PlayerID);

This will throw a run-time exception Microsoft.CSharp.RuntimeBinder.RuntimeBinderException with the text "Could not match up class property with object property."

Weird huh?  Specify a Type and you can play fast and loose with the bindings.  Don't specify a Type, go dynamic, and you have to match the property name case exactly to the the case of the column returned in the record set.

The thing to keep in mind with the dynamic "type" is that it's not really a type.  There is still an underlying type that's the real type.  When you use the dynamic type for a variable, you are saying to the compiler, "I got this.  You don't need to check type whenever you see this variable during compile time."  Does this sound a lot like the object type?  It works exactly the same way in many circumstances.  In fact, dynamic only exists at compile time.  At run time it's converted into type object.  (Read about it here on MSDN).

So what's Dapper doing behind the scenes here?  Since it's an open source project we don't have to guess, we can look at the source code.  This link will show the source code for how Dapper maps a Typed query.  The part we really care about is in the GetMember method.  If you step through that you'll see how the property names of the class are matched up with field/column names from the returned record set.  The matching is done with the null coalescing operator:


var property = _properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
               ?? _properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));

StringComparison.Ordinal means to compare the strings by comparing a code for each char in the string.  It's fast but culture dependent.  Remember that Dapper was built for speed, so it reasons they chose speed over the ability to by culture independent.  If it finds a match there, great.  If it doesn't then it does the same comparison but with StringComparison.OrdinalIgnoreCase.  OrdinalIgnoreCase converts each char in both strings to all upper case and then checks for a match.  That's why you don't have to match case when comparing properties of a Type to columns in a returned record set.  If it doesn't find a perfect match the first time, it coverts everything to upper case and checks again.  I suspect matching case on both sides would result in slightly faster return times.  Once a match is made an object of type SimpleObjectMap is returned.

So what about the dynamic side of things?  It's a lot more straightforward...and convoluted.  Lines 1635-1643 show where Dapper loops through the columns in the result set and makes a DapperTable filled with the names of the columns.  If you step through the code you'll see that these are in turn converted to a collection of DapperRow and this is what is returned to the calling method undercover of dynamic.  The DapperRow class builds "properties" that have the same name and type as the column returned from the database.  Since these are properties, they have to be referred to with matching case.  I could spend a few more posts just on the DapperRow class but that's the gist of how it works.

So case sensitivity holds up like it is supposed to in C#.  If Dapper has a Type to work with in addition to a set of columns, it can make mappings for you even if you get the case wrong.  If you are leaving it up to Dapper to return  the result and and work without a column map you have to make sure the case is right for each property.  Intellisense won't help you.







Saturday, July 13, 2013

Screencasting on a Budget

Scott Hanselman has a great post about making quality screencasts.  If you want to get into the screencasting thing, go read it.  If you are able to buy the recommended software and hardware that Scott recommends, great!  No need for you to read further.  But if you are on a budget or you want to make sure screen casting is really for you before you sink a lot of money into it, then read on...

  1. Don't use your computer/laptop microphone.  You're going to need a new microphone.  I didn't have $100+ (or $300+) to spend on a mic, so I bought the Samson Go Mic (on Amazon) for $39.99.  It's a USB mic (which is important) and it's very highly reviewed.  It has worked great for me both for screen casts and for interviews for my linguistics class.  This is the most expensive thing I've purchased for screen casting.
  2. Download Audacity.  You need a way to modify the sound from your screen casts.  Audacity is free.  Learn how to insert silence, add a music track, fade in, fade and most importantly, Noise Removal.
  3. Download Screencast O Matic.  You can use the free version but go ahead and spend the money on the pro version, it's $15 a year.  You are going to need the tools in the pro version to cut out your mistakes, add transitions (like dissolves) and most importantly, export and and import your audio track (which you cleaned up using Audacity).

That's really all you need.  Total cost is $45 and some change.  When you are recording be sure to turn off any fans, window A/C units, mobile phones, tablets and any program that might automatically pop up a notification or make a sound. If you have any three year olds in the house, you might want to wait until they are asleep.

Once you've exported your screen cast to a video file, you can upload it to You Tube for free, or you can use Vimeo.  I suggest you check out Vimeo, they have a basic plan that's free.  I decided to use Vimeo Plus which costs me $9.99/month.  So far I've been very pleased with the service.  If you want to keep costs low at the start, stay with You Tube but you will probably see the need for more than the free service that You Tube offers if you continue screen casting. There are a number of comparison articles on Vimeo vs You Tube to help you decide.

Friday, July 12, 2013

Getting Started With Dapper Part 3

     In part three I cover how to use alternate constructors for types used with Dapper. In parts 1 & 2 I used the default parameterless constructor but that doesn't work in every situation.

     Dapper can also make use of a constructor that matches the type and field names returned in a recordset in addition to completely custom constructors that don't mach up to returned recordsets.

     Lastly, I cover how to use a custom constructor and initialize a property during the Dapper mapping using Ling and a simple lambda expression.


Intro To Dapper - Part 3 from Jon Wear on Vimeo.

Source code: https://github.com/genghisjahn/DapperIntroPt1/archive/Pt3.zip