by xnorswap · 2y ago · 0 comments
> .ConfigurationFileService implements IConfigurationFileService
> STOP MAKING SERVICES AND FACTORIES AND INTERFACES AND JUST READ THE FUCKING
> JSON FILE YOU ENTERPRISE FUCKERS
I know it's cool to "hate" on OO, but "just read the fucking file" doesn't work if you want to run your unit tests without reading a fucking file.
It makes sense to abstract configuration behind an interface so you can easily mock it our or implement it differently for unit testing.
Perhaps you also want to have some services configured through a database instead.
This isn't a ConfigurationFileServiceFactoryFactory.
Then don't do that, if in the real world it'll read a fucking file, then test with reading a fucking file. Tests aren't there to just be passed, they're to catch problems and if they're not testing the same workflows that the code will see IRL then the test is flawed. The first test should be reading a fucking file and that fucking file could be full of all sorts of garbage.
Same goes for non-fucking files.
I'm happy to have a long running integration test suite that runs on a build server.
But while working on a project, I need fast running unit tests that I can edit and run to get fast feedback on my work. I find that "time to iterate" is key to effective and enjoyable development. That's why hot module reloading is an amazing innovation for the front-end. The back-end equivalent is quickly running affected unit tests.
So I'd rather unit test my FooFileReader to make sure it can read parse (or not) what's in various files, and unit test my service which consumes the output of my FooFileReader by either parameterising the FooFile result or having an IFooFileReader injected. ( Either works to separate concerns. )
While unit testing, I'm going to test "given that System.IO.File can read a file", and write tests accordingly. I don't want a test sometimes fails because "read errors can happen IRL". That doesn't help test my business logic.
I can even test what happens if read failures do happen, because I can mock my mock IFooFileReader to return a FileNotFoundException or any other exception. I'd rather not have to force a real-world scenario where I'm getting such an error.
In a functional world, it's the difference between:
function string -> result
and function string -> parsedType -> result
The second is cleaner and neater, and you can separately test: function string -> parsedType
function parsedType -> result
The second is more testable, at the cost of being more indirect.Interfaces and factories are just an idiomatic .NET way of doing this indirection over services and classes.
Of course you can also write more in a functional style, and there are times and places to do that too.
Also reading / parsing a JSON file is fast enough for hot reloads / auto rerunning unless you have multiple GB files - so the argument for speed makes no sense. I'd argue it's slower as a whole to have to code up mocks and fill in the data than copy paste some json.
I do agree with the second being neater, however past a certain point of enterprise coding it's a negligible difference compared to the overall complexity of the code - so taking a shortcut and making your tests simpler through JSON files actually ends up being the cleaner / neater solution.
>While unit testing, I'm going to test "given that System.IO.File can read a file", and write tests accordingly. I don't want a test sometimes fails because "read errors can happen IRL". That doesn't help test my business logic.
Since you're given that - use it. If your test fails because a "low level" dependency is failing it's indicating something is seriously fucked up on your machine.
Basically too many unit testing tutorials were simplified too far, so the vast majority of people think a "unit" is syntactic rather than semantic. Like, a single function rather than a single action.
That sounds pretty squarely in the "you ain't gonna need it" category. If your test harness cannot make a temporary directory and populate it with a copy of the test config file that's stored in the same SCM repo as the test case code, then you simply have a broken CI server. There's no need to complicate your codebase and make your tests less realistic all to avoid hypothetical problems that would almost certainly break your test suite before the test case gets around to attempting an fopen. Just read the damn file.
There are more complicated instances where mocking and dependency injection is needed. "fopen might fail on the CI server" usually isn't one of them.
Reading a file is a fast operation these days. Re-reading a file shortly after a read is less than a memory copy.
Making the structure more complicated so that you can avoid reading a file during unit tests is a poor investment of resources - that complexity will haunt down the team forever.
You see it everywhere where someone handrolls a "ServiceResolver" or "DtoMapper" that wrap what DI or ORM already handle on your behalf, simply because it is consistent with ancient badly written code that originates from practices that came from heavier Java and before that C++ codebases.
There is no cost trade-off.
So many developers don't understand this simple concept - it manifests in 2 ways: 1. Not writing tests 2. Writing too many / too specific tests
Testing should always be focussed on the OUTCOMES never the implementation. That's why they're so good for making sure edge cases are covered - since we are able to assert the input and expected outcome of the code. I like to use the mental image that in an ideal world I could put the same tests on a completely separate implementation and it would still pass (mocks/stubs, and implementation specific tests don't pass this).
I'm always far more frustrated by 2 than by 1 - since 2 adds so much unnecessary code / complexity that doesn't need to be there, growing technical debt through the tool that should help us manage it. They make changing implementations painful. And worst of all they think they're doing something correctly and when combined with the sunk-cost fallacy they're incredibly resistant to changing these fucked up tests.
Don't get me wrong 1 is annoying too but he'll at least add the tests when you ask him to and not over engineer everything.
At the end of the day, tests are necessarily a mock-up of what's real. You just happen to disagree with where some people put the abstraction layer. I also would like to make my tests more "real" but I have a lot of sympathy for folks that are trying to test something smaller without involving eg a file. After all, the whole point of "everything is a file" in Unix is that we shouldn't need to worry about this detail, it's an OS concern. If you write to a file that's not actually a file on disk but actually a device, that it should fundamentally be okay and work as expected.
> file isn't a "real" configuration file then isn't it just a "mock?"
I want to say "no" but I haven't thought about it enough yet. My reasoning is that the file itself contains information about the expected messages to/from systems, since it is the body of whatever the system should respond to. And while it is only 1 layer separated from just creating the same object in memory for your test this "feels" different because you can't just pull it out of your codebase into curl.
isn't that an oxymoron?
"Interface all the things" is a bit lazy, but it's easy, especially if you have Moq as a way to auto-mock interfaces and a DI framework to setup factory methods.
But spinning into rage just because you see an interface or abstract factory isn't healthy.
There's nothing that triggers* me more than seeing an interface that only has one implementation. That's a huge code smell and often a result of pre-mature architecture design in my opinion. It also often leads to complexity where if you have an interface, you create a factory class/method to instantiate a "default" implementation. Fortunately it seems that it is not used as often as before. Our code has no factories and only a few interfaces, that actually have a practical use. The same applied to my previous workplace
* The trigger applies to 2024 Java code written as if it was 2004. I may have a form of PTSD after many years of interfaces and FactoryFactory, but fortunately times have changed. I don't see much of that today except in legacy systems/organizations.
I used to be in the "Interfaces with only a single implementation is a code smell" camp, but I prefer to follow the principle of least surprise, so going with the flow and following the way the MS standards want you to do things makes it easier to onboard developers and get people up to speed with your code base. Save "Do it your own way" for those parts of the system that really requires it.
And technically the auto-generated mock is a second implementation, even if you never see it.
I sometimes work on legacy C# code that we inherited from another team and I try to follow the style as close as possible. I just haven't invested enough time to make any informed decisions about how things should be.
My comment was regarding interfaces used internally within the code, with no expectation of any external use. I wrote from a modern Java perspective, with mockable classes. Apparently interfaces are used by .Net to create mocks in unit tests, which could be a reason to use that approach if that is considered "best practice"
An interface with a single implementation sometimes makes sense, but in the code I've seen, such things are cludges/workarounds for technical limitations that haven't been there for more than a decade already. At least, it looks that way from the perspective of a polyglot programmer who has worked with multiple interface-less OOP languages, from Smalltalk to Python to C++.
IConfigurationFileService implies abstraction of file system-based configuration. Are we planning that there's going to be a different way to read configuration files in the future, and what exactly is that? If no one can articulate it, it just seems like architecture astronautism and: YAGNI.
IConfigurationService makes writing unit tests for anything that uses it way easier, too. There can be a simple TestConfigurationService:IConfigurationService that just implements everything as settable, and in your test code you can provide exactly the properties you need (and nothing more), and easily have 100 variations of configs to ensure your code is working. Without the headache of dealing with actual files separate from your test code, or worse, shared with other test code.
I've actually written multiple long-lived pieces of software this way, and more than once ended up implementing stuff like environment variable-based configuration, REST API-sourced configuration, and even aggregations that combine multiple sources, eg:
new AggregateConfig(new ServerConfig("https://whatever"), new EnvironmentConfig(), new FileConfig("/some/path.config"));
All that code that used IConfigurationService is completely untouched and unaware of any of this, letting whoever is doing this as part of changing deployment (or whatever) be productive quickly with very little knowledge of the rest of the (possibly massive) app.I don't understand how this is the case. If anything, an interface is MUCH easier to understand than a variety of functions strung together.
I mean, this is the whole reason we have APIs. If I'm a consumer, I would much rather read and understand the API and its contract than try to read through the code to find out requirements.
I have waded through such code in Java, rather than C#. At least some of it is fighting the language; Java is pretty hostile to writing DI style code.
On top of that, even in languages that are more DI friendly, DI significantly decreases the lexical locality of code that is dynamically very close.
The whole point of specifications is trying to extract the most requirements in the least amount of time. With more "top level" interfaces and tools like DI you can do that, but certainly you can take it too far. A single function, I'd say, is way too far.
Config config;
// production
config_from_file(&config, "config.json");
run_production_stuff(&config);
// unit tests
Config config;
config_from_memory(&config, &some_test_values);
run_tests(&config);So let's say you have a service FooService that requires some configuration.
( Ignoring the System.configuration namespace for now)
You'd have:
class FooService(IConfigurationService ConfigurationService){
// Access Configuration Through IConfigurationService
}
Then elsewhere you'd set up your DI framework to inject your ConfigFileService to satisfy IConfigurationService in prod.Yes, it can sometimes feel a bit like "turtles all the way down", where sometimes you just wish you had a bunch of concrete implementations.
In unit tests, you'd auto-mock IConfigurationService. For integration tests you might provide a different concrete resolution.
There are some advantages to service based DI though. The standard ASP.NET DI framework makes it trivially easy to configure it as a singleton, or per-request-lifetime, or per-instantiation, without having to manually implement singleton patterns.
This gives you good control over service lifetime.
But I just wanted to illustrate idiomatic .NET DI, and on reflection picking configuration was probably the worst way to illustrate it.
You could make a few dozen different configuration files. Or maybe it's more than that because you want to test permutations. Now you're maintaining a bestiary.
So instead you think "I'll write code that generates the config file for each test". And that's reasonable sometimes.
On the other hand, the single-responsibility principle can be reasonably applied here and "reading the config data" is a good single responsibility. You don't want to have to write code to muck with json or xml every time some component needs a configuration value. So there should already be a clean boundary here and it often makes sense to test the components separately.
There's not one rule. The article author sounds like an excitable jr engineer that's never written software at scale.
Is this like a never version of that insult where people would say someone's opinion doesn't matter because they worked on a project that never shipped (regardless of how much or how little they contributed to the failure)? Just replacing it with an AWS bill-measuring contest?
But yeah, when I hear "STOP MAKING SERVICES AND FACTORIES AND INTERFACES AND JUST READ THE FUCKING JSON FILE YOU ENTERPRISE FUCKERS" I think "developer who's never worked on anything more complicated than a chat app, and isn't old enough to have learned humility yet".
Any battle-hardened test suite is already a bestiary. Having a subfolder of diverse & exemplary config files, that could be iterated over, is not adding much to the pile.
Could just be a case of bad naming and it solves everything you're saying. But it sounds like pointless enterprise-y fuckery to me.
I would not say the same thing about `ConfigurationFileService : IConfigurationLoader` or something.
I found out that our unit test suite would only pass when run under elevated credentials. Our internal developer tooling had been running under semi-privileged credentials for years, and was the usual way of triggering a full unit test suite run, so no-one really noticed that it didn't work when run at a lower elevation.
When run from a lower privilege, a unit test was failing because it was failing to write to a registry key. I first double checked that I wasn't accidentally triggering integration tests, or that the test should be tagged integration.
But no, we had simply failed to abstract away our registry writes within that service. Of course no unit test should be writing to the real registry, but this settings manager was just being new'ed up as a concrete class, and there was no interface for it, and so it was just naively making registry edits.
This settings class wrote directly to the windows registry as it's data-store wasn't noticed as an issue for years, because all the times it had previously been run, it had been under credentials which could access that registry key.
And yes, there are different ways we could have mocked it, but favouring a concrete class meant this registry edit was happening unnoticed across all our unit test runs. And I suspect this might have been behind some of the dreaded flaky test syndrome, "I just tweaked a CSS file, why did my PR build fail?". Because 99% of times it was fast enough that it didn't cause issues, but with just the right concurrency of test execution, and you'd have a problem that wouldn't show up in any meaningful error message, just a failed test "for no reason".
Why shouldn't unit tests read real-world files? Because that introduces brittleness, and an inherent link between tests. If you want fast and easy to parallelize tests they need to have no real-world effects.
A test suite which is effectively pure can be executed orders of magnitude more quickly, and more reliably, than one which depends on:
- Files
- DateTime.Now (Anywhere in your code. A DateTimeFactory which you can mock might sound ridiculous, but it's perhaps the best thing you can do for your code if your current code / tests run on real dateTimes. Even for production code, having a DateTimeFactory can be really helpful for relieving some timing issues. )
- Databases ( This is more "obvious", but still needs to be said! )
And so on. A unit test suite should boil down to essentially pure statements. Given inputs A,B,C, when applying functions f, g, h, then we expect results h(g(f(A,B,C))) to be X.This can also be the difference between a test taking <1ms and taking <10ms.
As a final point, you're usually not wanting to "test the code that uses a config file", you want to test code which you don't care if it uses a config file.
The "Code that uses a config file" should be your Configurator class. What you actually want to test is some service which actually produces useful output, and that contains business logic.
Yes, "separation of concerns" can be taken too far, but having something else responsible for the manner in which your service is configured so that your service can just take in a business-domain relevant typed settings object is helpful.
As I've said elsewhere, config is actually a terrible example, because it's essentially a solved problem, MS released System.Configuration.ConfigurationManager ( https://www.nuget.org/packages/system.configuration.configur... ), and you should probably use it.
If you're not using that, you ought to have a good excuse. "Legacy" is the usual one of course.
I've got this in several places.
I have code that needs to check if other date is within two weeks of today. I have test data.
I could either modify the test data based on today's date (adding other logic to tests that itself could be faulty), do something while loading the test data... or have the date to be used for comparisons be injected in.
That date is July 1, 2018. It was selected so that I didn't have difficulty with reasoning about the test data and "is this a leap year?" or across a year boundary on January 1.
Its not a "I don't trust it to work across those conditions" but rather a "it is easier to reason about what is 60 days before or after July 1 than 60 days before or after January 1.
And returning to the point - injectable dates for "now" are very useful. Repeatable and reasonable tests save time.
EDIT: Found xnorswap's comment below about configuration, which makes sense I get - but as they mentioned, it does feel like "turtles all the way down".
You can analogize this to non-software use cases. I've got phillips head and flathead screwdrivers and ideally don't want to have to worry about the specific qualities of a particular kind of screw when selecting one. It either has one slot on the head or two. That's the interface to the screw and it should be the only thing I have to worry about when selecting a screwdriver.
Unfortunately, this kind of thing can balloon out of control, and in the worst kinds of "enterprise" Java shops I was involved in deep into my past, where concrete classes were injected at runtime by xml file loaded into the framework, it was literally impossible to tell what code was going to do simply by reading it, because it is impossible to know what is being injected at runtime except by inspecting it during runtime. It's a pretty frustrating experience when reading an entire code base doesn't tell you what the code actually does.
I've worked in "legacy" nodejs code since node 0.x. Glad to hear that there might be hope of codebases that don't have this problem. I thought typescript would help, but I've learned that fancy generics can ensure that it's still quite possible to have no idea what something will actually do in a real world environment, you'll just have a lot more cognitive overhead in wondering about it.
To be clear, I love ts and fancy generics that try to impose a Haskell-like determinacy on js Object structure with exclusivity and exception guarantees and all the rest; I just also hate it/them, at the same time.
So, for example, I could have a IGadgetStore with methods for creating, retrieving, updating, and deleting gadget instances and then I can have a bunch of different classes implementing that interface. An obvious example is to have a PostgresGadgetStore and a MysqlGadgetstore and CsvFileGadgetStore. If the user wants to implement their own store that I haven't written, they can.
It is.
Nowadays, .NET is usually able to do away with the abstraction cost of such interface abuse luckily, but it remains an additional item you mentally have to deal with, which isn't good.
Single-implementation interfaces are still considered an anti-pattern, and teams that over-abstract and mock everything out when writing unit tests usually just waste time in pursuit of multi-decade old cargo cult. These also often test that modules comprise of specific implementations and not whether they simply satisfy the interface contract, which is terrible. And often turn stateless parts of logic that could have lived on some static class into an interface and an implementation injected with DI, that is then mocked out, instead of just calling methods on a class. More difficult to remove, worse locality of behavior, does not answer the question "if tests are green, are we confident this will work in prod?", sadness all around.
I agree with your sentiment. It's much more practical to write functional and component-level tests with coarser granularity of individual test items, but with more extensive coverage of component inputs. There's a wealth of choices for doing this with little effort (e.g. testcontainers).
So in this case, is this entire file being handed to clients to do what they will with it? Does that make sense as an interface.
If you are building an app, and you want other parts of the app, or clients of the app, to use this data, does it make sense to just hand over the entire file as the interface.
Basically :
Programmer 1: "Hey man, show me your data interface so I can build a quick lookup on something"
Programmer 2: "here is the whole damn file, do whatever you want and leave me alone. Figure it out yourself, and no I'm not going to give you a schema and I'll change it whenever I want".
"Mock" can be a loaded word in this context, so please excuse me if I'm looking at it through a difference lens, but if you're using some sort of mocking set of tooling (like Jest or similar), I'd argue that those mocks are much more confusing than an interface with an implementation.
I personally love an interface because it defines the most narrow set of operations an object needs to support to be passed in, and the implementation of those are completely irrelevant for calling. In many cases, I personally find that a lot simpler and cleaner to read.
Because I always enjoy leaked code comments. It’s like “tell me how you really feel about this shitty bloated enterprise framework you are using”.
There were some good ones in the leaked windows source code, weren’t there?