Sunday 5 November 2017

Active Object in Go

In Go, it is very easy to accidentally access the same data from different go-routines creating a race condition. Conventionally, you avoid this sort of problem with a mutex; and, in fact, you can easily do this in Go using sync.Mutex.

A way that is often better, and preferred in Go, is to simply avoid accessing the data from different go-routines at the same time. One way is to send messages (through a channel) to a confining go-routine responsible for all access and control of the data. By confining all access to a single go-routine no locks are required.

You can also confine use of a value by only using it within one go-routine at a time. This is idiomatically done in Go by transferring control of the variable through a channel, but I won't discuss that here as there are plenty of other articles about it. On another note, there are "low level" ways to do "lock-free" concurrency, using atomic operations, but that will have to wait for another time.


Avoiding Locks
“the main advantage
is that it simplifies
writing the code”

So what is the advantage of avoiding locks? Well, a great deal has been written about that (do a search on Google :), some of it misleading. In my opinion the main advantage is that it simplifies writing the code, by not getting side-tracked with other issues like race conditions. Using mutexes, in complex scenarios, is notorious for retaining subtle race conditions, or potential deadlocks or just performance problems such as unintentionally holding a lock while blocking on I/O.

Lock contention is often cited as a major advantage of avoiding locks but that is not really the issue. After all, using a confining go-routine (as described above) replaces lock contentions with contention for use of the go-routine. In fact proper use of locks is often more efficient than channels; it's just that it usually involves convoluted and/or repetitive code. For example, this is a typical scenario using locks:
  1. lock
  2. check "something"
  3. unlock
  4. do a lengthy operation based on knowledge obtained at 2
  5. lock
  6. check "something" again (repeating test at 2)
  7. update data using results at 4 (if "something" hasn't changed)
  8. unlock
However, there are some performance advantages. First, if many threads block on mutex(es) then thread-switching overhead becomes important. Even though the time for thread-switching is only measured in microseconds, if you have thousands of threads it can all add up. Of course, using go-routines lessens this effect, since Go multiplexes them onto a small numbers of threads, but it may still be significant.

Further, I think Go tries to run go-routines on the same core each time, which means that a confining go-routine may be better at maintaining the CPU cache which could have large performance benefits.


Active Object

A useful refinement of the confining go-routine is something that goes by many names but possibly the most common is the Active Object Concurrency Pattern. It is often used in server software involving a lot of simultaneous connections where the overhead of using a thread for every connection is too onerous. I first encountered this with Boost ASIO - the excellent C++ asynchronous I/O library. (Thanks Leon for introducing me to this and explaining it.)

However the code for Boost ASIO is complex, since it needs to create its own light-weight "co-routines" (called strands) to multiplex use of threads.  I wanted to do something similar in Go and I was amazed to find no advice on how to do this. It should be much simpler since Go provides all the requisite parts: go-routines (rather like strands), and channels of closures.

Active Object in Go can be implemented by a go-routine that reads closures from a channel (chan func() ) and executes them. This simple system means that all the closures, containing the code that accesses the data, are run on the same go-routine in the order they are posted to the channel. I guess the best way for you to understand this is with an example.

My example uses the quintypical example of concurrent coding - the bank account. First, we look at a race condition and how to fix it with a mutex, then using an Active Object. Of course, there are a few complications and things to be aware which I also explain and demonstrate in the code below.

Note that later code examples make heavy use of anonymous functions (closures), even nesting them. If you are unfamiliar with how they work you may need to read up on them first.


Race Example

Here is the code for a poorly-featured bank account that only allows deposits. Note that I could have written the Deposit() function more simply in one line (ac.bal += amt), but the code below is designed to trigger the race condition, which is there anyway, but the delay caused by the sleep should expose it. (This is one of the biggest problems with race conditions - they may be lurking but invisible - which is why you should get into the habit of using the Go Race Detector.)


type (
  Money int64 // cents
  Account struct {
    bal Money
  }
)

const Dollars Money = 100  // 100 cents to the dollar

// NewAccount creates a new account with bonus $100.
func NewAccount() *Account {
  return &Account{bal: 100 * Dollars}
}

// Deposit adds money to an account.
func (ac *Account) Deposit(amt Money) {
  current := ac.bal
  time.Sleep(1*time.Millisecond)
  ac.bal = current + amt
}

func (ac Account) Balance() Money { return ac.bal }


Now let's do a few concurrent deposits. Note that I tested all this code in a single (main) package. If you want to try it you could move all the "account" code to a separate package (eg bank), but then you need to call the function to create a new account as bank.NewAccount().


  ac := NewAccount()
  go ac.Deposit(1000 * Dollars)
  go ac.Deposit(200 * Dollars)
  time.Sleep(100*time.Millisecond)
  fmt.Printf("Balance: $%2.2f\n", ac.Balance()/100.0)


If you run the above code you will be disappointed to find that one of the deposits has gone missing. The deposits are run on separate go routines causing a race condition on bal.


Mutex Example

Luckily, this is easily fixed using a mutex to protect concurrent access to bal. We add a mutex to every account since if we had just one mutex for all accounts that would create a contention problem if many accounts were being updated at the same time.


type (
  Account struct {
    bal Money
    mutex sync.Mutex
  }
)

// Deposit adds money to an account.
func (ac *Account) Deposit(amt Money) {
  ac.mutex.Lock()
  defer ac.mutext.Unlock()

  current := ac.bal
  time.Sleep(1*time.Millisecond)
  ac.bal = current + amt
}

// Balance returns funds available.
func (ac *Account) Balance() Money {
  ac.mutex.Lock()
  defer ac.mutext.Unlock()

  return ac.bal
}


Note that Balance() now takes a pointer receiver, otherwise we would only be locking a copy of the mutex. We have to lock the mutex in the Balance() function even though it only reads from the value since there can be concurrent write operations. (If there are lots of reads and very few writes then a sync.RWMutex may be better than a sync.Mutex but that is another story.)


Active Object Example

OK that avoids the race condition by using a mutex, but how do we do this using the Active Object pattern? First, instead of a mutex we use a channel of functions. We also need to start a go-routine for each account in the NewAccount() function, which reads from the channel and runs the functions. Finally, instead of updating ac.bal directly in the Deposit() function we wrap the code in a closure (lambda function) and post this closure onto the account channel so that the account's go-routine will process it when it gets a chance.


type (
  Account struct {
    bal Money
    ch chan<- func()
  }
)

func NewAccount() *Account {
  ch := make(chan func())
  go func() {
    for f := range ch { f() }
  }()
  return &Account{bal: 100*Dollars, ch: ch}
}

// Deposit adds money to an account.
func (ac *Account) Deposit(amt Money) {
  ac.ch <- func() {
    current := ac.bal
    time.Sleep(1*time.Millisecond)
    ac.bal = current + amt
  }
}


Note that the unnamed function created in Deposit() and posted onto the account's channel is a closure (or lambda). Closures have the useful ability to capture variables from their enclosing scope (in this case ac.bal and amt).

Moreover if you make ch into a buffered channel, then the account can handle multiple concurrent deposits without ever blocking the calls to Deposit(). This means that transient spikes in activity on the account will be handled smoothly. Of course, a sustained onslaught of deposits, sent faster than they can be processed will eventually cause blocking when the channel buffer becomes full.


Returning Values

You may have noticed that the above code does not include a Balance() method. Before showing the code for Balance(), I need to explain how to "return" a value; because the closures are invoked asynchronously you can't simply use a function that returns a value. Even for methods that only update something we may want to return an error to indicate that something went wrong.

So how do we do it? We simply pass in a callback function (probably a closure) that is called when the operation completes (or fails with an error).

In the following code I have implemented the Balance() method but I have also replaced the Deposit() method with Add() since we are going to use it for withdrawals (allowing for negative amounts) too. Withdrawals may generate an error if there are insufficient funds in the account, so we pass a callback which can "return" an error.


// Adds transfers money to/from an account.
func (ac *Account) Add(amt Money, callback func(error)) {
  ac.ch <- func() {
    if ac.bal + amt < 0 {
      callback(fmt.Errorf("insuff. funds %v for w/d %v",
                          ac.bal, amt))
      return
    }
    ac.bal += amt
    callback(nil)   // successful transfer
  }
}

// Balance provides funds available.
func (ac *Account) Balance(callback func(Money)) {
  ac.ch <- func() {
    callback(ac.bal)
  }
}


Now here is some code that makes two deposits and attempts a very large withdrawal. Notice that for the deposits we provide a callback (closure) that does nothing - passing a +ve amount means the operation cannot fail so we ignore the possibility of an error. For the withdrawal, we check if there was an error and just print it out.


  ac := NewAccount()
  ac.Add(1000 * Dollars, func(error) {} )
  ac.Add(200 * Dollars, func(error) {} )
  ac.Add(-1e6 * Dollars, func(err error) {
    if err != nil { fmt.Println(err) }
  })
  ac.Balance(func(bal Money) {
    fmt.Printf("Balance: $%v\n", bal/100)
  })
  time.Sleep(100*time.Millisecond)


The first thing you may have noticed is that we don't have the keyword go before the call to ac.Add(), as we did above for ac.Deposit(). This is not necessary as most of the Add() function's code has been made asynchronous anyway. That is, the actual work is done in a closure posted onto the account's channel (for execution by the account's go-routine) allowing Add() to return almost immediately.

Notice also the call to Sleep() in the final line of code which is simply there to prevent the program exiting immediately. If you run the above in a main() function you may not see any messages. When main() returns the program ends and all active go-routines are silently terminated.  So the calls to Println(), executed in the account's go-routine may not get a chance to execute. Later I will look at how to wait for all pending operations on an account to complete.

A crucial thing to remember here is that the callbacks are run on the account's go-routine. This is important to keep this in mind since it is very easy to access a variable from the caller's go-routine in the callback. . If you need to send information back to the posting go-routine the callback can post to another Active Object channel as we will see.
“if you perform
a lengthy operation
... in the callback ...
delay other operations
… even cause deadlock”

Another important thing to remember is that if you perform a lengthy operation, or an operation that may block, in the callback then you will delay other operations on the account or even cause deadlock. In the example code above, I only call fmt.Printf() inside the callback but even that may be too much for a server that is handling hundreds of thousands of requests per second.


Transfers between Accounts

We have basic account features but more advanced features can introduce pitfalls to be aware of.  Here is the code for a method to transfer funds between accounts.


// WARNING: This code has problems

// TransferTo moves funds between accounts.
func (ac *Account) TransferTo(to *Account, amt Money,  
                              callback func(error)) {
   ac.ch <- func() {
    if amt > ac.bal {
      callback(fmt.Errorf("Insuff. funds %v for tfr %v",
                          ac.bal, amt))
      return
    }
    ac.bal -= amt
    to.Add(amt, callback)
  }
}


To understand what is happening here you need to remember that each account has its own go-routine. The code inside the above closure is executed on the "from" account's go-routine, the end of which calls to.Add() which posts to the "to" account's go-routine. The third parameter (callback) to TransferTo() is effectively a pointer to a function that is "captured" in the closure and passed on to to.Add() whence it is again captured and called to process the result of the final Add().

However, there are two problems with this code. First, you should not be able to transfer out more funds than are available (ie we need to check that -amt <= to.bal). The second problem is due to possible deadlocks - eg if two transfers are done simultaneously in opposite directions then each account may block the other - but we'll address that problem later.

How would we fix the first problem? My first thought was something like this:


// WARNING: This code has worse problems

// TransferTo moves funds between accounts.
func (ac *Account) TransferTo(to *Account, amt Money,  
                              callback func(error)) {
   ac.ch <- func() {
    if amt > ac.bal {
      callback(fmt.Errorf("Insuff. funds %v for tfr %v",
                          ac.bal, amt))
      return
    } else if amt < 0 && -amt > to.bal {
      callback(fmt.Errorf("Insuff. funds %v for tfr %v",
                          to.bal, -amt))
      return
    }
    ac.bal -= amt
    to.Add(amt, callback)
  }
}


Can you see a problem here? If not, think about which go-routine is used to run the above code.  All the code inside the closure (including the new code in red) runs on the ac account's go-routine, but it accesses to.bal, access to which should be confined to the to account's go-routine. (Remember that each account has it's own go-routine which is the only place where that account's bal should be used.)


// WARNING: There is still a problem

// TransferTo moves funds between accounts.
func (ac *Account) TransferTo(to *Account, amt Money,  
                              callback func(error)) {
   ac.ch <- func() {
    if amt < 0 {
      to.TransferTo(ac, -amt, callback)
      return
    }
    if amt > ac.bal {
      callback(fmt.Errorf("Insuff. funds %v for tfr %v",
                          ac.bal, amt))
      return
    }
    ac.bal -= amt
    to.Add(amt, callback)
  }
}


This fixes the problem with accessing to.bal on the wrong go-routine but as I mentioned before there is also a deadlock problem.


Deadlock

The first thing to note is that a channel in go has a fixed size; this means that any call to Add(), Balance() or Transfer() will block if the channel is full. If other concurrent requests can be posted to the accounts then the "to" account may be blocked waiting for the ac.Transfer() request to be posted which then blocks the "ac" account in the call to to.Add(). This causes a mutual deadlock between the two accounts.  A simpler scenario is where an account posts to its own channel causing itself to deadlock.

A solution to these problems is just to fire up another go routine like this.


// TransferTo moves funds between accounts.
func (ac *Account) TransferTo(to *Account, amt Money,  
                              callback func(error)) {
   ac.ch <- func() {
    if amt < 0 {
      go to.TransferTo(ac, -amt, callback)
      return
    }
    if amt > ac.bal {
      callback(fmt.Errorf("Insuff. funds %v for tfr %v",
                          ac.bal, amt))
      return
    }
    ac.bal -= amt
    go to.Add(amt, callback)
  }
}


This prevents TransferTo() from blocking and avoids the deadlock. The disadvantage is that we have no guarantees about when the request will be posted if the account channel is overloaded. In this case it may mean there is a delay between the "ac" account being debited and the "to" account being credited. In this example it is not a problem since the funds will eventually be transferred.

A solution that preserves the order of posted requests is to have two channels: one for external requests and one for priority requests (see priChan below) posted by an account to itself or to another account.


type (
  Account struct {
    bal Money
    pubChan, priChan chan<- func()
  }
)

func NewAccount() *Account {
  pub := make(chan func(), 2)
  pri := make(chan func(), 20)  // "private" chan

  go func() {
    for {
      if len(pri) > 0 {
        f := <- pri
        f()
      } else {
        select {
        case f := <- pri:
          f()
        case f := <- pub:
          f()
        }
      }
  }()
  return &Account{
    bal: 100*Dollars, 
    pubChan: pub, 
    priChan: pri,
  }
}


The idea is not to have any "circular" posts - that is any closures posted to a channel should never end up posting back to the same channel. In this way deadlock is not possible.


Conclusion

I hope I have demonstrated how easy it is to use the Active Object Concurrency Pattern in Go. As long as you understand how it works and are aware of the pitfalls it provides a simpler, and possibly more efficient, solution than using mutexes.

One pitfall is that, even though there is no visible locking, it is easy to create a deadlock if an Active Object's method posts (directly or indirectly) back to it's own channel, since channels have a fixed size once created. But this can be avoided as discussed above.

One thing that is very easy to do in Go is accidentally access a confined variable from the wrong go-routine. In another language like C it would be easy (though not portable) to use an assertion to verify that code is running on the right thread. Unfortunately, Go does not provide any identifier for go-routines (for arguably good reasons), but this hinders attempts to ensure that the code behaves correctly. Luckily there are (deprecated) ways to determine an go-routine's "indentity" which I will explore and keep you informed.

Also I have not explored how to wait for pending asynchronous operations to complete as I promised above. This post is long enough so we will look at that next time.

Sunday 22 October 2017

Improving Go Error Handling

Last time I mentioned that I had a way to improve error-handling in Go but I didn't get into the details. The idea is to use the compiler to eliminate all the boilerplate error-handling code but without the problems of full-blown templates.

But first, let's try to understand why Go is designed as it is. An obvious, and major influence was experience with C so I will look at my experience with error-handling in C. (If you are not familiar with C then you may be inclined to skip the following section but please at least skim it.)

C Error-Handling

C (and C++)...
are less forgiving

Generally, error-handling in C is poor to non-existent. This has probably caused more aggravation for users than any other software deficiency of the last few decades. That's not to say that C programmers are of a lower standard (probably the contrary :), just that most of the commonly used software was written in C (and C++) and these languages are less forgiving if you do not know what you are doing.

Here I share some of my experience with C, which is typical.

I started programming in C in the early 1980's and one of the biggest tediums (tedia ?) was having to write masses of error-handling code, and making sure the code worked. As an example, consider this code to copy a file. (I know there are simpler ways to copy a file but this sort of code was like a lot of C code I was writing at the time.)

bool copy_file(const char *in_name, const char *out_name) {
  FILE *fin, *fout;
  const size_t BUF_SIZE = 1024;
  char * buf;
  size_t count;

if ((fin = fopen(in_name, "r")) == NULL)
  {
return false;
}
  if ((fout = fopen(out_name, "w")) == NULL)
  {
  fclose(fin);
return false;
  }
  if ((buf = malloc(BUF_SIZE)) == NULL)
  {
fclose(fin);
fclose(fout);
return false;
}

  for (;;)
{
  if ((count = fread(buf, 1, BUF_SIZE, fin)) < BUF_SIZE)
{                                // WARNING: see below
  if (feof(fin))
break;

  fclose(fin);
  fclose(fout);
  free(buf);

  return false;
  }

  if (fwrite(buf, 1, count, fout) < count)
    {
fclose(fin);
fclose(fout);
free(buf);
return false;
  }
  }

  fclose(fin);
  fclose(fout);
  free(buf);

  return true;
}
Listing 1. C function to copy a file.

“most C
error-handling code
is never tested”

An obvious problem with Listing 1 is that the large amount of error-handling tends to obscure the essence of the code.  (Compare it with the same code without error-handling, in Listing 3 below.)  This sort of code is hard to write, hard to read and hard to modify.  Further, it is difficult to verify that error-handling code is correct; in fact most C error-handling code is never tested and causes all sorts of chaos in the field when the actual errors do occur.

WARNING: I should point out that Listing 1 (and Listing 2), despite attempts at thorough error-handling has at least two problems.  Can you spot them? Furthermore, production code should have more informative error handling - such as trying to diagnose, and inform the user why different errors occurred. For example, if the input file could not be opened was that because it did not exist, was not accessible or some other reason?

Part of the complexity of Listing 1 is due to all the fclose/free/return statements in the error-handling which are repetitive and error-prone (remember DRY). It would be quite easy to forget a call to free()  and cause a memory leak. In fact the code I would typically write (if the coding standards in effect allowed use of goto :) would be more like this:

bool copy_file(const char *in_name, const char *out_name)
{
  bool retval = false;
  FILE *fin = NULL, *fout = NULL;
  const size_t BUF_SIZE = 1024;
  char * buf = NULL;
  size_t count;

  if ((fin = fopen(in_name, "r")) == NULL)
  goto handle_error;
  if ((fout = fopen(out_name, "w")) == NULL)
  goto handle_error;
  if ((buf = malloc(BUF_SIZE)) == NULL)
goto handle_error;

  for (;;)
  {
  if ((count = fread(buf, 1, BUF_SIZE, fin)) < BUF_SIZE)
  {
  if (feof(fin))
  break;
  else
goto handle_error;
  }
  if (fwrite(buf, 1, count, fout) < count)
  goto handle_error;
  }
  retval = true;  // indicate success

handle_error:
  if (fin != NULL) fclose(fin);
  if (fout != NULL) fclose(fout);
  if (buf != NULL) free(buf);

  return retval;
}
Listing 2. Using goto to avoid repeated code.

Note that the Go language neatly addresses this problem with the defer statement as I mention later.

Now look at the same function (Listing 3) without any error-handling code.

void copy_file(const char *in_name, const char *out_name)
{
  FILE *fin = fopen(in_name, "r");
  FILE *fout = fopen(out_name, "w");
  const size_t BUF_SIZE = 1024;
  char *buf = malloc(BUF_SIZE);
  size_t count;

  while ((count = fread(buf, 1, BUF_SIZE, fin)) > 0)
  fwrite(buf, 1, count, fout);

  free(buf);
  fclose(fout);
  fclose(fin);
}
Listing 3. No error handling.

This is plainly much simpler than the previous versions (and fixes the major bug). This is why many examples you see in textbooks omit the error-handling code to make it easier to understand.

Unfortunately, a lot of production code is actually written like this!  Moreover, even more (95% or more) has inadequate error-handling to some extent.  Why is that?

  1. Blind following of example code from textbooks, as I just mentioned.
  2. Lack of awareness that special values indicate errors, due to C's use of "in-band" signalling. I discuss how Go addresses this below.
  3. Lack of awareness that some functions even return errors. For example, in Listing 1, the final fclose(fout) may return an error. (If buffered data can't be written to disk for some reason then fclose() will return an error.).  Unfortunately, Go does not really address this problem.
  4. The attitude (laziness?) of many C programmers. For example, many security threats have been caused by buffer overflow problems. Most C programmers are aware of the dangers of strcpy() but neglect using safer functions like strncpy().
  5. Poor reasoning. Sometimes you can ignore errors but often there may be subtleties of which you are unaware. For example, I have seen a lot of software that assumes you can write a file in current directory which is not always true
  6. Code changes made without full understanding of the existing code.
  7. Finally, occasionally, despite the best of intentions, errors are ignored by accident or oversight.

How Go Improves on C

Go has several facilities, such as the error type and multiple return values, that make error-handling simpler and safer than in C. (To be honest the standard C library's error-handling strategy, especially use of the global errno variable, could not be much worse.)

The error type

Go eschews the common C error-handling pattern of "in-band signalling". That is, in C, when a function returns a value of a certain type it reserves a special value of that type to indicate a failure. When returning an integer, -1 is often used, or when returning a pointer, NULL is used. You can see this above in the calls to fopen() and malloc() which can return NULL pointers. A different example in the above code is fwrite(), which indicates an error by returning a written count less than the requested count.

The are a few problems with in-band signaling:

  1. sometimes there is no spare value that can be used as the error value
  2. you often want to return more information than just that something went wrong
  3. it is easy to ignore the error return value and continue blithely
  4. it may not even occur to the uninitiated that there is a special error return value

An example of the problem (1) can be seen in the code above - fread() will return zero on error to indicate that nothing could be read, but zero is also returned when you attempt to read at the end of file, which, in general, is not an error condition. One way this is handled in the C standard library is to check errno after the call (remembering to ensure it is zero before the call); in the case of fread() you need to do a further call to ferror() or feof() to distinguish between an error and reading at EOF.

(2) The C standard library uses the global errno variable to indicate more about the nature of the error.  However, this is a poor strategy which has been discussed at length elsewhere.

(3) and (4) are common in C and the cause of countless bugs.

Go addresses these problems using the error type (and allowing functions to have multiple return values - see below). A function that may encounter an error returns a value of type error as well as its normal return value(s). If the error value returned is not nil then it indicates there was an error and the value can be further inspected to determine the exact nature of the problem.

Defer

Although it is rarely mentioned when talking about error-handling in Go, understanding how to use the defer statement is critical.

First using defer avoids lots of repetitive cleanup code (as seen in Listing 1 above).  Moreover, I believe it greatly reduces the chances of accidentally forgetting cleanup code, and makes it easier to visually inspect code to check that cleanup is done.  I have seen countless bugs in C code (and even created a few myself early on in my career) where some resource is allocated (eg file opened, resource handle allocated, mutex locked, etc) but then never released/closed/freed/unlocked causing a resource leak or worse.

In C it is easy to forget to free something because the allocate and free functions are necessarily called at different places (classic example of the DIRE principle). The problem is also often due to complex control flows or later code changes such as someone adding an early return from a function. Using defer in Go to free a resource immediately after it has been (successfully) allocated very neatly avoids these problems.

Though the creators of Go may deny it, I think that defer is inspired by C++ destructors (which inspired with/using statements of other languages).  As well as being called in normal return circumstances, destructors are called when an exception is thrown in C++ (during stack-unwinding); similarly defer statements are called when the code panics.

The addition of defer to Go is especially useful for error-handling but there are a few pitfalls for the unwary:

• Deferred functions are called at the end of the function not the enclosing block.
          (I expected behavior like C++ destructors which are called at the end of the block.)
• Only defer freeing of a resource after checking that it was successfully allocated.
• It’s common to see a deferred Close such as this:

if file, err = os.Open(fileName); err != nil { return err }
defer file.Close()


The problem with this code is that it ignores the error-return value from Close(). Generally, it should be written like this:

if file, err := os.Open(fileName); err != nil { return err }
defer func() {
if err = file.Close(); err != nil { return err }
}


Multiple Return Values

A function in Go can return more than one value. I believe that a reason, probably the main reason, this was added to the language is to allow a function to return a value and an error condition without resorting to C's in-band signalling due to the problems discussed above (especially problem 3).

Go forces you to explicitly say you are ignoring an error by using the blank identifier (a single underscore).  For example:

i,  _  := strconv.Atoi(str)

which converts a string into an integer. In this case if there is an error during the conversion then it is ignored, and i retains the zero value. However, there are some problems with this system.

First, even if you know an error will not occur, you cannot use the return value in an expression.  I often want to use the return value of strconv.Atoi() in an expression knowing that the string represents a valid integer (or just being happy with a zero value, if not).  It is tedious and error-prone to have to assign the return value to a temporary variable, which is why I usually wrap Atoi() in my own function which returns a single value.

A bigger problem is that you can ignore easily ignore an error return value when you are not interested in any of the the returned values. It is all too common to see Go code that ignores the error return value of functions like os.file.Close().

For example, this generates a compile error:

file := os.Open(fileName)   // compile error: multiple-value in single-value context

If you know the error will not occur, in a particular circumstance, then you can explicitly state that you do not want to use the error-return value like this:
when a function
only returns
an error in Go, it is
too easy to ignore it

file, _  := os.Open(fileName)

However, you can call Close() like this:

file.Close()         // compiles OK!!

whereas having to do something like this would be preferable (if we know that Close() cannot return an error):

_ = file.Close()   // ignore error from Close()


A Go Example

As an example, of how Go error-handling compares with C here is the same function as in Listing 1 but written in Go (or a language like Go), using defer and multiple return values.  Note that this is not real Go code as the standard file handling functions are different and Go has no need for anything like malloc().

func copy_file(in_name string, out_name string) error
{
  var err error
  var fin, fout *file
  if fin, err = fopen(in_name, "r"); err != nil {
  return err
  }
  defer fclose(fin)
  if fout, err = fopen(out_name, "w"); err != nil {
return err
}
  defer fclose(fout)

  var buf []byte
  if buf, err = malloc(1024); err != nil {
  return err
  }
  defer free(buf)

  for {
  if eof, err := fread(buf, fin); err != nil {
  return err
  }
    if eof {
  break
  }
  if err = fwrite(buf, fout); err != nil {
  return err
  }
  }
  return nil
}
Listing 4. Error handling in a "GO" like language

Comparing Listing 4 with Listing 1 you can see that there are some improvements, but it is still far from ideal when you compare it with Listing 3. You might argue that the only way to get anything like Listing 3 is to have exceptions added to the language - I agree that exceptions have advantages, but they also have negatives - so we take a slight detour to consider why Go does not have exceptions.

Exceptions

exceptions
simply can't be
... ignored!     
There are two major advantages with exceptions, plus a disadvantage.

Advantages

A. If you search on the Internet for the advantages of exceptions you find all sorts of things mentioned (eg the first hit at Google I get is to the Java documentation on exceptions). What they fail to mention is the most important one - exceptions simply can't be (accidentally or intentionally) ignored! This was the first thing that struck me when I first read of exceptions in
* Note that nowadays these sort of C bugs are sometimes detected in some way and the software terminated by the operating system but when I started using C on operating systems without hardware memory protection (eg MSDOS, AmigaDOS, etc) an ignored error could cause mayhem, eg: behave erratically, even corrupt its own data and save it to disk. It might also trash other running software, or bring down the OS!
Stroustrup's The C++ Programming Language, 2nd Edition as I had spent many painful years tracking down bugs of this nature in C code* - if an error occurs you throw an exception and the program stops, unless steps are taken to catch it.

B. Of course, the other major advantage of exceptions is reduced complexity (see Listing 3). The error-processing code does not obscure the "normal" control flow.  This makes the software more understandable and even easier to get right. And of course, it relieves the tedium of writing lots of similar, uninteresting code.

Disadvantages

From the above advantages you can see that exceptions are great to (A) ensure that errors are not ignored and (B) to make "normal" code easier to write and understand.  In other words they are great when:

A. exceptions are thrown and not caught (error causes program to terminate)
B. exceptions are never thrown (no error encountered)

The real problems occur when:

C. exceptions are thrown and caught

The reason is that exceptions are often thrown when you are not expecting it. At the point they are caught it is easy for the software to be left in an inconsistent state causing memory/resource leaks and even more serious bugs. In fact there are many examples of simple, seemingly innocuous, C++ code where an exception causes that most heinous of coding-crimes: undefined behavior.

This is not too serious if exceptions are used properly and sparingly but the last decade has revealed a new problem - the gross overuse and misuse of exceptions for normal control flow as seen in a lot of Java code.
To elaborate, you can write safe code using exceptions but it is hard. The trouble is you have to always be thinking about what exceptions could be thrown in addition to the actual problem that you are trying to solve. And the human brain is not good at multi-tasking.

Furthermore, exceptions and concurrency do not mix well. (Eg: see the section on Mismatch With Parallel Programming in Exception Handling Considered Harmful).  Go makes writing concurrent code easy, so it seems better to avoid exceptions in the language.

Go

So Go does not have exceptions due to their major problem (C above). Go attempts in other ways to obtain their benefits (A and B), but does does not do so effectively. My proposal is to enhance the Go compiler's support for error handling to obtain the benefits that exceptions give to A and B.

The Proposal

My proposal relies on the compiler generating some hidden code. (Alternatively, this could be done by some sort of preprocessing of Go code.)

In summary, I propose these changes to Go:

  • If a function is called which returns one or more values, the last of which is of type error, and
  • if that last returned (error) value of the function is not assigned or used AND
  • the calling function also has a (last) error-return value THEN
  • the compiler will automatically add code to check the error return value AND
  • if the called function returns an error then the calling function should return the same error
Returning tto our original example, Listing 5 has the same copy function as Listing 4 but with no error-handling, which is proposed to be implicitly added by the compiler.

func copy_file(in_name string, out_name string) error
{
  fin := fopen(in_name, "r")
  defer fclose(fin)
  fout := fopen(out_name, "w")
  defer fclose(fout)
  buf := malloc(1024)
  defer free(buf)

  fmt.Println("Copying", in_name, "to", out_name)
  for fread(buf, fin) != eof {
  fwrite(buf, fout)
  }

}
Listing 5 Copy function with implicit error-handling.

the compiler would generate code equivalent to:

func copy_file(in_name string, out_name string) error
{
  fin, err := fopen(in_name, "r")
  if (err != nil) {
  return err
  }
  defer fclose(fin)
  fout, err := fopen(out_name, "w")
  if (err != nil) {
  return err
  }
  defer func() {
    err := fclose(fout)
  if (err != nil) {
  return err
  }
  }
  buf, err := malloc(1024)
  if (err != nil) {
  return err
  }
  defer free(buf)
  _, err = fmt.Println("Copying", in_name, "to", out_name)
  if err != nil {
  return err
}
  for {
  tmp, err := fread(buf, fin)
  if (err != nil) {
  return err
  }
    if tmp == eof {
      break;
    }
  err = fwrite(buf, fout)
    if err != nil {
  return err
  }
  }
}
Listing 6 Same function showing compiler-generated error-handling.

In this way errors can be propagated up the call stack without the need for explicit error-handling code at each level. Even accidentally forgetting to check the error return value of a function like close() will automatically be handled.

Of course, at any level you can override the compiler generated code, if it's error-handling is insufficient. This is done by simply using the error return value.

Or, if you know the error condition won't occur then you can explicitly assign the error to the blank identifier to ignore it.

A further advantage is that functions which return a result and an error can be used in expressions like this:

calc(strconv.Atoi(str))

instead of:

tmp, _ := strconv.Atoi(str)
calc(tmp)


which avoids the use of error-prone temporaries and has the added advantage that if Atoi() unexpectedly does get an error that it will be detected and returned.

Auxiliary Proposal

In addition, I have a related, but independent, proposal.
  • If a function just returns an error then you must use it (or assign to the blank identifier)
That is, this code should generate a compile-time error:

file.Close()          // compile error: error return cannot be ignored

To explicitly ignore the error you must do this:

_ = file.Close()   // ignore error return value from Close

Combined with the above main proposal this makes code much safer. In fact a lot of existing code that ignores the return value of Close() will now be safer without any code changes! Of course, without my main proposal this proposal would mean modifying a lot of existing code, such as most uses of fmt.Printf().

Summary

Two of the biggest problems I found in decades of programming in C were:

1. code that ignored error return values, often with severe consequences
2. having to write lots of boilerplate error-handling code

Exception handling (as first implemented in C++) was a great boon in addressing both of these problems.  However, exception handling introduced problems of it's own (as mentioned above) and the creators of Go chose not to add exception handling to the language, which I endorse.

Unfortunately, Go's approach to error-handling is not that much better than C. It attempts to address problem 1 but does not do so convincingly.  For example, it is easy to accidentally ignore an error-return value from a function that only returns one value.

Problem 2 has been alleviated somewhat by the introduction of the defer statement, but it is still tedious and error-prone - the sort of thing that a computer can do. Many people, including the Go creators, have debated this subject at length but their proposed strategies can be as tedious as the problem and are not generally applicable (at least until generics are added to Go. :).

My proposal addresses both the above problems without using exceptions. It relieves the tedium of writing a lot of very similar code, and makes the code easier to scan, and hence less likely to have bugs.

The benefits are obvious from comparing Listing 4 and Listing 5 above.

It also has the added advantage that functions that return two values, like strconv.Atoi(), can be used in expressions when the error return value is not needed. Again this can make the code simpler, by avoiding error-prone temporaries, and easier to read.

Sunday 20 August 2017

The Essence of Go

The Go programming language - what do you know about it? I was looking for my next favorite language a couple of years ago.  I tried and rejected Go based on a fair bit of research. However, I have been working on a project for the last few months using Go and I must admit my initial impressions were wrong. Here I hope to describe what using Go is really like for anyone thinking of trying it so they don't jump to the same erroneous conclusions that I did.
“… what using Go is really like …”

Last year I mentioned here another new language, Rust, that I am very excited about (and which I hope to talk more about soon). Go is similar to Rust in many ways but Go is not a low-level language like Rust (despite what Google and others say). I would classify Go as a medium-level language on a par with C#. For one thing a language can't be low-level unless it allows control of memory allocations, but Go (like C#, Java and many interpreted languages) uses GC - ie, memory management is handled by the run-time using a garbage collected heap (I might talk more about that later).

Initially I decided to steer clear of Go, for several reasons but mainly due to its lack of support for templates (generics) - which BTW Rust does have. But now that I have used Go I think one particular aspect is brilliant - it makes programming simple (in a myriad of ways), even more so than C# (which I talked about last time).  And if you have read much of my blog you may have noticed my love of simplicity. I believe complexity is at the root of all problems in software development (see my very first post Handling Software Complexity).


Influences

Whenever I try a new language I quickly get a feel for its style - what the designer(s) think is important (performance, flexibility, safety, etc). I can also usually pick what other languages influenced it. But Go's style and influences confusing.
Go's style and influences are confusing

First, it's overriding premise seems to be to keep things simple (and most of the time it does that very well), but the motivation for this is a mystery. The initial impression I got was that it was that everything was done "on the cheap" - that is, the Go creators just found it too hard, or too time-consuming, to think about adding exception handling or templates or whatever. This is clearly wrong when you consider some of the other features that are present. I next formed the opinion that it was based on an intense dislike of C++, so anything that Bjarne Stroustrup invented was simply rejected out of hand. My current (final?) impression is that the creators of Go consider the average programmer to be lazy and incompetent so everything is kept as simple and safe as possible (though sometimes making things safer detracts from simplicity as we will see).
“ …making things safer detracts from simplicity…”

Go's influences are many but as a generalization I would say that Go is a bit like a simplified C#, with all the C++ derived stuff removed, plus some additional features that support concurrency. For example, it has features similar or the same as these from C#: GC (memory management), lambdas (called closures in Go), metadata, reflection, interfaces, zero initialization, immutable strings, partial classes, extension methods, implicit typing (var), etc. And like C#, Go also tries to avoid lots of the problem areas of C/C++ such as expressions with undefined behavior.

Go is like C# with the C++ stuff removed
On the other hand almost all the things that C# inherited from C++  Go completely discards - like generics, exception handling, operator overloading, implicit conversions, and even classes and inheritance.

However, there are a few more things to Go that seem to be new or come from elsewhere.  One of the most interesting is its support for concurrency, including channels which I first encountered in Occam about 25 years ago. And, of course, like all popular modern languages Go is heavily influenced by C and C++ (though in the case of C++ the influence is in the form of avoidance).  Let's look at these influences just a bit more.

Safer C

Go has strong links to C, ostensibly because Google wanted a modern alternative to C. I think a big reason is that one of the Go architects is Ken Thompson who (along with Dennis Ritchie) created the C language (and the Unix operating system) and even precursors to C in the 1960's.

The syntax of Go is obviously derived from C, but there are many "improvements" to avoid problems that many beginners in C encounter. A good example is that there is no automatic "fall through" between cases in a switch statement which is a perennial source of bugs in C. On the other hand side-effects in expressions have been removed (eg, no assignment chaining etc) which is bad (see below).

Most of the problems with using pointers that C is notorious for have been eliminated by disallowing pointer arithmetic and by automatic memory handling using the garbage-collected heap.

Another common problem for beginners in C is due to uninitialized variables which can lead to bugs which are almost impossible to track down due to unreproducibility. Go's solution is the "shotgun" approach where everything is guaranteed to be initialized to a "zero" value.  This is good for reproducibility but introduces its own problems as I discussed in Shotgun Initialization.

Finally, I should mention that Go tries to address perhaps the worst problem of most C code (yes worse than the above problems!). This is the problem that there is an enormous amount of C code that ignores error conditions or does not handle them correctly. Go has a more systematic approach to error handling but, in all honesty, it is only marginally better than the C approach. Now I am not saying that Go should have exceptions and I understand and agree with the decision not to have them (even though it effectively does have them in the form of panic/recover). All I am saying is that Go should do something about relieving the tedium and complexity of C-like error-handling and in fact I have a proposal to do just that - more on this later.
“Go error-handling is
only marginally better than C”

In summary, the designers of Go have honored the age-old tradition of finding ways to improve on C.  Some of the improvements are actually useful but some are just denigrating to competent programmers.

Occam

Go is the first language I have encountered since Occam to use the brilliant idea of communication between concurrent processes using "channels".  Apparently channels are heavily used in Erlang and other languages that I have not had the fortune to use.  However, at one time (more than 25 years ago) I was very interested in the Inmos Transputer which you can read more about here but basically it was designed to allow multiple CPUs to be hooked together easily.

Occam had other features which I thought were going to be very important such as the ability to say whether instructions could be parallelized or must be run sequentially.
I became interested in the Transputer as it was a little like my own (even more way-out) idea for a bit-oriented processor. At the time single chip CPUs were 8 or 16 bit.

My thinking was that there large benefits in moving to single-bit processors which read from memory, and other CPUs serially - ie, one bit at a time.  Each CPU would be like a neuron. They could be hooked together to make something more powerful.

The industry successfully advanced in the opposite direction and soon 32-bit processors (and now 64-bit CPUs) are the norm. I'm not sure that this was the right direction. Maybe one day single-bit computers will find a place.

At the time I thought the software industry needed to embrace multi-threading (or multi-tasking as it was called then). At the time even the major operating systems from Microsoft and Apple did not support multi-tasking (using a kludge called "co-operative multi-tasking). Unfortunately, it was another decade before mainstream operating systems and languages were supporting multi-threading.

It's a shame that the Transputer and Occam never became popular. I think they were ahead of their time.

Not C++

As I said above I think one of the main influences on Go is that it avoids anything invented by C++. Here is a list and my opinion of whether that is good or bad.
  1. No support for inheritance, ie. no vtables etc, as used in compiled OO languages. This is not a bad thing, since inheritance is over-used, badly used and even when used well there are simpler alternatives. When required, Go has mixins (struct embedding) and interfaces, which are perfectly adequate.
  2. No templates. Templates (which made possible the amazing STL) are the thing I like most about C++.  This is a bad thing.
  3. No exceptions. I appreciate the argument for no exceptions, but I wish the alternative provided by Go was better. (Rust has no exceptions, but handles errors better using algebraic data types.) Go tries to improve on C's error-handling (which is very bad) but it is almost as easy to ignore errors in Go as C and the tedium of creating masses of error-handling code is back. Not being one to simply criticize, I propose how to improve Go's error-handling below.
  4. “I propose how to
    improve Go error-handling”
  5. No namespaces. Go has a similar concept of packages (sort of like a combination of assembly and namespace of C#). Unfortunately, packages can't be nested, which is limiting.
  6. Const was one of the simplest and most brilliant inventions of C++. I can't believe Go (and other modern languages) even consider leaving it out.
  7. No public/private/protected keywords. Go has a system where capitalized variable names are public, but a lower-case first letter means it is private to the package (a bit like internal in C#). This is simple but I am undecided whether it is sufficient.
  8. No user-defined operator-overloading. (Of course, like most languages there is operator-overloading for built-in types.) I don't really miss this.
  9. No function overloading (except you can overload methods with different receiver types - otherwise interfaces would not work). I miss this ability but I guess it is not essential.
  10. No optional parameters. I understand the problems of optional parameters, but they are rarely seen in practice. Not a biggy but the alternatives in Go are all error-prone and/or tedious to implement.
  11. Go eschews the C++ philosophy that you should be able to create user-defined types that are as simple and flexible to use as the built-in types (eg see 7 above). Some people hate this about Go, but personally I am not that fussed as long as it gives me everything I need to do the job simply and effectively (which it usually does)
  12. There is nothing as flexible and useful as the STL.  This is bad.
  13. One thing Go does use that comes from C++ is the // end of line comments. (Maybe the Go designers were not aware where that came from :)
In summary, leaving all the C++ stuff out greatly simplifies things (and I don't like a lot of the complexity of C++ either, as you may have guessed from some of my previous posts). However, I think the designers of Go may have thrown out the baby with the bath-water. In particular, I think templates (generics) and const are essential for any modern language.

Simplicity

Leaving out lots of features found in C++ and other languages makes Go programming simpler, but there are a lot of other niceties. Here is a list of all the things I like about Go.
  • Simple Builds Probably the best thing about Go is how easy it is to build a project. In the past (on C projects) I have spent hours or even days trying to sort out problems with header file inclusion, linking or even run-time problems due to incompatible struct member alignment, not to mention DLL Hell. C++ improved on C by using name-mangling so the linker could catch many mistakes. Then C# (actually .Net) further alleviated build problems using metadata to completely describe how to attach to an assembly. Go takes this a step further and makes building software quick, painless and trouble-free.
  • Integration I have always found integrating an open-source library into my own project or even downloading and building a complete application time-consuming and frustrating. (For example, I have spent weeks trying to streamline the build process for my own project which uses several open-sources libraries - see HexEdit.) In Go you simply use go get which finds and installs an open-source project and dependent projects so you can start using it straight away.
  • Compilation Speed Go's build speed is amazing (mainly because the metadata for a package also stores all info about its dependent packages). I never used to think build speed was that important since you can take a break while the project is building. However, Go's almost instant builds makes things possible like the IDE checking your code for all errors (not just syntax errors) as you type, which is great.
  • Type Safety Because of the quick build speed developing with Go has the feel of using an interpreted language like Python. The problem with an interpreted language, though, is that a lot of errors aren't found until you run the program. Go on the other hand catches many errors at compile-time resulting in greater confidence that the code will run without error.
  • Memory Management Another huge tedium in many C programs is keeping track of heap memory and knowing who has to free it. And, if you get it wrong then you can have memory-leaks, double-frees and even nastier problems such as overwriting memory that is used for something else. Go avoids all of this by using a garbage collected heap while somehow avoiding any major performance hit. (My guess is it makes typical code about 30% slower, but at least it does not suffer from the large pauses that you see in multi-generational GC systems like C#). Rust, BTW, does not use GC, having an even better system that allows it to track and free used memory (or anything) automatically.
  • OO One of the best things about Go is its support for inheritance - there is none. I have spent decades trying to remember all the intricacies of C++ inheritance (and still forget things). Go is simple but has all you need in interfaces and mixins for most modern design patterns. There are some inheritance-based design patterns, such as the template pattern (see Template Method Pattern) which you would not implement in Go but in my opinion these are not good design patterns anyway.
  • Concurrency Many forms of concurrent programming are greatly simplified with the use of go-routines and channels, as I mentioned above.
  • Closures Some narrow-minded people claim that Go is not a modern language because it does not support any modern features like OO, generics and exceptions. This claim is discredited by its support for closures - something that did not even make it into C++ (as lambdas) until 2011. Though not as powerful (ie complicated) as lambdas in C++ they are simple and adequate for use with modern design patterns.
  • Interfaces Interfaces in Go are simpler and more flexible than other languages like Java and C# or the abstract base type of C++, since a type does not need to explicitly state that it implements an interface. People have mentioned complications with this system but in reality it works fine.
  • Information Hiding Go has a very simple system of denoting that a value is visible outside a package. If the identifier starts with a capital letter it is visible (called public in C++, C# etc), otherwise it is only usable inside the package (like internal in C#). Once again this is simple and effective.  I have at times found this cumbersome when I want to hide parts of a package from other parts but I think a refinement that avoids this problem (and may be a better design in general) is to have small "internal" packages.
  • Unit Tests If you have read my blog you know that I love Unit Tests (see my posts from the end of 2013 and the start of 2014 such as this). I have tried different C# and C++ Unit Test frameworks and they can be tedious to understand, set-up and start using. In contrast, the unit test framework that comes with Go and is very easy to use. Note that the name "automated package tests" is preferred (I'm not fond of the term unit test either but it seems to be the term commonly used).
  • Code Coverage A very good thing to do is run code coverage tests on your Unit Tests to ensure that all or most of the code is tested. (Note that even 100% code coverage does not mean you have no bugs but it is a good indicator of how thorough your tests are.)  Despite the benefits, I rarely ran code coverage checks until I started using Go simply because it was too hard. Go makes it easy to get simple code coverage statistics and not that much harder to do even more sophisticated analysis.
  • Benchmarks I use benchmarks a lot, for example to check the performance of a function or compare algorithms and have created my own C++ classes for this purpose. Go comes with a simple, flexible, and effective benchmarking system which can even be used for timing concurrent algorithms.
  • Profiling Profiling allows you to find performance bottlenecks in your software.  Go has built-in support for profiling too, though I have not yet needed to try it.
  • Identifiers Finally, though this is more the culture of Go than the language per se, but I really like the emphasis on short, simple (but meaningful) identifiers instead of some of the monstrosities you see in Java and other languages. See Long Identifiers Make Code Unreadable for more info.
Complexity

Despite its emphasis on simplicity Go does not always succeed. Many features seem to be designed to make things simpler for "beginners" but end up making things more complex for those who know what they are doing. I am all in favor of making things safer but it should not get in the way of competent developers.  Here are a few examples:
  • Side effects Expressions in Go are based on C expressions but (most) side effects have been removed (ie the operators ++, --, =, +=, etc). I guess this is to avoid expressions with undefined behavior that novices often write in C (like a[i] = i++). The consequence is that things that are easily and sensibly expressed in C/C++ cannot be in Go, often requiring use of temporary variables and more lines of code. This makes code more complex and harder to read. [Note that function calls can still cause side effects in Go expressions resulting in undefined behavior - eg, see this.]
  • Operators Similarly, the ternary (?:) and comma operators are not supported (plus maybe others I have not noticed yet). This cuts down the large and confusing precedence table of C, but makes it painful to produce concise and easily scanned code.
  • Map Iteration Order If you iterate over the elements of a map in Go the order of elements is deliberately unpredictable to prevent someone depending on the order. When I first read of this I thought it was an interesting idea, but what idiot would depend on the order of elements from a hash table?!!  I didn't really foresee any problems with it until I came to debug a problem with data from a map. In that circumstance it is an absolute pain to restart a debug session and find your way back to the same point.
  • Unused Variables One of the biggest annoyances is that the Go compiler won't under any circumstances allow the code to build if there are unused variables or unused imports. Now this is great for finished code but is a complete pain in the q*** when you are writing, testing or debugging.  The justification for using errors and not just a warning is (from the Go website) "if it's worth complaining about, it's worth fixing in the code".  I agree entirely that it's worth fixing just NOT RIGHT NOW. Perhaps this problem can be addressed with a good IDE and better debuggers but it needs urgent addressing.  Here are some examples to demonstrate the problem:
    • I accidentally paste some code into the wrong source file and the IDE (Gogland in this case) "kindly" adds a dozen imports at the top of the file. After I delete accident, the code no longer builds and I have to manually go and delete the bogus imports.
    • I add an import I know I will need and save the file and the IDE (VSCode in this case) "kindly" deletes the unused imports for me - annoying.  Later on when I use the imported function the IDE can't seem to determine how to re-add the import and I have try to remember where it was and add it again manually.
    • I declare a variable and the IDE draws a red squiggle under it to indicate an error. So I click on it to find it's just trying to tell me it is unused. Of course, it's unused I just declared it!
    • I want to see the value of an expression while testing so I assign to a temp variable so I can inspect it in the debugger but then the compiler won't even build the code.
  • Shadowing A source of bugs (in C/C++, Pascal/Delphi, Java, Python, Go and other languages that allow it) is shadowing, where an identifier in an inner scope hides the same name in an outer scope. For example, you might add some code with a new variable which changes the behavior of code at the same level which uses an outer variable of the same name.  In decades of programming in the above languages I have encountered bugs caused by this rarely but Go seems to make it much more likely because of the special if statement and how easy it is to use ":=" instead of "=". Go would be safer if it disallowed shadowing, like in C#, or the compiler could at least warn about it (as many C compilers do).
  • Assertions One of the first things I discovered about Go is that it doesn't have assertions.  (There is even a dubious explanation of this in the official Go FAQ.) I love assertions as they have saved me (literally) years of debugging time but I admit with the advent of exceptions and unit tests they have less use. Luckily, Go actually does have them under the name of panic.
    • - C: assert(a > 0);   // meaningful explanation
    • - C#: Debug.Assert(a > 0, "Meaningful explanation");
    • - Go: if a <= 0 { panic("meaningful explanation") }
  • Exceptions Another thing that there has been a lot of complaint about is Go's lack of exceptions. Admittedly, there are many complexities caused by exceptions (such as very subtle undefined behaviors in C++) but I think it is more a reaction against the rampant misuse of exceptions in much Java code (either that or because modern exception handling was essentially a C++ invention and we don't want anything from C++ in Go :). But again we discover that Go does have exceptions but uses the keywords panic and recover, instead of throw and catch.
  • Error Handling So Go does have exceptions (ie panic/recover) but according to the Go ethos (ie, autocratic pronouncement) this mechanism is only supposed to be used for handling software failures (ie, bugs) not errors. The problem with this is that the distinction between a bug and an error is not always straightforward (eg, see Error Handling vs Defensive Programming in my Defensive Programming post); moreover the Go standard library itself often uses panic in situations that are clearly errors, not bugs. Go does have a few tricks (like defer, multiple-return values, the error type, etc) that make error-handling a bit easier than in C, but the simple fact is that in many situations (and without using panic) error-handling in Go can be a mass of complex, repetitive code. (Of course, Rob Pike and others deny this and demonstrate approaches that are unconvincing, being either just as complex or not universally applicable.)
  • Reference Types Go has pointers but it also has reference types (slices, maps, interfaces, chans, and functions) and the way reference types work is complex. For example a nil slice is treated exactly the same as an empty slice (except when you compare the slice to nil, of course) - and these sorts "split personality" behaviors lead to confusion (like arrays and pointers in C). You can also treat nil maps the same as empty maps except that you can't assign to an element of a nil map.
  • Value/Pointer Receivers The rules about when receivers are converted is confusing. Moreover there seem to be contradictory conventions: (1) use a value receiver for "const" methods and a pointer receiver for methods that modify the receiver (in lieu of "const" methods - see Not C++ point 5) and (2) use a pointer for large types (such as a large struct or an array).
  • Implicit Typing Implicit typing is achieved very simply in Go by using := instead of = for the first use of a variable. (Implicit typing has become very popular - int recent years it has been added to C# [var], C++ [auto], Rust [let] etc.). However, my experience is that I am continually adding/removing explicit declarations, converting between = and := and moving statements into or out of the initialization part of if statements.  This (along with shadowing mentioned above) makes refactoring code tedious and error-prone.
  • Memory Allocation Performance One thing that makes me a little uncomfortable is not knowing where the memory for a variable is coming from. In other languages you know if memory is being allocated from the stack or the heap; but in Go you just have to trust the compiler. I must admit that I have not yet encountered any performance problems but I can't shake the nagging feeling that I (or someone else) may make some innocuous code change and suddenly a lot more memory allocations need to be done from the heap. (My benchmarks have shown that this could slow them by more than 20 times!!)
  • Unit Tests Tests are so easy to write but there is one fatal flaw - tests are part of the package. Anyone with any experience of unit testing knows that tests should only test through the public interface (ie Go automated tests should not be part of the package) otherwise test maintenance becomes far too burdensome (see White Box Testing).
  • Formatting Having programmed in C and syntactically similar languages for almost 4 decades I have encountered a lot of different code formatting and debates on the merits thereof. Personally, I have always strictly conformed to K&R styling rules (even including the slight variations with the release of the 2nd edition of the book) with one important exception - I always place an opening brace on a line by itself. I started doing this in C in the mid-1980's and have been doing it ever since (in C/C++/C# etc). It makes the code easier to scan and I believe it has avoided numerous bugs and build problems by doing this.

Conclusion

I started writing this post many months ago and it keeps changing as I learn more about Go. I have now been using Go for almost six months. I have really found that Go makes life so much easier than any other language I have used, in many many areas. On occasion I yearn for an STL container or algorithm but generally you can do a lot of useful stuff in Go.

That said, there are a few things that I really don't like. Possibly the main one is the condescending attitude of the creators of the language. (I have also detected this to different extents in Smalltalk, Pascal, and Java.) In fact one of the things that I believe turned programmers away in droves from Pascal and towards C in the 1980's (me included) was treating programmers like idiots. Note that I am all in favor of making languages safer, as everyone makes mistakes, but not if it gets in the way of doing things properly.

I guess a good example of this is the fact that it is mandated exactly how code should be formatted. If you get the formatting wrong the code won't even compile. To be honest, I actually like the formatting rules, except for one biggy - that a left brace cannot be on a line by itself, but must be a the end of the preceding line. This convention (from K&R) is an anachronism from a time of paper terminals. In my experience it makes code hard to read and leads to bugs. (In fact I seem to recall Brian Kernighan stating in an interview that the only reason they chose this convention was to keep down printing costs in the original edition of The C Programming Language.)

On a practical note, Go does a good job of avoiding many errors that occur in C. However, in one area, it greatly magnifies the problem - Go makes it extremely easy to create bugs by accidentally shadowing a variable. (In fact just last Friday I discovered another bug of my own due to this.) Something urgently needs to be done about this.

Finally, I just realized that I was going to explain how Go error-handling could be improved, without resorting to exception-handling. Writing error-handling code in Go, like C, is tedious - the sort of job a computer should do. I have a proposal to relieve the tedium but I've rambled on long enough for now so I will have to leave you in suspense until next time.

Next Month: A Proposal for Better Go Error-Handling