which is best option?
-
I have 10 different classes in an application. I need to access a constant (int value = 125;) in all ten classes. Which is better way of following two options? 1. Declaring int value = 125; in all classes or 2. creating static class public static class Constants { public static int value = 125; } using it as Constants.value in all classes. Any other best option? Thank you in advance..
-
I have 10 different classes in an application. I need to access a constant (int value = 125;) in all ten classes. Which is better way of following two options? 1. Declaring int value = 125; in all classes or 2. creating static class public static class Constants { public static int value = 125; } using it as Constants.value in all classes. Any other best option? Thank you in advance..
If you put it in a static class, this is accessible to all other classes, not just your ten classes. Putting it in each class is a maintenance nightmare - if you add an 11th class, you have to remember to add the int. If the int changes, you have to change it in all places. Do the classes all derive from a base class? If so, put it there and make it
protected
.We violated nature and our children have to pay the penalty Don't go near the water children... Johnny Cash - 1974
-
If you put it in a static class, this is accessible to all other classes, not just your ten classes. Putting it in each class is a maintenance nightmare - if you add an 11th class, you have to remember to add the int. If the int changes, you have to change it in all places. Do the classes all derive from a base class? If so, put it there and make it
protected
.We violated nature and our children have to pay the penalty Don't go near the water children... Johnny Cash - 1974
-
I have 10 different classes in an application. I need to access a constant (int value = 125;) in all ten classes. Which is better way of following two options? 1. Declaring int value = 125; in all classes or 2. creating static class public static class Constants { public static int value = 125; } using it as Constants.value in all classes. Any other best option? Thank you in advance..
A static variable in a class is the best option (or similar solutions). Declaring the same value in several places largely defeats the purpose of declaring it at all. If you use a constant, the value will be inlined when compiling, so if you change the value you have to recompile all code to get the value to change everywhere. If you have a static variable, all classes will always read from the same physical variable.
Experience is the sum of all the mistakes you have done.