Global Variable Access Solution Ideas - c#

I have an initialization class that preloads content into a variable (probably a list or array). There will only be one instance of this initialization class but there will be many classes that need to access the preloaded content.
The problem is not many of them are related and none of them extend my initialization class. I thought about this for a bit and decided on using a static method and variable for this use. So something like this...
public class InitClass
{
static List PreloadedContent;
static ModelData GetContent(String ContentName)
{
//return the preloaded content that matches given name
}
}
The preloaded content may at some time decrease or increase in size depending on what the situation may call for. I've run into situations where something like this has been the only decent looking solution however; I think its an ugly solution.
Note: I can't load the data onto a class that needs it when it is created due to a variety of reasons - most of which are reasons I don't know about yet but will most likely come up. Certain classes will be loaded/unloaded depending on the rendering of the scene and my InitClass won't handle the creation of these objects most of the time.
Can anyone give me a better solution?

what you are doing is known as singleton. here are some previous discussions on this:
How to implement a singleton in C#
What’s a good threadsafe singleton generic template pattern in C#

To avoid static/global scope you could use some kind of Registry class. This means you have one class which you initialize at program startup. This class holds references to all other classes that need to be accessed globally.
Now you pass the initialized instance of your registry class to all instances in your application.
It isn't a very pretty soluation, but for me it is the best. With Static and global variables I always ended up in having some problems when testing or debugging code.
Another aproach would be to use a Singleton. Since they also just hold a static instance I would not prefer them.

Related

Passing config values as parameters to an instance method C#

I come across this regularly when refactoring code. Say I have a base class and I read some configuration parameters and stuff them into properties like this
public BaseClass()
{
_property1 = ConfigurationManager.AppSettings["AppSetting1"];
_property2 = ConfigurationManager.AppSettings["AppSetting2"];
_property3 = ConfigurationManager.AppSettings["AppSetting3"];
}
And then I call a method in another class like this
OtherClass otherClass = new OtherClass();
var foo = otherClass.SomeMethod(_property1, _property2, _property3);
Is it better to do that? What if I only needed the AppSettings values inside of the OtherClass class? then I could just load them up as private props and initialize them in the constructor and the referencing class/caller wouldn't need to be concerned with the settings.
public OtherClass()
{
_property1 = ConfigurationManager.AppSettings["AppSetting1"];
_property2 = ConfigurationManager.AppSettings["AppSetting2"];
_property3 = ConfigurationManager.AppSettings["AppSetting3"];
}
My implementation would then simply be
OtherClass otherClass = new OtherClass();
var foo = otherClass.SomeMethod();
This one bugs me but I am not really sure why. Which is a better practice and why? And I apologise I am missing something obvious. It happens sometimes lol.
Thanks -Frank
In my view, it depends on what goal of your class.
If class belongs to domain classes, so there is no need to have a dependency to ConfigurationManager class. You can create a constructor and supply necessary data:
public class FooClass()
{
public Property1 {get; private set;}
public FooClass(string property1)
{
Property1 = property1;
}
}
If FooClass belongs to Service Layer, then, in my view, it is eligible to have a dependency to ConfigurationManager class.
I can't really comment on "better" as that's quite subjective, but it's at the very least factual to say that passing the parameters into the method, rather than having the method go and get them itself, is a form of dependency injection. Dependency injection has advantages in that it reduces the number of things the class has to know how to do/reduces the number of other classes any given class needs to do its work. Typically in OO design we look for ways to reduce the dependencies a class has on other classes. You might also see the concept referred to in general as low coupling. Classes that are not highly coupled to other classes are easier to reuse as independent modules within multiple programs
In your example, OtherClass (and/or BaseClass) needs to know what a ConfigurationManager is, which means it needs a reference to its namespace, needs to have system.configuration.dll available on the target etc just so that it can go and get some basic things (strings) that contain info necessary to do its work. If you instead give the strings to the method then it can do its work without knowing what a ConfigurationManager is - you can use it in an app that doesn't even have a ConfigurationManager anywhere, maybe because it gets its config from a database or perhaps it's part of a unit test that gets some contrived data directly from hard coding to ensure a given result is always obtained
When you're down with the concept that the data a class needs to do its work can come from above it starts to make more sense why systems that pass data around like this can work with an inversion-of-control container; essentially software that creates instances of objects for you according to some preconfigured rules about where to get the data that should be passed in. An IoC container can look at an object and decide what arguments to pass to (e.g. its constructor) based on a consistent set of rules, and take another step towards removing dependencies by further reducing use of the word "new". Think of it like writing a config file to describe which of your objects need what instances of other classes to do the work. You craft your IoC container setup so it makes one IniFileConfigSettingsProvider instance and then provides that instance to any object that needs some kind of IConfigSettingsProvider to do its work. Later you switch away form ini files and go to Xml files. You create a class called XmlFileConfigSettingProvider, register it with the IoC and it becomes the new instance that is passed to any class needing an IConfigSettingsProvider. Critically, you made another class, registered it with the IoC and then it gets used throughout your program but you never made an instance of it yourself
If you ever heard the phrase "new is glue" concepts like this are generally what it alludes to - when your OtherClass says var x = new ConfigurationManager... x.Settings["a"].... the use of the word new has suddenly hard wired it to needing a ConfigurationManager; it can't function without knowing what it is. The strive these days is generally to have a class accepting a "passed-in provider of settings that complies with some interface" or "passed-in primitives that are settings" - things that are either implementation specific but obey a generic interface, or ubiquitous in the language and need no special imports respectively. Perhaps either of your mentioned approaches bug you because deep down you feel that neither of them need to depend on ConfigManager; whether they both need settings or not, they can get them passed in, from something higher up the chain that should be making the decisions as to what settings to use
There will be pros and cons of every design and coding choice. As they say, same pattern may not fit everyone. So one has to customize based on need.
Mainly, decision should be based on use cases of your application. Let me provide few scenarios to describe it. Suppose items configured in AppSettings will not change in life-time of the your application then you can have an approach in which dependencies with AppSettings are least. In particular an approach as var foo = otherClass.SomeMethod(_property1, _property2, _property3);. This matches with OOD principles as classes will focus on business logic.
But if you see add/modifying/deleting items (even in rare situations) during life time then above approach would be difficult to maintain. For example without restarting your application/WebServer if AppSettings needs to be reloaded based on certain conditions. One may argue why such settings will be kept in AppSettings, which is very valid too. If your application demands such scenarios then it would be better to use ConfigurationManager.AppSettings without worrying about dependencies. One can opt to extend it have wrapper class (Singleton pattern) to manage and provide access to ConfigurationManager.AppSettings.

What are the desirable situation (real life example) to create static methods except for creating helper?

I just want to understand the purpose that static method serves and what are the desirable situation where i can create static methods except some would say that static methods are used for creating helper.
Consider i have 1 website that will be used in my company only like Human resource management system like websites.
Now after Admin login in to the system admin will see the list of employees.so the method is simple which does nothing more than fetching all details of employees from employee table and will display them on the web site and this method will be define in business access layer like this in .net:
public class EmployeeBal
{
public List<Employee> GetAllEmployees()
{
return Select * from Employee
}
}
This is how i would call this method from my application.For Eg(.aspx page or mvc controller etc....)
var employeeBal= new EmployeeBal();
employeeBal.GetAllEmployees();
So my question is should i create this method as static method or non static method??
Note:This is just an example of method and this method is in my business access layer.
Consider i have 1 ecommerce website where on the home page i am displaying some list of products and on visit of that website every users can see that list of products.
so my function would be same as above define in Business acess layer:
public class ProductBal
{
public List<Product> DisplayProductonHomePage()
{
return Select * from Products
}
}
So my question would be same like whether to create this method as static method or non-static method and what will happen if more than 10 users at same time simultaneously access this website then what will be the behaviour/implications of this method???
Will this method will serve the purpose of this each user if we declare this method as static??
Can anybody answer this question with briefly explaining every scenario???
A static method makes sense when there’s no state to maintain. What do I mean by state? Well, consider the following: You have two distinct objects, a and b, which are both of type EmployeeBal. Is there ever a case in your program where a.GetAllEmployees() and b.GetAllEmployees() would yield different results?
If not, then why do the objects a and b exist at all? The whole point of having objects is to associate some distinct state with them. If two different objects can never refer to a different state, then they fulfil no purpose.
In fact, in this situation your EmployeeBal would be exactly equivalent to System.Math, and all its methods are “helper methods” (if that’s what you want to call them). In this case, forget about static methods for a minute: your whole class should be static (static class EmployeeBal), and it should not have any constructors; because the concept of an object of type EmployeeBal simply makes no sense. In fact, in other languages EmployeeBal wouldn’t be a class at all; instead, it would be something generally called a module: a unit that logically groups code. C# has no modules, and all code must reside within classes. Classes thus fulfil a dual purpose: they group code, and they generate objects.1
Now consider a less extreme case: EmployeeBal objects actually maintain state, and differ. Yet GetAllEmployees() will still yield the same result, regardless of which object calls the method.
In this case, EmployeeBal obviously cannot be a static class. But GetAllEmployees is still stateless, and thus doesn’t belong to objects of type EmployeeBal. And thus the method should be static.
1 This lack of distinction between two fundamentally distinct concepts (module and class) is actually quite annoying, and the main reason that C# behaves this way is because it was conceived to be similar to Java. It was a mistake in hindsight, but not a serious one.
Is there a reason why the method should be static? If not I'd always side with non-static.
One big reason is being able to write unit tests.
In order to write unit tests you want to be able to isolate the class you're testing from other classes. But if class A contains a reference to static class B, then you can't test A without testing B. Maybe B depends on connection strings or config settings. Maybe B depends on other static classes. Now you can't test A unless B and everything it depends on are in place.
If, on the other hand, class A depends on an interface like IEmployeeProvider that gets provided through its constructor then you can test class A with a mocked implementation of IEmployeeProvider.
If A has IEmployeeProvider as an argument in its constructor then you can tell by looking at the constructor that it depends on IEmployeeProvider. But if it depends on a static EmployeeProvider class somewhere inside a method then the dependency is hidden. You have to read the whole class to know what it depends on.
Also, the static class itself can be harder to test. Unless it's absolutely always going to remain stateless then it's better to have a non-static class that you can unit test.
It's fine to have multiple threads executing the same static method, as long as the method does not access static state such as field or properties. In that case, the shared objects stored in the fields/properties must themselves be thread safe. The data access parts of .Net are not designed to be thread safe.
As soon as you start considering aspects such as managing a database connection that can be reused for several queries during the execution of a single web request, you should consider if static is the best approach. Since you cannot store the connection in a static field as explained above, you will have to pass it as a parameter to each static method. On the other hand, if you pass the connection to a constructor and store it in a (non-static) field, you can access it from multiple non-static methods of that instance, which will IMO be easier to manage.
This is quite a big topic however, and in general the management of class dependencies is quite tricky to get right in OOP. Some programmers prefer to delegate this task to an "Inversion of Control"-library. There are many available for .Net such as Microsoft Unity, StructureMap, AutoFac, etc.
To answer your question:
So my question is should i create this method as static method or non static method??
Note:This is just an example of method and this method is in my business access layer.
I would make those methods static - given what you provided. But I bet that you would have instance variables either declared in your class, or in methods in that class, which then of course that would mean don't make it static.
So a determining factor for me if I decide to use a static method or not has to do with re-use and resources.
If I find myself re-using a method many times over, and I conclude it doesn't need state (kept in memory) - I will make it a static method.
Also I usually will make my methods static if they can be used in other applications or if I think they will be useful down the road.
For example I recently wrote a method that converts a excel file to a flat file. I made this a static method in its own static class (i may put it in a similar utility class down the road) because I will probably end up using it again in another project, so I can now just reference its class without having to instantiate a new object to just call the method. ( I don't need state anyways)
I'm pretty new to programming as well and I hope you found this helpful.
If we are going to talk about static, we need to introduce a dependency. In this case it is a sql client. Here's what the code looks like with that introduced. Since we aren't going to get into the details of a sql client it's used as an interface in the static method.
var client = new SqlClient();
var allEmployeeData = EmployeeBal.GetAllEmployees(client);
class EmployeeBal
{
public static Employee GetAllEmployees(ISqlClient client)
{
return client.Execute("Select * from Employee");
}
}
Dependency injection through an interface changes everything. Now the method is good as being static, because it only deals with an interface and a string. Both of these are stateless. Since all components of the method are stateless they are perfectly safe for a static method which can have only one global state.
As your code was written originally it's not safe as being static, because how can I be assured the sql client is prepared to be used and after I've checked that it's ready it hasn't been altered when I go to run the query? If I can inject the sql client I can manage it since it has a local vs global scope.
A better example would be something like a factory for a sql client. For example with nhibernate there should only be one session factory created. That one thread safe session factory can create multiple non-thread safe sessions for running sql queries. In this case it's appropriate to have the session factory exposed through a static method, because that describes the fact that there is only ever going to be one session factory.
var session = SessionFactory.OpenSession();
Using static methods is equivalent of having a global behaviour. It comes with benefits: ease of access for simple scenarios.
It also comes with all the problems that global data and state have. Among them you cannot substitute an implementation with another (for example for tests). See https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
While you might consider that you don't have a global state ... conceptually you have. You have a unique, predetermined, unconfigurable, hard coded way of accessing some behaviour. You published it and you cannot change it ... ever. You break the open-close principle. You break the liskov substitution principle.
Java has this but scala amended that. More on this here: Why doesn't Scala have static members inside a class?
Use cases for static and non-static methods differ, so you need to create one based on what's the need that they fulfill:
Static method does not participate in inheritance-based polymorphism, while non-static does. In other words, you can't mark static method as virtual or abstract, which means you cannot change its behavior. This also means that caller of the static method knows exactly what this static method is going to do and how exactly. With non-static method, you can be calling it on base class but due to polymorphism you may end up calling the derived class method with overriden behavior.
Both static and non-static methods can be changing a state of something (as opposed to what others claim), but there's a difference. You can design a static class that has all static members (properties, methods, etc.) in it, so the methods can be changing the state of this static class (that said, even though C# allows you doing that, I don't recommend creating such class anyway). With non-static method, you can be changing both static and non-static state of the class. This goes further into the differences between static and non-static classes, which in short means: static class is one concrete instance, while a non-static class can be multiplied and each of them will have its own copy of the state (so why design a static class with the artificial limitation then - this is why I didn't recommend them before).
One more nice usage of static methods is extension methods. These should be defined as static, but you can call them on the instance of the class that they are extending. They still serve as outside shortcuts to the instance, since they can't do anything more than regular static methods (cannot access private or protected members for instance).
And you're right, static class fits well when defining helper methods, because those usually are just shortcuts to some fixed functionality, accessible easily to re-execute it from many places. In Visual Basic, instead of static keyword you would use shared keyword, which nicely explains the purpose of the static method.
Finally, I personally recommend creating static methods as Pure functions, which always produce same output for the same input (no side effects, such as output is different based on time or other implicit factors). You should have a strong reason to design it otherwise (e.g. if you are writing Math.Random()).
Now, to answer the points from your question (I know, finally):
I think business access layer should not be static, because you would most likely need benefits of non-static classes, such as dependency injection and unit-testability.
There is no difference between static and non-static methods from the threading/multithreading standpoint, both of them can be called by multiple threads at the same time and all of them will execute simultaneously (unless using synchronization constructs). However, there is common design recommendation that you should make static methods thread-safe if you expect race conditions. Non-static methods don't have to worry about this, as this would put them into too many assumptions.

How to structure classes in a C# program

I have a VSTO (Excel) project written in C#. Three questions:
I have a lot of variables that are populated once and then referenced extensively throughout the project. So I created a public static class which I called "Omni" - since that is both descriptive and short. Is something like this the recommended approach?
I put common functions in a public static class that I named "Utilities". I then used the "this" keyword as the first parameter, making them extension methods. They can then be accessed from anywhere - without using a "Utilities." prefix (although I'm not exactly sure why). Same question: is this the preferred way of doing this?
Finally, I have some common 'subroutines', i.e., public void methods. So parameters are passed in and processed, but nothing is returned. Should such common code just go in its own appropriately named public static class and then get called with the class name as a prefix? If so, is there any convention as to what the name of the class would be?
I realize these are newbie type questions (and I have been searching for a while!). Thanks.
Regarding your points
I have a lot of variables that are populated once and then referenced
extensively throughout the project. So I created a public static class
which I called "Omni" - since that is both descriptive and short. Is
something like this the recommended approach?
Yes, it is common practise to centralize for example string constants that
are often used.
If you have more of those, I would start to structure those to different
classes.
If you want that to be flexible and e.g. have cases where there are
mappings between constants, like Green = 1, I would move to some
enumeration value technology.
More on that idea can be found in this article
If the value does not change between different starts of your application,
check if you can use resources for that, which is often a good choice
for string constants to.
I put common functions in a public static class that I named
"Utilities". I then used the "this" keyword as the first parameter,
making them extension methods. They can then be accessed from
anywhere - without using a "Utilities." prefix (although I'm not
exactly sure why). Same question: is this the preferred way of doing
this?
Extension methods are a handy way of getting things like conversions done.
Just do not everything as an extension, just conversions as a rule of thumb.
Finally, I have some common 'subroutines', i.e., public void methods.
So parameters are passed in and processed, but nothing is returned.
Should such common code just go in its own appropriately named public
static class and then get called with the class name as a prefix? If
so, is there any convention as to what the name of the class would be?
This, in opposite of the others, looks like a design flaw.
Perhaps you can provide more information on what those subroutines do.
In object oriented code, code is distributed near the objects it is working
with. If you depend heavily on code that is in static classes, probably there
is something wrong. Do your static classes have members? Do they share some
knowledge between different calls to your static classes?

Singleton rule questions (do not allow to create copy and deserialization)

Reading some article about singleton, I stopped at the point saying: "Do not allow to crate copy of existing instance".
I realized that I do not know how would I do that! Could you tell me, please, how could I copy existing instance of class?
And the second one: deserializaition. How it could be dangerous?
And for both - how to deny creating copies or deserialization?
Thanks
There are objects with something like a Clone or a Copy method. The idea behind it that it will take the current values of the object and make a new one. The defeats the purpose of a singleton object, because suddenly someone can create a second copy of it.
Another possible way of creating a copy of the object, would be to serialize the object and then de-serialize it to create another copy. So you probably want to mark the singleton object as not serializable.
Using serialization/deserialization, you could store the object somewhere and then restore it. That way, you will have two objects. Any changes made to the singleton in the meantime would not be reflected in your new copy.
Afterwards, when you now try to get/set something using the singleton object, you might change it in/get it from the one object or the other. Obviously that can cause all sorts of (sometimes very hard to debug) problems.
EDIT: To create a singleton in C#, see the explanation at http://www.yoda.arachsys.com/csharp/singleton.html
As for serialization: You have to explicitely enable it by including the SerializableAttribute. So simply don't mark your class with it. Note that there is no NonSerializableAttribute for classes, only for fields. It is used when you enabled serialization, but want to deny it for certain parts of the class.
EDIT2: To deny XML-serialization, you could implement IXmlSerializable on the class. Then simply either have empty implementations or throw exceptions from the member methods.
As has already been mentioned:
You don't want to make a singleton serializable or copy/clone-able because then you can make more than one object, which defeats the purpose of the singleton.
To prevent serialization in c# is easy - don't mark the class as [Serializable]
To prevent copying/cloning of your singleton you could try changing it to a static class so that can't be instantiated (in the normal way) if that's practical. I'm not sure if the class is technically a singleton any more then.
Another way (probably better) is detailed in Item 13 of Bill Wagner's Effective C#. i.e. using a static constructor and making your singleton a read only property of your static class.
Example:
public class SingletonExample
{
private static readonly SingletonExample singleInstance
static SingletonExample()
{
singleInstance = new SingletonExample();
}
public static SingletonExample Instance
{
get { return singleInstance; }
}
private SingletonExample()
{
}
}
There are a few things to look out for, like Kevin mentioned any sort of .Clone() or .Copy() methods. If your building the class your self, then be carful with the .MemberwiseClone() method as it will make shallow copies of the object.
As far as serialization. Preventing general serialization can be done by not tagging [SerializableAttribute()] to you class. I'm not sure there is a way to prevent XmlSerialzation, directly. But there are a few things you could do to prevent this if your building the class.
If you're building the class, and you do not provide a default constructor then the XmlDeserializer will not work as it uses the default constructor to rebuild the object. I belive this funcitonality has changed in 4.0 however, so you may want to look more into that. Using the [XmlIgnore] Attribute on yoru fields and properties will render the serialzation useless as well.
The important part here is that the person trying to do this understand it shouldn't be done, not that it can't. If someone really wants to do serialization/deserialization on your class, then you can't stop all avenues as he can implement his own serialzation/deserialization of your object. Also serialzation of singletons is sometimes intended such as the cases of application settings or custom settings. The intent is to inform somehow the person trying to serialize/deserialize not to do so.

Techniques for sharing a value among classes in a program

I'm using
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\MyProgram"
As the path to store several files used by my program. I'd like to avoid pasting the same snippet of code all over the my applcation.
I need to ensure that:
The path cannot be accidentally changed once its been set
The classes that need it have access to it.
I've considered:
Making it a singleton
Using constructor dependency injection
Using property dependency injection
Using AOP to create the path where its needed.
Each has pros and cons.
The singleton is everyone's favorite whipping boy. I'm not opposed to using one but there are valid reasons to avoid it if possible.
I'm already heavily using constructor injection through Castle Windsor. But this is a path string and Windsor doesn't handle system type dependencies very gracefully. I could always wrap it in a class but that seems like overkill for something as simple as a passing around a string value. In any case this route would add yet another constructor argument to each class where it is used.
The problem I see with property injection in this case is that there is a large amount of indirection from the where the value is set to where it is needed. I would need a very long line of middlemen to reach all the places where its used.
AOP looks promising and I'm planning on using AOP for logging anyway so this at least sounds like a simple solution.
Is there any other options I haven't considered? Am I off base with my evaluation of the options I have considered?
I've never seen a problem with creating a static class like Environment for my own projects, when there's been strong enough need.
MyAppEnvironment.ApplicationFolder
If you're passing the value in using injection then you're either a) creating a class just to hold the value or b) passing in a string. The latter is bad, because your value should be constant. The former is valid, but seems like a fair overhead since there's only ever a single valid value (and you can still mock/fake that value for tests if you really need to).
I suppose you could inject your environment class, but for me this seems like overkill.
It seems like what you have amounts to a global setting within your application. Using AOP o constructor injection to pass around this dependency seems like quite a bit of overkill since a simpler solution would do the trick.
My preference here would be to use a static property on a static class. I would add a specific write routine that prevents multiple sets. For example ...
public static class GlobalSettings {
private static string s_path;
public static string Path { get { return s_path; } }
public static void UpdatePath(string path) {
if ( s_path != null || path == null ) { throw ... }
s_path = path;
}
}
We would constructor inject a class of type IMyAppConfig which is just a wrapper for all this kind of stuff.
if you have a standard .net application, you should already have a settings - class. you could create a new setting and set that value as default value or so.
My process is to always ask questions like these: What kinds of things can change? What would create the least amount of pain when those things change? What pieces can be re-used in other systems, and how can the pain of the reuse be minimized? Basically, how can these things be decoupled as much as possible?
With that in mind, the answer is really based on the details of the system that you are working on.
In whatever process uses this path, I would likely pass it down as a parameter. This would start at whatever action initiates the use of the path. Each method should "do one thing well", and if the path is part of that thing, then it should be a parameter. In the class that initiates the action (and in whatever classes control the lifetime of that class, etc.), I would likely make the path part of the constructor.
This is the method that I have used in the past, and it has served me well. For example, in one application I took this approach, and then later discovered a need to allow the user to change the path setting. By following this architecture (and avoiding a singleton) the objects that had already used the path could continue to use the old one without an error, but the new path was used correctly from the point of the change. It just worked.
And the classes can be migrated to a new project without a dependency on this particular detail.

Categories