Most active commenters

    ←back to thread

    257 points pmig | 34 comments | | HN request time: 0.847s | source | bottom
    Show context
    bryancoxwell ◴[] No.43096481[source]
    > 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.

    replies(8): >>43096604 #>>43096796 #>>43096956 #>>43097757 #>>43098179 #>>43098205 #>>43099616 #>>43099625 #
    1. MrDarcy ◴[] No.43096604[source]
    I 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.

    replies(14): >>43096842 #>>43098162 #>>43098528 #>>43099235 #>>43099768 #>>43099821 #>>43100046 #>>43100754 #>>43100817 #>>43101015 #>>43101030 #>>43101721 #>>43101893 #>>43103377 #
    2. arnath ◴[] No.43096842[source]
    This 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?
    replies(2): >>43098306 #>>43098889 #
    3. mukunda_johnson ◴[] No.43098162[source]
    I 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.
    replies(1): >>43099348 #
    4. MrDarcy ◴[] No.43098306[source]
    I 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.
    5. nine_k ◴[] No.43098528[source]
    The 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.

    replies(1): >>43099165 #
    6. bcrosby95 ◴[] No.43098889[source]
    DI 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.
    replies(1): >>43101250 #
    7. lelanthran ◴[] No.43099165[source]
    > 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?

    replies(1): >>43099834 #
    8. nesarkvechnep ◴[] No.43099235[source]
    I’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.
    replies(2): >>43099695 #>>43100282 #
    9. ignoramous ◴[] No.43099348[source]
    > 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

    10. vram22 ◴[] No.43099695[source]
    That 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-l...

    replies(1): >>43099969 #
    11. akoboldfrying ◴[] No.43099768[source]
    > 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

    12. andreasmetsala ◴[] No.43099821[source]
    > 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.

    replies(1): >>43099943 #
    13. galaxyLogic ◴[] No.43099834{3}[source]
    I 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.

    14. RussianCow ◴[] No.43099943[source]
    If 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.
    replies(5): >>43100207 #>>43100273 #>>43100588 #>>43100709 #>>43101162 #
    15. eximius ◴[] No.43100046[source]
    > 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.

    16. com2kid ◴[] No.43100207{3}[source]
    Design 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.

    17. cryptos ◴[] No.43100273{3}[source]
    But that "framework" could be a simple factory function.
    18. mavelikara ◴[] No.43100282[source]
    This isn’t anything special about Java. A determined programmer can write Fortran in any language.
    19. lucumo ◴[] No.43100588{3}[source]
    No, 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.

    20. gf000 ◴[] No.43100709{3}[source]
    No, you can pass (inject) the necessary dependencies to the constructor of an object at creation time, and then simply use that object instance everywhere. The only thing frameworks do is "solve" the dependency graph and instantiate stuff in the correct order.

    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).

    21. fweimer ◴[] No.43100754[source]
    How 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?

    replies(1): >>43101748 #
    22. nprateem ◴[] No.43100817[source]
    > Regarding stack traces, it turns out you don’t need them

    Then you go on to explain how to recreate them by hand.

    23. saturn_vk ◴[] No.43101015[source]
    > 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`

    24. saturn_vk ◴[] No.43101030[source]
    > 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.

    replies(1): >>43101199 #
    25. simiones ◴[] No.43101162{3}[source]
    "Injection" in "dependency injection" simply refers to getting your dependencies from outside instead of building them yourself.

    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.

    26. unscaled ◴[] No.43101199[source]
    Too 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.

    replies(1): >>43103293 #
    27. unscaled ◴[] No.43101250{3}[source]
    To 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.

    28. Cthulhu_ ◴[] No.43101721[source]
    > 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.

    replies(1): >>43102360 #
    29. Cthulhu_ ◴[] No.43101748[source]
    Go 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?

    30. jbreckmckye ◴[] No.43101893[source]
    > 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

    replies(1): >>43107247 #
    31. gf000 ◴[] No.43102360[source]
    I 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.

    32. mexicocitinluez ◴[] No.43103293{3}[source]
    > 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.

    33. mexicocitinluez ◴[] No.43103377[source]
    > 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.

    34. Capricorn2481 ◴[] No.43107247[source]
    > Because it just sounds like a manual version of stacktraces

    Because it is. I don't understand it either.