0

I am looking to design and create a new large-scale application from the ground up and use type safety with structs where appropriate. The application does have a large number of calls between classes.

Currently I am looking to implement structs to represent Id's and different types of numbers (e.g. prices and quantities), but when would be taking it too far?

Thanks,

Update: Thanks for the link to when to use structs, but that does not answer when you should enforce type safety.

Dech
  • 1,582
  • 4
  • 17
  • 32
  • 1
    Only use immuatbles for [immutable objects](https://en.wikipedia.org/wiki/Immutable_object). Nothing else. Structs should typically be used sparingly. Specifically be wary that structs are [inefficient to pass around](http://stackoverflow.com/questions/521298/when-to-use-struct/521311#521311) as you must pass the value and not just a reference to the value – Liam May 13 '16 at 09:17
  • Structure are archaic and you should use classes instead. Good design practices says modules (.cs) should be limited to around 400 to 500 lines of code. A class can be spit into more than one module. A class being used as an interface should be used when two classes or more classes share same data structures. If you have a large number of calls between classes than maybe you should consider redesign of the classes. Classes should not be calling each other. One class should be a master and 2nd a slave so the calling should be in one direction. – jdweng May 13 '16 at 09:26
  • What is the advantage of beeing not type safty in you case? – JanDotNet May 13 '16 at 10:35
  • structs were also not supported in Entity Framework 5. – mcy May 13 '16 at 10:35

1 Answers1

2

It depends upon the system your are writing and how big is "large-scale". Why? I would argue that defining system ids and other value based types as structs would not be a waste of time or taking it too far. It would help define the limitations and bounds for the type.

There have been too many instances of String being re-purposed for various nefarious programming constructs:

  • multiple value chaining where and id has data added to it because it is easy and convenient
  • unintended invariant usage such as knowing the - char is invalid so using that for another value

Practices like this will creep into your system because the original authors never specified or enforced, via type constructs, the limitations. Business priorities (we go live tomorrow and cannot change the database now!) or even lazy development practices take advantage of you lack of specificity.

Define your value types as value types, including using structs, but make their usage clear and enforced by the code.

Ken Brittain
  • 2,255
  • 17
  • 21