Let's say management decides that statuses of "Awesome" are too strong. What about the risk that the value changes in the future. I see magic strings the same way. Yes, you might make a mistake the compiler doesn't catch, but that's why we test our code. How long until you figure that out? You'll have tests and/or run the code yourself and see it doesn't work, right?Īlso, if you work with a dynamic language, you know you can type in any nonsense and your compiler won't help you. It's up to you to test it. Let's say you're in JavaScript and looking for that status of "Coll" instead of "Cool". That you mistype the string? There is type-safety risk, but it's a mild one and only applies to C#. But 1) everyone likes magic, and 2) what's the risk? "But this is using magic strings, and those are bad." Maybe. I prefer strings so I can immediately know what the value represents and code around that (e.g., the Status is "Cool" instead of 2). The simplest alternatives are primitive types that convert across all layers, like ints and strings. That is, unless you want to add enum converters from Json.NET to your JsonSerializer to turn them into strings: (new ()) What about sending the value down to the client in JSON? Again, by default you get an int that looses the point of having the enum in the first place. Return (Status) Enum.Parse(typeof (Status), status) Public Status ConvertStringToEnum(string status) It's easy convert the enum to a string before sending it to SQL, but then you have to convert it back to an enum in C# when you read it in, and that code is gross: public string ConvertEnumToString(Status status) Have you ever tried to save an enum to SQL? It becomes an int and you're right back to, "Wait, what does a Status of 2 mean again?". Enums in C# can make you code easier to read: private enum Statusīut enums don't cross in and out of C# easily.
0 Comments
Leave a Reply. |