Archive for June, 2011

Go’s reflection example

The Go Programming language is really cool language by Google. According to the sales pitch, it’s a “fast, statically typed, compiled language that feels like a dynamically typed, interpreted language”. Well, if you are like me, you don’t trust sales pitches because you know that people writing them dont’ care about you, they care about their product. However cynical you are, you still have to check the facts. So here is a quick demonstration showing how to use Go’s reflection feature.

Installing Go is actually really straight forward on a Mac, and slightly harder on Linux, check this guide to see how to build Go in a few minutes.

Once all setup, you might want to read the documentation to see how to code in Go. Go is actually a kind of nice version of C with a simplified syntax, no header files, really fast compilation time, a garbage collector and a simple way to approach object inheritance without turning in the complicated mess C++ is. The language is designed around the concept of goroutines, a very nice way to handle concurrency. It also has some features that Rubyists, Pythonistas and Javascripters wouldn’t want to live without such as closures and some they probably wish they had such as defer. But of the things we are used to with dynamic languages is the concept of reflection. In a nutshell, at runtime, your code can reflect on the type of a given object and let the developer act accordingly. Depending on your programming background that might be obvious or you might not see the value. To be honest, that’s not the question here. What I’m interested in showing you is how it works.

For the sake of this demo, let’s pretend we want to have a “Dish” data model, each instance of the “Dish” type will have a few attributes, an id, a name, an origin and a custom query which really is a function that we store as an attribute. Here is how we would represent that model in Go:

// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}

This is more or less the equivalent of the following Ruby code:

class Dish
  attr_accessor :id, :name, :origin, :query
end

Ruby works slightly differently in the sense that defining attribute accessors create getters and setter methods but doesn’t technically create instance variables until they are used. Here is what I mean:

shabushabu = Dish.new
shabushabu.instance_variables # => []
shabushabu.name = "Shabu-Shabu"
shabushabu.instance_variables # => ["@name"]
shabushabu.origin = "Japan"
shabushabu.instance_variables # => ["@name", "@origin"]

Another way of checking on the accessors is to check the methods defined on the object:

shabushabu.methods - Object.new.methods
=> ["name", "name=", "origin", "origin=", "id=", "query", "query="]

But anyway, this post isn’t about Ruby, it’s about Go and what we would like is to reflect on an object of “Dish” type and see its attributes. The good news is that the Go language ships with a package to do just that. Here is the full implementation:

package main
 
import(
  "fmt"
  "reflect"
)
 
func main(){
  // iterate through the attributes of a Data Model instance
  for name, mtype := range attributes(&Dish{}) {
    fmt.Printf("Name: %s, Type %s\n", name, mtype.Name())
  }
}
 
// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}
 
// Example of how to use Go's reflection
// Print the attributes of a Data Model
func attributes(m interface{}) (map[string]reflect.Type) {
  typ := reflect.TypeOf(m)
  // if a pointer to a struct is passed, get the type of the dereferenced object
  if typ.Kind() == reflect.Ptr{
    typ = typ.Elem()
  }
 
  // create an attribute data structure as a map of types keyed by a string.
  attrs := make(map[string]reflect.Type)
  // Only structs are supported so return an empty result if the passed object
  // isn't a struct
  if typ.Kind() != reflect.Struct {
    fmt.Printf("%v type can't have attributes inspected\n", typ.Kind())
    return attrs
  }
 
  // loop through the struct's fields and set the map
  for i := 0; i < typ.NumField(); i++ {
    p := typ.Field(i)
      if !p.Anonymous {
        attrs[p.Name] = p.Type
      }
     }
 
  return attrs
}

Unfortunately, my code highlighter doesn’t support the Go syntax, but GitHub does, so here is a pretty version.

There are ways of running Go source code like Ruby or Python scripts but in this case, we’ll use the compiler & linker provided with Go. I named my source file “example.go”, and here is how I compiled, linked and run it:

$ 6g example.go && 6l example.6 && ./6.out
Name: Origin, Type string
Name: Id, Type int
Name: Query, Type 
Name: Name, Type string

As you can see each attribute is printed out with its name and type. The code might seem a bit odd if you never looked at Go before.
Here is a quick rundown of the code:

In our main function, we create a new instance of type Dish on which we call attributes on. The call returns a map on which we iterate through and print the attribute name (key) and type (value).
The attributes function is defined a bit below and and it takes any type of objects (empty interface) and returns a map, which is like a Hash or a Dictionary. The map has keys of String type and values of “Type” type. The “Type” type is defined in the reflect package. Inside the function, 23 then use the previously mentioned reflect package to check on the type and the name of each attribute and assign it to a map object. (note that I’m explicitly returning the map, but I could have done it in a more implicit way)

So there you go, that’s how you use reflection in Go. Pretty nifty and simple.

 

No Comments

Sayonara Sony

It’s now official, I have resigned from Sony Computer Entertainment America.

I was planning on posting this a bit later but since I was politely escorted out of the building by HR/security, I have more free time to let you know of my decision. Before you ask: No, my decision isn’t directly related to the recent PSN/Sony security breach events and no, I don’t have your credit card number. More seriously, my decision boils down to something much simpler & concrete: drive and passion.

The concept of drive is very well explained in this talk by Dan Pink and illustrated by RSA:

As explained, it is proven that when doing cognitive tasks, there are 3 factors that lead to better performance & personal satisfaction:

  • Autonomy: engagement vs compliance
  • Mastery: get better at stuff
  • Purpose: be disruptive but make the world a better place

 

The challenge is that when you work for a big corporation, you rarely see these factors applied. The amount of red tape, management overhead, lack of recognition and accountability result in a low drive by most employees. I think it was the first time in my entire career that I was told by a manager to care less about the quality and end result of our products.

The second important concept that I think is critical when looking at your career is passion. This topic is very well covered in Chad Fowler‘s book: The Passionate Programmer.

Here is a quote from Chad’s book:

Fulfillment and happiness don’t (often) come by chance. They require thought, intention, action, and a willingness to change course when you’ve made mistakes. [...] It might be a technology or business domain that gets you excited. Or, on the other hand, it might be a specific technology or business domain that drags you down. Or a type of organization. Maybe you’re meant for small teams or big teams. Or rigid processes. Or agile processes. Whatever the mix, take some time to find yours. You can fake it for a while, but a lack of passion will catch up with you and your work.

 

It’s hard to summarize Chad’s book into just a few sentences, but what I got from his book is that if, for whatever reason, you lose your passion for your job, you should move on to another place where you can be passionate and excel. In my case, I’m still very much passionate about video game development but I find my passion seriously affected by an unhealthy work environment, bad communication and a lack of desire to change things in concrete ways. As the saying goes, “People don’t leave jobs…”

 

What’s next for me?

If you are in the software industry you know that everybody is hiring and that there is a real shortage of talent out there. You probably also receive half a dozen emails per week from recruiters offering you “the best job ever” with an obscene salary. Well, I receive them too. But in this market, you and I can allow ourselves to be picky and to choose the right job for ourselves. By choosing the right job, we are going to be more passionate, more driven, more efficient and bring a lot more value to our employers, who, in return, will hopefully do everything they can to make sure we grow within the company with a strong desire to do even better. As I was considering what I would want to do if I were to leave Sony, I came up with a few ideas about a job:

  • I don’t want to live to work, but rather, work to live. (kind of an European cliché sentence)
  • It’s not about the job title.
  • It’s not about the pay check.
  • It’s not about how glamourous an industry  is.
  • What matters is :
    • the company culture.
    • the passion coming from the leaders.
    • the company’s ambitions.
    • how the company rewards and respects its employees.
    • the autonomy/trust given to the employees.
    • the purpose of the company and its potential to disrupt a market/change the world.
    • personal growth within the company.

 

Writing this list helped me realize that I was definitely not in the right place and helped me create a list of criteria to define what kind of job I should be doing instead. As I was thinking about all that, I was reminded of this quote:

“One should not pursue goals that are easily achieved. One must develop an instinct for what one can just barely achieve through one’s greatest efforts.” —Albert Einstein

This is probably a personality trait, but I like/need to be at the edge of my confort zone. I need to learn new things, experience new challenges. I need to try to solve unsolved problems. So part of me needs a company with a rich culture, a great a vision and leadership, but another part also needs to be allowed to think creatively, to push the existing boundaries, to challenge myself and to try to achieve things through my greatest efforts.

The challenge is that over the last 5-7 years I have become a Ruby specialist. I have learned to understand and master the language, learning its pros/cons and what goes on “under the hood”. I have built small and huge solutions for various domain spaces on top of Ruby. I have shared my knowledge giving talks, books, blog posts. I have also spent a lot of time expanding my own computer science knowledge, looking into other programming languages, frameworks, designs. My job at Sony was interesting due to the fact that Ruby is used in a quite singular way with very specific problems and a lot of C/C++ interaction. So while it is true that I am a Ruby specialist, I don’t like that label. I don’t like it because it’s very limiting. My goal is to solve problems and quite often Ruby is a great tool for that, but for some problems, it is not. So I need a job where my expertise is helpful but would not limit my desire to learn new approaches, languages and skills.

And this is why I will soon start working as a Code Alchemist in the LivingSocial R&D’s lab.

That might be a shocker at first glance. Going from working on video games to working for a daily-deal startup? It doesn’t seem like a very smart career move. To be honest, that was my first reaction. But LivingSocial’s VP of engineering is Chad Fowler (the author of The Passionate Programmer, mentioned earlier) and its VP of R&D is Rich Kilmer, InfoEther’s cofounder and recognized mad-scientist-coder. I’ve known Chad and Rich for many years, meeting at tech conferences that they organized or were invited to give talks to, and even getting to hack on some projects with Rich. So when they approached me to join them at LivingSocial, I wanted to know more about their own motivations, why I would be a good fit and how the company/job would rate against my list of criteria. We had long and honest discussions and the result is that I am excited to soon be working with one of the best teams I know of. More concretely, I will be working with Rich, Bruce and Michael in helping LivingSocial revolutionize the local market. LivingSocial is a fast growing and successful company with a strong focus on creating a great experience for both customers and merchants. The company’s vision is well defined and the desire to change the world the way we know it is palpable. Most of the founders have a technical background, they value good engineering practices and have created a nice, positive company culture. Chad has some really awesome, passionate and talented engineers on his team (too many to mention), for whom I have a lot of respect and with whom I look forward to working with.  I also value the fact that LivingSocial trusts and values me enough to let me work remotely. This is very important for me because it shows that my new employer really wants to work with me, trusts me but also is willing to embrace the challenges of having a remote team if that’s what’s needed to create the “right team”. After looking more deeply at what I need and what LivingSocial is, I believe that I can assist LivingSocial in making a very positive change to the way small businesses around the world are run. And I am looking forward to this.

 

25 Comments