by tyleo · 1y ago · 0 comments
readonly struct Id32<M> {
public readonly int Value { get; }
}
Then you can do: public sealed class MFoo { }
public sealed class MBar { }
And: Id32<MFoo> x;
Id32<MBar> y;
This gives you integer ids that can’t be confused with each other. It can be extended to IdGuid and IdString and supports new unique use cases simply by creating new M-prefixed “marker” types which is done in a single line.I’ve also done variations of this in TypeScript and Rust.
[1] enum class from C++11, classic enums have too many implicit conversions to be of any use.
They're fairly useful still (and since C++11 you can specify their underlying type), you can use them as namespaced macro definitions
Kinda hard to do "bitfield enums" with enum class
They're fairly useful still (and since C++11 you can specify their underlying type), you can use them as namespaced macro definitions
The name means "Value Object Generator" as it uses Source generation to generate the "Value object" types.
That readme has links to similar libraries and further reading.
Once you have several of these types, and they have validation and other concerns then the cost-benefit might flip.
FYI, In modern c#, you could try using "readonly record struct" in order to get lots of equality and other concerns generated for you. It's like a "whole library" but it's a compiler feature.
I want it for a case where it seems very well suited - all customer ids are strings, but only very specific strings are customer ids. And there are other string ids around as well.
IMHO Migration won't be hard - you could allow casts to/from the primitive type while you change code. Temporarily disallowing these casts will show you where you need to make changes.
I don't know yet how "close to the edges" you would have to go back to the primitive types in ordered for json and db serialisation to work.
But it would be easier to get in place in a new "green field" codebase. I pitched it as a refactoring, but the other people were well, "antithetical" is a good word.
I prefer to have the generated code to be the part of the code repo. That's why I use code templates instead of source generators. But a properly constructed ID type has a non-trivial amount of code: https://github.com/vborovikov/pwsh/blob/main/Templates/ItemT...
That is correct, I've looked at the generated code and it's non-trivial, especially when validation, serialisation and casting concerns are present. And when you have multiple id types, and the allowed casts can change over time (i.e. lock it down when the migration is complete)
That's why I'd want it to be common, tested code.