Stop Fighting the Language (02/11/20)
Sometimes, there are new things added to languages that makes your work infinitely easier. You just have to spend the time to integrate it into your workflows.
For some reason, I learned about Go's type system and tried to shoehorn C++-style classifications into it. Along the way, I learned how to leverage the type system properly, but it's been a struggle trying to keep from falling back onto bad habits.
Example
An example of what I'm referring to looks something like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
In this example, there are a number of issues:
-
In order to fulfil the contract with the
SampleConverter
interface, the functions attached to the struct need to be a pointer. While this isn't terrible, it means that the value internally is inherently mutable, which isn't great. -
There's a random pointer shoved into the struct, named
SampleConverter
. This is very sub-optimal, as it bloats memory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
In this example, the solution is much cleaner and enjoys the following benefits:
-
The compiler can solve for the interface automatically and will apply a auto-pointer where needed.
-
The value stored within is immutable, as expected.
-
Inlined references to this value will only be stored on the stack or in the CPU's registers instead of in the heap, which means there's no memory cleanup.
There are so many places in gotracker that need this sort of cleanup. Fortunately, I made all the effects work off this model, but they're only accounting for a third of the whole codebase at best.