Sunday, December 5, 2010

Ubuntu Packages Please Get Your Act Together

I didn't intend to write another blog entry so close to the conclusion of my Week with Go series, but my experiences earlier today definitely warranted a rant. Installing the SpiderMonkey JavaScript engine for use as a stand-alone interpreter on Ubuntu 10.04 LTS doesn't sound like outlandish goal. After all, CouchDB ships by default as of 9.10 and it requires a JavaScript run-time. Technologies like node.js and v8 are pretty hot right now so there might even be a few alternatives to choose from, right? WRONG!
sudo apt-get install spidermonkey-bin
E: Couldn't find package spidermonkey-bin
There used to be such a package but apparently SpiderMonkey is "unsupported" now and was removed from the Universe repository.

Sorry Ubuntu. I'm not feeling the love for Rhino. It doesn't do JIT and runs slower than a one-legged sloth. Besides, I don't feel like installing ca-certificates-java, default-jre-headless, icedtea-6-jre-cacao, java-common, libavahi-client3, libavahi-common-data, libavahi-common3, libcups2, libjline-java, liblcms1, libnspr4-0d, libnss3-1d, openjdk-6-jre-headless, openjdk-6-jre-lib, and tzdata-java on my system.

I thought about installing it from source but then I'd lose the benefits all the experts say I get from using packages*. After a bit of searching I found some developer rolled a package that is available from a Launchpad PPA, so all I'd have to do is just add the repository!
$ sudo add-apt-repository ppa:launchpad/ppa
sudo: add-apt-repository: command not found
Sigh. add-apt-repository is provided by the package python-software-properties. The intuitiveness of it all is underwhelming.

It's great that PPAs exist and people volunteer their time to maintain them to fill the gap, but Ubuntu needs to pull its head out of its ass and get its act together. Ubuntu gained popularity because people were pissed at Red Hat, not by emulating OSX with moving its close buttons, adding boring purple artwork, or the Dropbox rip-off called Ubuntu One. It needs to focus on solving real problems, like developing better package identification/search solutions, finding better ways to convey information and their rational when dropping support for packages, and making the entire system user-friendly. If Ubuntu keeps disrespecting the needs of its user base then it's only a matter of time until the popularity-torch is passed to another distro.

* Benefits include unexpected dropped support, irrelevant dependencies and symlinks puked all over the system, inconsistent packaging conventions, headaches, dry-mouth, and an occasional ulcer.

Friday, December 3, 2010

A Week with Go, Day 5

Concurrent programming in Go makes use of coroutines, which are quaintly called "goroutines", and channels. Coroutines are functions executed asynchronously from the rest of your program, and channels are synchronous pipes through which the routines communicate. I had written a multi-threaded Kember Identity program in C a while back, and decided to rewrite it in Go to gain some exposure working with these features.

The Effective Go primer gives a hint of what goes on under the hood with coroutines in Go.
A goroutine has a simple model: it is a function executing in parallel with other goroutines in the same address space. It is lightweight, costing little more than the allocation of stack space. And the stacks start small, so they are cheap, and grow by allocating (and freeing) heap storage as required.

Goroutines are multiplexed onto multiple OS threads so if one should block, such as while waiting for I/O, others continue to run. Their design hides many of the complexities of thread creation and management.
Indeed, Go does a wonderful job of hiding the complexities of working with threads. Spawning the coroutine is as simple as prefacing the function call with go.
go kemberTest(start, tmp, ch)
Writing and reading values to and from a channel is done with <-. Both are blocking operations, so you don't have to worry about manually fumbling with locks to synchronize routines. The primer has this to say about channels:
Channels combine communication—the exchange of a value—with synchronization—guaranteeing that two calculations (goroutines) are in a known state.
if hash == curr {
    fmt.Println(hash)
    ch <- true
    return
}
No muss, no fuss. Coroutines and channels work together to make concurrent programming a breeze! I sat down expecting to stumble through getting my threads to communicate properly, but to be honest I spent more time working out the correct type castings throughout the program than I spent on the concurrency piece.

The asynchronous nature of coroutines with the synchronous nature of channels make it easy to write generators, too.
func fib(ch chan int64) {
    var a, b int64 = 1, 2
    for {
        ch <- a
        a, b = b, a + b
    }
}

func main() {
    ch := make(chan int64)
    go fib(ch)
    for i := <- ch; i > 0; i = <- ch {
        fmt.Println(i)
    }
}
After spending a week with Go I formed some good opinions and some bad opinions. The language has a dynamic feel with := and garbage collection which is nice, though I would have liked to have seen some more type inference being done by the compiler. An OO model that's not focused on hierarchical inheritance is a welcome change. Go is still rough around the edges and I wouldn't consider it ready to be a full-time development language for production projects just yet, but it has come quite a long way in the past year... and will undoubtedly continue to mature rapidly as an open source project.

Google did a disservice to Go when the language was first released by placing so much emphasis on compilation speed. The tech pundits and skeptics were right in questioning whether the world needed yet another language just because the current ones compiled too slow. Compilation is a function of the compiler after all, so if that was really the problem then a more appropriate solution would be to write a new compiler! But the pundits were ignorant in dismissing Go and believing there was no room for a new language. They failed to see an opportunity to re-examine old beliefs and explore now constructs. Many more would have taken Go seriously out of the gate if Google and early developers had touted its OO model and goroutines/channels instead of its compilation speed.

I can see myself using Go for a few side projects here and there, and perhaps larger projects in the future. Perhaps I'm just not comfortable yet with garbage collection in real-time and system-level programming yet, but I don't see it replacing my use of C; I choose C when a major need of my program is speed or memory and the unpredictable nature of a garbage collector works against those. But Go would definitely be a good choice for problems now solved using Java.

Thanks for spending the week with me (and Go); feel free to share your impressions of Go in the comments below. If you're interested, here's my Kember Identity code.

Thursday, December 2, 2010

A Week with Go, Day 4

Day 4 was spent learning about Go's take on object oriented programming, which I found to be a refreshing change from the likes of Java and C#. It's not type-focused; instead of relying on an object's type to know whether or not it offer certain functionality, the object will generally implement an interface. This mindset is not dissimilar to good JavaScript programming where feature detection is preferred over browser sniffing. The code doesn't care what something is (browser/object), just what it can do (functionality/interface).

The word "object" is probably a bit misleading since Go doesn't really have them in the traditional sense. There's no need to write a class definition as in Java, nor to instantiate an object literal like JavaScript. The programmer specifies a set of functions and Go's compiler deduces the relationships.
type Rectangle struct {
    width  float
    height float
}

func (r *Rectangle) Area() float {
    return r.width * r.height
}

func (r *Rectangle) Perimeter() float {
    return r.width*2 + r.height*2
}

func main() {
    r := new(Rectangle)
}
Here the Rectangle "object" is a pointer to a structure consisting of two floats. The Area() function can be applied as a method against any Rectangle to calculate an area, and the Perimeter() function can be applied to calculate the perimeter.

If I were to later specify the interface Shape which dictated an Area() float method and Perimeter() float method, then any Rectangle instances will automatically implement it. The compiler knows a Shape can have its area and perimeter calculated. A Rectangle can have its area and perimeter calculated; therefore, it must be a Shape.
type Shape interface {
    Area() float
    Perimeter() float
}
I appreciate Go's rejection of Java-style type-masturbation and focus on functionality. After all, code is a liability, functionality is an asset. It looks like Go will let me focus more on writing code which provides functionality instead of code that specifies type hierarchies rivaling Jesus' lineage in the book of Matthew.

Feel free to share your impressions of Go in the comments below and come back tomorrow for the final day's entry in the series. If you're interested, here's my shapes code with with Rectangle and Circle objects.

Wednesday, December 1, 2010

A Week with Go, Day 3

The first two days of tinkering and scouring helped me form an opinion of Go based on its syntax. To form a more-informed opinion I would have to write some more code and see how much resistance I experienced along the way. What features were missing? How was typing applied? I wrote a rudimentary version of Deal or No Deal, and slowly some of those meaningless sections in the language spec started taking on more meaning.

I decided to store the case amounts as an integer array (nobody likes the 0.01 anyway!) and came across my first bit of frustration and misunderstanding when it came time to shuffle the amounts.
cases = []int{100, 200, 300, 400, 500, 750, 1000,
    5000, 10000, 50000}
shuffle(cases)

func shuffle(arr []int) {
        rand.Seed(time.Nanoseconds())
        for i := len(arr) - 1; i > 0; i-- {
                j := rand.Intn(i)
                arr[i], arr[j] = arr[j], arr[i]
        }
}
The language spec says arrays are value types and slices are reference types. shuffle was doing what I wanted, but why was Go manipulating the array values if cases was supposed to be passed by value? I posted the question on Stack Overflow and it became clear that cases was a slice. I had written []int{} expecting the behavior of [...]int{}. Hopefully this will be the first and last time I make this mistake, but I have a feeling it won't be even with a correct understanding of what Go is doing. The syntax is just too similar. I don't understand why almost identical syntax was chosen for two different concepts here but different syntax was chosen for identical concepts with var = vs :=.

And I was lucky I only needed to shuffle a list of integer values; Go doesn't have generics, so I wouldn't be able to easily write a general-purpose shuffle function. It feels "dirty" to write shufflei(arr []int), shufflef(arr []float), etc. since the functions would all be identical except for their signatures!

The appeal of clean-looking code, novel looping, and an official formatting utility was waning because of issues and deficiencies more integral to the language and its implementation. Go is still nascent, but we shouldn't be revisiting these problems in a modern programming language.

Feel free to share your impressions of Go in the comments below and come back tomorrow for day 4. If you're interested, here's my Deal or No Deal code.