Reputation: 5082
I have a class with predefined constant strings which are used as keys to retrieve the data from the external storage by provided key.
public class StorageKeys
{
public const string SomeKey = "Foo";
public const string AnotherKey = "Foooo";
}
public interface IStorage
{
string GetValue(string key);
}
Which is used like this:
IStorage t = new Storage();
string value = t.GetValue(StorageKeys.SomeKey);
It works but I'm concerned that potentiality it's possible to call GetValue
method with just string argument which can cause an error:
string value = t.GetValue("Illegal key");
That's why I've come up with this idea:
public class StorageKeys
{
public static StorageKeys SomeKey = new StorageKeys("Foo");
public static StorageKeys AnotherKey = new StorageKeys("Foooo");
private StorageKeys(string key)
{
_key = key;
}
private readonly string _key;
public static implicit operator string(StorageKeys key) => key._key;
}
public interface IStorage
{
string GetValue(StorageKeys key);
}
After these changes my method can be used only with correct keys but I think it would decrease a performance because of static properties and implicit casting.
So my question is it a good idea?
Am I overconcerned?
How much slower my second approach would be comparing to the first one?
Is there another way to prevent passing wrong arguments?
Upvotes: 2
Views: 494
Reputation:
Am I overconcerned?
Short answer, yes.
What you are trying to do is prevent passing an invalid argument which isn't what you are supposed to do in the first place, you should consider using an enum IF that is possible, that makes it 99.9% typesafe and almost no checks would be required.
In a situation where you need that param to be a string, just perform a validation in GetValue(string key)
and either return a null if you wish to handle that later or just throw an Exception.
Upvotes: 2