Re:Learning a new language, or how I gained familiarity with Go
by randomdata on Wednesday August 17, 2022 @06:34PM
(#32502604)
> I've found that unless I write code in golang in a way that was intentionally written to be unit tested, it is very hard to bolt on unit testing after the fact.
Absolutely. This is true in most, if not all, languages. But when you're in the driver's seat, able to make choices like whether or not to use fx, why would you bolt on testing after the fact?
Not much you can do about legacy code, if that's what you have to deal with, but when dealing with legacy code it is unlikely the authors used fx, so...
Re:Learning a new language, or how I gained familiarity with Go
by latchkey on Wednesday August 17, 2022 @07:27PM
(#32503148)
As you refactor the code to be more testable, you can add in fx. It doesn't have to be from the beginning.
Re:Learning a new language, or how I gained familiarity with Go
by randomdata on Wednesday August 17, 2022 @07:43PM
(#32503306)
If you refactor code to be more testable then it is testing that is forcing you, not fx.
Re:Learning a new language, or how I gained familiarity with Go
by latchkey on Wednesday August 17, 2022 @11:33PM
(#32504956)
Correct, I haven't argued any differently. You introduce fx in, start writing tests and it will convince the other developers you're working with that there is importance to how you build the codebase in such a way as to enable testing.
Re:Learning a new language, or how I gained familiarity with Go
by randomdata on Thursday August 18, 2022 @04:43AM
(#32506919)
Then you must have mistakenly replied to the wrong thread? If you are in a position where you can introduce fx, then you are also in a position to introduce testing, and testing will already force testable code. If fx can help your code, great, but that's orthogonal to the discussion.
fx kind of highly encourages the second approach for all of your code. It is a bit more boilerplate, but by default, I'm always going to be thinking about passing my dependencies around instead of just being lazy and doing NewClient in the function.
I also get to take advantage of the fact that Client is just magically passed into my constructor. If there is some error doing so (like I forget to Provide), then fx will give me errors at start up. My dependency chain is clear. It just feels nicer to me.
Once again, of course I can write it the second way without fx... but it is kind of nice that every time I want to use Foo, I don't have to type NewFoo() in a constructor... I just reference *Foo.
By the way, mockery [1] generates super easy to use mocks for exactly this workflow.
[1] https://github.com/vektra/mockery