patterncsharpModerate
General static value required by multiple classes
Viewed 0 times
valuegeneralmultipleclassesrequiredstatic
Problem
I have a general value called Seed which is required to multiple class. But those class aren't dependent of the class which declare it.
And some class need a Seed value to work. I take the class
A solution would be to use
A other way would be to set as public field in the Noise class.
So in this way,
But I don't like it too, in this case this is about a
This solution works but I'm not pleased about it. For non-nullable type I have to define an other variable to check, for a nullable class I can compare it to
class Game {
class Settings {
public static float Seed = 1337;
}
}And some class need a Seed value to work. I take the class
Noise as example here.class Noise {
private static float _seed;
}A solution would be to use
Game.Settings.Seed to know the value into the class Noise. But what if one day I decide to take all the Noise class to use it in an other project. The code won't compile because there is probably not a Game.Settings.Seed declared in the other project obviously.A other way would be to set as public field in the Noise class.
class Noise {
public static float Seed;
}So in this way,
Game which know he need to use Noise class, will set Seed field before doing anything with this class.But I don't like it too, in this case this is about a
float, so that not really a problem, but what about an object that need to be declared, which means Noise class need to implement a verification about itself.class Noise {
private static float _seed;
private static bool _isSeedDeclared;
public static void SetSeed(int seed){
_seed = seed;
_isSeedDeclared = true;
}
public int GetValue(int x, int z){
CheckSettings();
return computedValue; //to calculate computedValue, I need Seed value
}
private void CheckSettings(){
if(!_isSeedDeclared)
throw new Exception("You have to define Seed value.");
}
}This solution works but I'm not pleased about it. For non-nullable type I have to define an other variable to check, for a nullable class I can compare it to
null. But anyway, I don't have only one parameter and I don't have only one class. I'm looking for an better way to implement it.Solution
If the
Consumers of the
seed parameter is required for the Noise class to work properly, it must go to the constructor as a required parameter. If an invalid seed passed to the constructor, it should throw an ArgumentException explaining what's wrong with the seed and (ideally) what the expected value could look like (e.g. if there are some range rules take place in your domain).Consumers of the
Noise class will have to inject the proper value (likely taking it from the settings).Context
StackExchange Code Review Q#155850, answer score: 10
Revisions (0)
No revisions yet.