krimog
krimog

Reputation: 1276

Create multiple structs with same implementation

My program has two different notions of Version: a DefinitionVersion and an InstanceVersion. They're both int. To avoid any confusion, I decided to create 2 specific structs that just contain an int field (DDD value objects).

I need to implement IEquatable<T>, IComparable<T>, overload operators, manage serialization, etc. on both of them. But apart from the name of the class (and the constructor), they're exactly the same.

What is the best approach?

Here's what I thought of:

Is there a better way? And if not, which of those should I use?

Upvotes: 0

Views: 133

Answers (1)

JonasH
JonasH

Reputation: 36371

I think it depend a bit on the exact use case.

If you only have two variants (and do not expect more), I would probably go for the copy/paste option. This will be easiest, and I would expect there to be few changes to a simple type like a version. Just keep in mind to write some unit tests so you can be confident that there are not a bunch of bugs being copied.

If the variants are only mostly the same I would also go for Copy/Paste. Perhaps you want some conversions for one variant only? Maybe there are some other operation that only make sense for one variant? Even if there are no differences right now you also need to consider what the types actually represents, and if they might diverge in the future.

If you have more variants, and all are identical, I would probably go for the generic struct, possibly with some constraint to restrict the generic type parameter. Just ensure you add suitable comments to explain the idea.

Upvotes: 2

Related Questions