I made the switch to Go a few years ago. For those who are on a similar journey as the author, or the author himself, I suggest spending time with the Go standard library and tools written by Rob Pike and Russ Cox to get a handle on idiomatic Go.
It’s clear the author still thinks in Java, not go. Saying Context ctx for example instead of ctx context.Context. Also DI, which is arguably not necessary at all in Go given how elegantly interfaces work.
I spent quite a lot of time using wire for DI in go only to really study the code it was generating and realizing it truly is code I would normally just write myself.
Edit:
Regarding stack traces, it turns out you don’t need them. I strongly suggest a top level error handler in Go combined with a custom error struct that records the file and line the error was first seen in your code. Then wrap the error as many times as you want to annotate additional lines as the error is handled up to the top level, but only that first point in our own code is what actually matters nearly all of the time.
DI is the idea that you should create your dependencies outside of the module / class / function that uses it and pass it in. This makes it easy to swap implementations.
DI does not require any framework and I would argue you can’t write modular code without it. Most likely you are doing DI even in your manually written code.
Let's take the case of an object which represents a simple CRUD web service that needs to talk to a database to get some data. Here is what it looks like without dependency injection:
func NewService(databaseHostname, databaseLoginSecret string) (WebService, error) {
databaseConn, err := databse.NewConn(databaseHostname, databaseLoginSecret)
if err != nil {
return WebService{}, fmt.Errorf("Failed to create database conn for WebService: %w", err)
}
return WebService{
databaseConn: databaseConn
}, nil
}
And here is what it looks like with dependncy injection: func NewService(databaseConn DatabaseConn) WebService {
return WebService{
databaseConn: databaseConn
}
}
This is the only concept: don't build your own dependencies, get them from outside.Ideally then there is a place in your application, possibly in `main()`, where all of the base services are initialized, in the required order, and references are passed between them as needed. This can include "factory" style objects if some of these need to be initialized on-demand.
DI requires that the deps come from outside, not that it's dynamically created. The opposite is that dependencies are created inside the unit. DI is about which part of the code owns the dependency. With DI it's some parent component, without DI it's the component itself.
DI with magic can simplify the management of component lifecycles, but it's entirely possible to do it without.
This is also the most common/preferred way Spring et alia implements their "framework-aided" DI, so that you can write unit tests easily without bootstrapping a Spring context (and it is just well-designed vanilla Java code).
OO and virtual functions can be implemented in C by looking up function pointers in a table.
Reference counting can be done by manually incrementing and decrementing references.
At the end of the day everything is compiled to assembly and the CPU doesn't care what ideology was in the programmer's head, except however much a given paradigm abstracts too far away from the underlying machine.
One can debug.PrintStack(), instead.
Replace Java with star and that statement still holds true (for some people).
Hence the statement that you can write FORTRAN in any language.
https://blog.codinghorror.com/you-can-write-fortran-in-any-l...
DI is necessary in every language that doesn't rely solely on global singletons. Passing dependencies as arguments to a function is DI.
What may not be necessary, are IOC containers automatically create objects and satisfy their dependencies.
One of the reason people needed a DI framework in Java is crazy "enterprise" configurability requirements and Java EE-based standards that required you to implement a class with a default no-argument constructor. If you're using a web framework like Jooby, Http4k, Ktor or Vert.x, you do not need a DI framework (source: we've written many modern Kotlin applications without a DI framework and we've had zero issues with that).
Of course, all of our non-toy Go applications are using dependency injection as well. Unless the code reviewer messes up, we won't let anyone configure behavior through globals and singletons.
No, it's so that you can have something else manage the lifetime and disposal of your services instead of doing this yourself. You don't have to be writing crazy enterprisey code to have the need for this.
I agree DI is simple, but 100% disagree that you can achieve this through a hand-rolled library without sinking a ton of wasted time.
This is still insanity, but the insanity comes from Java EE rather than the apps themselves.
In Node, I remember wrapping Promisesromises into objects that had a stack for pushing messages onto them, so that the creator of a Promise could mark the calling site, and creating another Promise within that promise would pick up the chain of call site names and append to it, etc. Logging that chain when a Promise fails proved to be very useful.
Sounds complicated. I don't use Node much (nor recently, for that matter), but when I write f/end JS I capture the chain of function calls by creating a new exception (or using whatever exception was thrown), and sending the `.stack` field to a globally-scope function which can then do whatever it wants with it.
Will that not work in Node?
Sometimes a function or method is called very many times so trying to log them all is useless. But at the same time it can be the case that there are multiple callers of the said function. Then looking at a stack we can log just the case of some specific call-chain calling that function.
goes on to suggest rolling your own buggy, slow, informally specified implementation of half of a stack trace printer
Yes, but the point is 1) you don't have to write it yourself and 2) it does 'the right thing' even if your junior dev straight out of BS CS wouldn't know how to write it.
There are, of course, caveats and not all frameworks are created equal and any tool can be misused. But I find DI very useful. Personally I'd recommend Uber's Fx framework and underlying dig library.
So instead of a stacktrace, you are - tracing the stack? Am I understanding correctly?
Because it just sounds like a manual version of stacktraces
Because it is. I don't understand it either.
I'd add that this is a last resort; errors should be handled and resolved as close to where they occur as possible. Having them bubble up to a central error handler implies you don't really want to do anything with it.
Exceptions pretty much make this the sane/default behavior, with rust-like ADTs with syntax sugar being close.
Is it that people who like this kind of stuff write microservices for deployment on Kubernetes clusters?
I can't speak for the ecosystem / developers though; there are plenty of examples where e.g. HTTP request handlers are wrapped in several onion layers of middleware itself. But, there's also an emphasis on keeping things simple and lightweight.
What kind of middleware are you thinking of when you mention things getting bogged down?
Please don't do this either. Read the stuff you want to log as additional attributes in your slog handler from the context, which you ultimately pass to `slog.*Context`
Then you go on to explain how to recreate them by hand.
This is like saying "I won't use source generators because it generates code I would normally write myself"
Like, yea no shit. THAT'S the point.
> internal Google style guide
Can we read this somewhere?"Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions."
Using context as a some sort of a mule is an antipattern.
> Using context as a some sort of a mule
I never saw the term "mule" used in this way. Very succinct!I made an issue for it: https://github.com/google/styleguide/issues/881
It is useful for some things, particularly middleware that needs to cross API boundaries.
> The biggest selling point of Go to me is that I can usually just look at anyone’s code and know what it’s doing
This is not possible in Java or C#? Both of those languages are so simple to grasp.Not really, no.
Apart from the cognitive burden of knowing the test framework in use, the DI tooling in use, the Mocking framework in use, plus all the annotations that each framework may want/need, almost none of which applies to the Go projects I've seen, the languages themselves have drifted away from simplicity.
I used to program in C# but left it for a long time and only recently looked at it again. C# is approaching C++ levels of syntax indecipherability.
It's actually converging with JS and TS
Small repo: https://github.com/CharlieDigital/js-ts-csharp
Edit: but I don't want to dismiss either because C# does cover a large gamut of use cases (desktop, 3D/gaming, COM interop, etc.) and it is true that in some use cases, you may see a wider range of keyword soup compared to just building web APIs (where I think it really shines; this is a .NET web API in 4 lines: https://imgur.com/a/simple-net-api-with-route-param-validati...).
Can you post an example of such new syntax? In my experience C#'s syntax is getting cleaner.
There is absolutely nothing more readable in Go than in Java, it's just classis familiarity (referencing the simple vs easy talk), I would even wager that too little expressivity will actively hinder code understanding.
(It's much easier to understand the intent of a complex stream API "pipe" than 4 nested for loops with ifs, with a bunch of dumb if errs pretending to be error handling).
Also, you are comparing a complex framework that solves 70% of your problem domain (at the price of a bit of a learning curve) with a vanilla Go project that only calls libraries. The exact same is more than possible with Java, it just doesn't make much sense in case of CRUD apps because better ways exist.
It definitely has more language features than Go, but by no means is indecipherable.
I find C# syntax to be quite crisp.
Go has some large frameworks, but the community frequently suggests they aren't needed and that the standard library is enough.
Granted, Go's testing library / setup is also a bit of a jump from regular Go code (especially things like table tests). But the assertions are just `if`s.
Sure, reinventing the wheel is fun, but if I can finish a whole project while the equivalent go code can finally return "Hello world", then I'm not sure it's a worthwhile tradeoff. Java is not anemic when it comes to its standard library, people moved to frameworks because a good deal of CRUD apps have to solve some of the same problems. Don't forget, the only silver bullet is reusing existing code.
Frameworks reverse who calls who, it is your code that will be called at certain points, not the other way around. Obviously, one has to learn a bit about the framework before touching one, blindly copy-pasting from stackoverflow/chatgpt is not software develolment.
Just use the dependent package directly. Initialize the package once using init() or Init(). Rely on the built-in package dependency resolver system in Go, which will catch cyclic dependencies, call init() in topo order, and other such things.
Test using monkey-patching. Stop using interfaces just to be able to swap a real thing with a mock implementation. These are all symptoms of writing Java in Go.
If you're ever writing Go and wish you had real classes instead of this deconstructed "mess" with struct types, methods, and interfaces, you're writing Go totally wrong.
[1] https://google.github.io/styleguide/go/best-practices#global... [2] https://google.github.io/styleguide/go/best-practices#provid...
TIL Go has monkey-patching.
But since it has monkey-patching, how is it statically typed? Or does Go monkey-patching amount to creating an instance of a defined-on-the-fly subclass?
The latter would be interesting, because Java lets you do this too -- conveniently "new up" an instance of a subclass that you define inline of a given class or interface (this used to be the easiest way to define callbacks, before lambdas came along), so this testing strategy is available to Java too, but seems not to be preferred.
Separate question: IIUC, monkey-patching is convenient if your test code directly needs to create a TestX instead of a real X, but what if you need the test double "deeper down" -- that is, you need an X that creates a Y that creates a TestZ instead of a real Z?
On the other other, there is a movement to remove such late binding/rebinding features from the Java platform. However, I think JVMTI is expected to remain supported if the agents are loaded ahead of time. Only on-demand loading of agents will be removed from OpenJDK.
That way AOT compilation becomes possible/efficient and dependencies can't hack into other packages in an unmaintainable way without explicit permission from the user, so that updating the JVM and dependencies will be even more streamlined.
This doesn't concern features that have been traditionally abused (such as reflection on core OpenJDK classes), but also harmless (from an encapsulation perspective) uses of JNI, and access to future features such as FFI/Panama. Justification for restricting those as well is not so much OpenJDK updates, I think, but that it could cause crashes that might be blamed on OpenJDK.
Java does have "agents", which enable arbitrary control of bytecode at class loading time -- bytecode in existing .class files can be transformed, or completely new bytecode generated on-the-fly. But generating bytecode just to replace a class with a test double would be insane.
From another comment I learned there's also a separate "Tool Interface" that can do this bytecode-replacement job, but again, it's a huge amount of tricksiness and bother for something more easily and clearly accomplished in source code with a boring old anonymous subclass. (Though it won't work if the class is sealed, or final, or your code uses reflection to check the class name, or...)
How would you construct an instance in a test that needs mock implementations?
Can you elaborate? What library do you use?
At least I hope that a context can be immutable throughout. I only see one variable in the documentation of the context package. Extending it with mutable fields, and mutating them to pass data between functions, would be something I'd never approve in a code review.
Man. This works. The context API allows/enables it. But I’d really recommend against passing data to functions via context. The biggest selling point of Go to me is that I can usually just look at anyone’s code and know what it’s doing, but this breaks down when data is hidden inside a context. Dependency injection is entirely possible without using the context package at all, interfaces are great for it.