8 ms·
> But there are obviously work around solutions in the Go ecosystem. It uses the Context ctx, which we pass around functions in order to juggle data around in t
by bryancoxwell 2y ago
> But there are obviously work around solutions in the Go ecosystem. It uses the Context ctx, which we pass around functions in order to juggle data around in the application.
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.
- MrDarcy 2y agoI hit this point in tfa and had the same comment. Please don’t pass things around in a Comtext. Maybe stash a slog logger in there, but that’s about it. 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.
- arnath 2y agoThis comment is about a very minor part of what you said, but isn’t the whole point of a DI framework to write code you’d have written anyway to save you time?
- MrDarcy 2y agoI was writing code similar to how the popular int13 kubelogin kubectl plugin works, which also uses wire for DI and is organized as a clean architecture repo. In that particular case I found both the clean architecture and the wire DI to add more layers of abstraction, which took more time to comprehend, write, and maintain than jettisoning both and doing it with idiomatic Go.
- bcrosby95 2y agoDI frameworks save you from writing trivial code, and it masks dependency insanity. This is why I don't use it even in Java. If the codebase gets to the point where a DI framework is really useful then you've fucked yourself over.
- unscaled 2y agoTo be fair, traditional Java EE apps often required a DI framework, because you couldn't control the main entry point of the program, and the entry point to your code was a class with a default no-argument constructor. This is still insanity, but the insanity comes from Java EE rather than the apps themselves.
- mukunda_johnson 2y agoI prefer stack traces in errors. It's gives so much more automatically so you don't have to worry about manual annotation. Stack traces and debug logs are the way to go. I like to use panics for exceptional conditions just for the convenient escape with the stack trace.
- ignoramous 2y ago> I like to use panics for exceptional conditions just for the convenient escape with the stack trace. One can debug.PrintStack(), instead. https://pkg.go.dev/runtime/debug#PrintStack https://pkg.go.dev/runtime/debug#PrintStack
- nine_k 2y agoThe exact stack trace may not be very necessary, but tracing the chain of calls, especially async, can be hugely helpful in troubleshooting, performance tracking, etc. 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.
- lelanthran 2y ago> 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?
- galaxyLogic 2y agoI believe it does. Creating a new Error-instance to learn what the current stack is a bit hacky, but it can be useful, even when there is no error. The code can reflect on who is calling it. 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.
- nesarkvechnep 2y agoI’m yet to see a former Java developer who uses the idioms of the language they currently use. They all just write Java in a different language.
- vram22 2y agoThat is a function of the developer, not of the language, i.e. f(dev), not f(lang) ;) 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-language/ https://blog.codinghorror.com/you-can-write-fortran-in-any-l...
- vram22 2y ago[flagged]
- mavelikara 2y agoThis isn’t anything special about Java. A determined programmer can write Fortran in any language.
- akoboldfrying 2y ago> Regarding stack traces, it turns out you don’t need them. goes on to suggest rolling your own buggy, slow, informally specified implementation of half of a stack trace printer
- _w1tm 2y ago> 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. 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.
- RussianCow 2y agoIf you're doing "dependency injection" by just passing arguments to functions/modules, you're not really doing dependency injection—you're doing "dependencies" without the "injection" part. I'm not saying that DI necessitates a ton of magic, but you need at least a small framework for specifying dependencies and injecting them into your modules dynamically.
- cryptos 2y agoBut that "framework" could be a simple factory function.
- com2kid 2y agoDesign patterns are independent of the implementation technology. 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.
- lucumo 2y agoNo, that's wrong. 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.
- eximius 2y ago> 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. 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.
- fweimer 2y agoHow does Go avoid getting bogged down by middleware-oriented programing in practice? I think most large-scale programming in organizations tend to converge on that because it sort of works. Is it that people who like this kind of stuff write microservices for deployment on Kubernetes clusters?
- Cthulhu_ 2y agoGo itself doesn't do anything about that, nor does Java or JS dictate anything about using middleware. 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?
- nprateem 2y ago> Regarding stack traces, it turns out you don’t need them Then you go on to explain how to recreate them by hand.
- saturn_vk 2y ago> Maybe stash a slog logger in there, but that’s about it. 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`
- saturn_vk 2y ago> Also DI, which is arguably not necessary at all in Go given how elegantly interfaces work. 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.
- unscaled 2y agoToo many people confuse the concept of DI with a DI framework. You don't even need a DI framework to write straightforward programs in Java. After all, Java also has interfaces! 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.
- mexicocitinluez 2y ago> One of the reason people needed a DI framework in Java is crazy "enterprise" configurability requirements a 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.
- Cthulhu_ 2y ago> Then wrap the error as many times as you want to annotate additional lines as the error is handled up to the top level 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.
- gf000 2y agoI would argue that in the majority of the cases that's the only reasonable behavior. I do agree that errors should be handled as close as possible to where they occured, but not any closer -- e.g. there is not much you can do within a library's functions if an unexpected error occured inside. It should be handled at whatever business code happens to call it. And in the worst case, they should bubble up to a central handler, that either outputs an 500 error, or an error dialog. Exceptions pretty much make this the sane/default behavior, with rust-like ADTs with syntax sugar being close.
- zero_shift 2y ago> 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 So instead of a stacktrace, you are - tracing the stack? Am I understanding correctly? Because it just sounds like a manual version of stacktraces
- Capricorn2481 2y ago> Because it just sounds like a manual version of stacktraces Because it is. I don't understand it either.
- mexicocitinluez 2y ago> 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. 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.
- cflewis 2y agoFWIW the internal Google style guide says to not pass anything via Context unless you _really_ know what you're doing and why. Things that make sense: security tokens and tracing. Things that don't make sense: almost everything else.
- throwaway2037 2y ago> internal Google style guide Can we read this somewhere?
- Saser 2y agohttps://google.github.io/styleguide/go/ https://google.github.io/styleguide/go/ is the public version of it. Having read both I'd say the differences are small. The main thing missing, though, are the GoTip episodes that haven't been made public, and which are excellent.
- starquake 2y agoI think the Google Go style guide is really nice and pragmatic. There are some references to the GoTips for some advanced subjects. I hope they release it someday. I made an issue for it: https://github.com/google/styleguide/issues/881 https://github.com/google/styleguide/issues/881
- konart 2y agoI'm not sure about Google style guild but Go's context package docs state: "Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions." https://pkg.go.dev/context https://pkg.go.dev/context Using context as a some sort of a mule is an antipattern.
- throwaway2037 2y ago> Using context as a some sort of a mule I never saw the term "mule" used in this way. Very succinct!
- Ferret7446 2y agoContext is just thread local storage aka dynamic scoping aka global variables. It is useful for some things, particularly middleware that needs to cross API boundaries. https://www.felesatra.moe/blog/2019/12/01/transiting-apis https://www.felesatra.moe/blog/2019/12/01/transiting-apis
- nine_k 2y agoImplicit shared state? Exactly the thing to enjoy in a highly concurrent environment! 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.
- cyberax 2y agoThe context itself is immutable, it's essentially a linked list (or actually a tree). If you need to "mutate" it, you create a new segment that links to a previous segment.
- throwaway2037 2y ago> 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.
- zdragnar 2y agoThe languages aren't, strictly speaking, so much the problem as are the massive frameworks configured via distant files with lots of DI and reflection magic involved. Go has some large frameworks, but the community frequently suggests they aren't needed and that the standard library is enough.
- demi56 2y agoSo the community influences the language, not the language that influence the community that explains everything
- rob74 2y agoWell, it's a bit of both. Java is of course very influential, and because it uses a framework for web applications, many languages/communities started imitating that (Ruby/Rails, PHP/Laravel, JS/[Framework_of_the_day] etc.). Then Go came along with its back-to-basics approach and its standard library which is "batteries included" but definitely not a framework, and for some this is a breath of fresh air, while for others it's apparently unbearably alien and backwards...
- gf000 2y agoI'm fairly sure that most of these frameworks are not direct imitations of what Java did, and there was a back-and-fort co-evolution where standard CRUD web applications can be written in a very very productive way (for the small price of learning a framework). 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.
- rendaw 2y agoHow are interfaces a replacement or improvement to context? Is it just that they're type safe?
- roncesvalles 2y agoIoC DI in Go is a massive antipattern and absolutely should not be done. Do NOT write Java/.NET style controllers in Go i.e. initializing an instance of a "controller" type with some instances of a "dependency" such as a store. 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.
- 3uler 2y agoAnd yet Uber wrote fx[1] to support DI in their golang services. It’s clearly a useful pattern when working on large services. [1]: https://github.com/uber-go/fx https://github.com/uber-go/fx
- roncesvalles 2y agoI disagree with the premise of that whole project. It shouldn't exist.
- 65a 2y agoI really cannot say Uber's use of Go is particularly idiomatic to me, having started writing Go more than a decade ago now. It just strikes me as overwrought, and I've worked on big services.
- Cthulhu_ 2y agoJust because a known company uses it doesn't mean it's authoritative; there's likewise functional programming libraries built by big companies, but FP should also be avoided in Go because it's not a functional language and not optimized for it.
- someothherguyy 2y agoSo, write python in go instead, gotcha.
- geitir 2y agoAlso https://github.com/uber-go/fx https://github.com/uber-go/fx