Static Classes & Class design - c#

While designing my data access layer, I wanted to make all my classes Static so that no object instantiation is required and all members of the class can be access using the class name.
Is this a good approach. If yes then why do we need to have a instance class type at all. Would it have an impact on the performance of the application where n clients want to access my DAL and then might cause a problem with managing the request(s) because no object is created at all?
I understand that static classes cannot be instantiated, and should be used for something like Logging, Utility methods etc, because all objects need to behave in a similar way, Is it valid/safe to assume that all DAL classes does behave the same way (have the same functionality) and hence make them static rather than instantiating it.
Please advice.

Either the type conceptually represents operations that are tied to instances, or it doesn't. Performance is not a consideration here.
If your methods have no state, or their state is designed to be shared between all invocations of the method throughout the application, then the method should be static. If there needs to be separate state shared between members but not shared with the entirety of the application then they need to be non-static. The type will generally require one or the other based on what it conceptually represents. It's not an actual choice.

Static classes are generally best avoided as they introduce tight coupling into your code. They make unit testing much harder because the calls are "hard wired" and can't be easily stubbed out.
Much better would be to make them instances, but only instantiate a single instance. If you couple this with dependency injection (i.e. passing the DAL object into the classes that need it) then you get looser coupling and can pass in a stub version for unit tests - look up Unity or Castle Windsor or other IoC frameworks to see how this works.

There is an impact on performace - static method calls are faster than instance method calls, especially if you address late binding. But that's also the big advantage of object-oriented programming.
If you just use static classes and therefore static method calls, you do not have the ability to 'exchange objects' - and that is, in my opinion, the most important part of object-oriented programming. Have a look at the SOLID principles of Object-Oriented Design and you'll learn about the real benefits of this programming style. Of course this might come with a performance penalty, but usually you won't have to think about it, except if you want to program e.g. real-time applications. Correct usage of OOP and OOD makes your code extremely flexible and (somewhat) easy to understand.

A useful design pattern for this is a variation of a singleton. Set up your static implementatation, leaving the static methods private, exposing them via an object instance, like this:
class MySingletonClass
{
//-----------------------------------------
// here, we hide the static implementations
//-----------------------------------------
private static int privateFoo()
{
/* do something useful here */
}
private static string privateBar()
{
/* do something useful here */
}
//---------------------------------------
// and expose them via an object instance
//---------------------------------------
public int Foo()
{
return privateFoo() ;
}
public string Bar()
{
return privateBar() ;
}
}
Your static class now has the same semantics as an ordinary object instance. Static methods are invoked thus:
SomeStaticClass.SomeStaticMethod() ;
while non-static classes are references thus:
SomeNonStaticClass instance = new SomeNonStaticClass() ;
instance.SomeNonStaticMethod() ;
By exposing the [private] static methods via instance methods, you have hidden the
implementation from the object's users. Down the line, then, when you realize that
your static methods won't work any more (for whatever reason) and the class has to
become non-static, all you have to do is modify the internal implementation of the class.
If your class's users were directly referencing the static methods, you would have to change
every reference in your code base.

Related

dependecy injection and unit testing - static helper methods or private instance methods

From unit testing and dependency injection point of view, what's the usual adopted norm when it comes to helper methods?
Here is my example situation:
public class GoodiesController : Controller
{
private IMyContext _context;
public GoodiesController(IMyContext context)
{
_context = context
}
public async Task<IAction> GetThoseGoodies()
{
if(YouLikeThemThisWay(Request.Path))
{
var result = await _context.GoGetThemThisWay()
} else { }
}
My question is am I better off with YouLikeThemThisWay(string path) as a static helper in some class or as a private instance method? Assuming I might have a couple of the likes of YouLikeThemThisWay?
It really depends on what your YouLikeThemThisWay(string path) method does. My rules for using a static method or as follows:
Does it require a non-primitive dependency? If so, don't use static.
Does it affect the state of the application? If so, don't use static.
Does it extend the functionality of a class or type you do not have access to internally (IE BCL classes or primatives)? If so use a static extension!
Will it impact unit tests--as in make them more difficult--if I cannot mock the routine? If no, then make it static!
Will it be used by more than one type or class? If so that it makes it a better candidate for static!
Does the routine perform some sort of IO, like calling a database or the filesystem? If so, I would not make it static.
Basically, small helper functions that are easily tested and don't affect state or usually OK to make static. If there is state involved, the routine requires a dependency that you would normally inject, or the routine is making IO or IPC calls then do not make it static.
One caveat to the dependency issue is technically you could use method injection to handle the dependencies, but I like to keep it simple. Your method is probably OK to be static.
Reuse is a big factor in statics too. If the routine will only be used in one class, it may be pointless to make static. Most of my static methods live in helper classes that are easily accessed anywhere.
EDIT: Note that I usually require most or all of those five rules to favor statics in order for me to even consider making something static.

Which method type should be used

i was wondering, what kind of method i should be using
public class UserProfile {
public String GetAsString(){
... Some Stuff
return anyString;
}
// Or this one
public static String GetAsString(UserProfile profile){
... Some Stuff
return anyString;
}
}
Are there any performance issues, or anything i should be using one of these methods?
Thanks for helping me
In an object-oriented language like C# your primary choice should be always instance members over static members.
Static members...
...are part of no instance.
...can't be polymorphic (i.e. virtual).
...can't access instance members. So, it's all or nothing if you thought you could mix static and instance members just because of performance issues (although instance members can access static members...).
Actually, the main issue with using statics in terms of software architecture is that they turn classes into just modules or containers of functions instead of considering classes as archetypes of objects.
Statics are good to implement factory methods, constants, singletons and some other requirements, but they shouldn't be considered as an alternative to pure object-oriented programming per se.

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.

Using optional singletons in OOP?

I'm writing a PCL in .NET and I have a wrapper class around HttpClient that loads an HtmlAgilityPack.HtmlDocument from a URI in multiple different methods. It is stateless, so I would really like to make it static, since in my opinion instantiating something with new gives the impression that it contains state. However, I have a couple of interfaces that I want it to inherit from, so it can't be static. This is where I thought of making it a singleton. Here are a few snippets from the code:
public class ConcurrentClient : IAsyncClient<HtmlDocument>
{
private static readonly ConcurrentClient _Instance = new ConcurrentClient();
private ConcurrentClient() { }
public static ConcurrentClient Instance
{
get { return _Instance; }
}
public HtmlDocument LoadUri(string uri)
{
return LoadUriAsync(uri).Result;
}
// ...
public async Task<HtmlDocument> LoadUriAsync(string uri,
Encoding e, NetworkCredential creds, Action<HtmlDocument> prehandler)
{
// ...
}
}
I'm wondering, though, if I should change the beginning parts to this:
private static readonly ConcurrentClient _SharedInstance = new ConcurrentClient();
public static ConcurrentClient SharedInstance
{
get { return _SharedInstance; }
}
The reason for this is I'm not that sure about using the Singleton pattern, mainly because I've rarely seen it in use in other libraries (maybe WinRT's Application.Current?), and I think it would encourage users of my PCL to write coupled code, since it's much easier to just call ConcurrentClient.Instance everywhere than it is to pass it in as a parameter.
However, I do want to encourage the use of a shared instance because excluding the reasons above, there's very little point in calling new ConcurrentClient() because all it does is create more memory overhead. Also, I can't think of a better way to implement inheritance with methods that don't really rely on state.
Your Singleton already implements 2 interfaces. The question really is, where are the dependencies to this Singleton and why are they there ?
If the answer is that these dependencies are there because they need to get to the implementation of those interfaces then I would say that this is wrong.
The whole point of doing a SOLID design is to have dependencies towards interfaces and not towards any concrete implementation. So anyone who needs any of these 2 interfaces should be given those interfaces via dependency injection. So that means that the interfaces would be passed by their constructor or via an extra parameter in a method call, a strategy pattern, ...
Also see this : http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
There can be a reason to make a singleton, but based on your explanation this is not that clear.
Investigate more of your time in using dependency injection. If you have that under control move one step further and investigate on how you can use an inversion of control container.
Also, it's easy to forget DI and passing around the object as a parameter when you can just access it by Singleton.Instance.
You are forgetting about unit testing. If you pass interfaces to your class constructors you can easily mock those interfaces and test your class functionality. With your singleton in place, your classes really need that singleton. Unit testing will be harder.
Of course Instance is easy to access, it's a global and since people revert back to old habits of programming towards objects all the time, that is why it is so popular.

Is this physical collection class that contains only static methods an Anti-Pattern?

I'm trying to figure out if I should continue on with a current pattern in an application I'm working in, or refactor this into something else.
I have a set of collection classes off a generic base of List. These classes have public constructors but contain only static methods that return collections. They look like this:
public class UserObjCollection : BaseCollection<UserObj>
{
public static UserObjCollection GetAllUserObj()
{
UserObjCollection obj = new UserObjCollection();
obj.MapObjects(new UserObjDataService().GetAllUserObj());
return obj;
}
}
Is this a Pattern or Anti-Pattern and what are the merits of this over a straight factory pattern?
EDIT: I'm leaning towards removing these physical collections, and moving their static methods into the data access layer (UserObjDataService). There are a lot of object types so I need to keep the code in seprate places, but they almost all have a 1 to 1 factory object in the datalayer.
UserObjCollection does not add anything to BaseCollection<UserObj>, objects of both classes are identical, functionality wise. It would be nicer to remove UserObjCollection and put GetAllUserObj() in BaseCollection<T> (Factory Method). You can also put GetAllUserObj() in a seperate static class. I don't think the abstract factory pattern is necessary here, as you're not creating different object families.
The reason why I would remove UserObjCollection is because this class might cause other developers to add to it without thinking it through. If it later turns out that UserObjCollection is in fact sufficiently different from BaseCollection<UserObj> that it warrants a separate class, you can re-add UserObjCollection then.
I tend to call this factory method pattern (possibly incorrectly).
Because I am doing only Test Driven Development these days, I tend to avoid it, because it is very difficult to test. In your static method you create a lot of concrete classes, so you can't really mock any of these objects. Moreover you can't mock the whole static method either, which makes all the classes fairly tightly coupled. A straight factory patterns would at least allow to mock the whole factory object, which makes testing much easier.

Categories