What is the desired situation (real life example) for creating static methods other than creating an assistant?

I just want to understand the purpose that the static method serves, and what is the desired situation where I can create static methods, except for some that say that static methods are used to create a helper.

I have 1 website that will be used in my company only as a Human Resource Management System , as websites.

Now, after the administrator logs in, the administrator will see a list of employees. So the method is simple, which does nothing more than get all the details of employees from the employee table and displays them on the website, and this method will be in the business access layer, for example, 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 a static or non-stationary method?

Note. This is just an example of a method, and this method is at my level of access to business .

I have 1 e-commerce site where on the home page I show some list of products, and when visiting this site each user can see this list of products.

so my function will be the same as above in the Business acess layer:

 public class ProductBal { public List<Product> DisplayProductonHomePage() { return Select * from Products } } 

So my question will be the same as creating this method as a static method or a non-static method, and what happens if more than 10 users can access this website at the same time, what will be the behavior / consequences of this method ???

Will this method serve the purpose of this each user if we declare this method as static?

Can someone answer this question by briefly explaining each scenario ???

+6
source share
7 answers

The static method makes sense when there is no state to save. What do I mean by state? Well, consider the following: you have two different objects: a and b , which are both types of EmployeeBal . Is there ever a case in your program where a.GetAllEmployees() and b.GetAllEmployees() will give different results?

If not, why do objects a and b exist at all? The whole point of having objects is to associate some specific state with them. If two different objects can never refer to another state, then they have no purpose.

In fact, in this situation, your EmployeeBal will be exactly equivalent to System.Math , and all of its methods will be "helper methods" (if that's what you want to call). 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 like EmployeeBal just doesn't make sense. In fact, in other languages, an EmployeeBal would not be a class at all; instead, it will be something commonly called a module: a block that logically groups code. C # does not have modules, and all code must be inside classes. Classes thus fulfill a dual purpose: they group code and generate objects. 1

Now consider a less extreme case: EmployeeBal objects actually maintain state and are different. However, GetAllEmployees() will still produce 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 therefore does not belong to objects of type EmployeeBal . And so the method should be static.


1 This lack of distinction between two fundamentally different concepts (module and class) is actually quite annoying, and the main reason C # behaves this way is because it was conceived as similar to Java. It was a mistake in retrospect, but not serious.

+7
source

Is there a reason why the method should be static? If not for me, I would always be unsteady. One big reason is the ability to write unit tests. To write unit tests, you want to highlight the class that you are testing from other classes. But if class A contains a reference to static class B, then you cannot test A without testing B. Perhaps B depends on the connection strings or configuration settings. Perhaps B depends on other static classes. Now you canโ€™t check A if B and everything it depends on is in place.

If, on the other hand, class A depends on an interface, such as IEmployeeProvider , that is provided through its constructor, then you can test class A with a laughed implementation of IEmployeeProvider .

If A has an IEmployeeProvider as an argument in its constructor, you can tell by looking at the constructor that it depends on IEmployeeProvider . But if it depends on the static class EmployeeProvider somewhere inside the method, then the dependency is hidden. You must read the whole class to know what it depends on.

In addition, the static class itself may be more difficult to test. If it will not always remain stateless, then it is better to have a non-static class that you can unit test.

+4
source

It is good that several threads execute the same static method if the method does not have access to a static state, such as a field or properties. In this case, shared objects stored in fields / properties must themselves be thread safe. Parts of .Net data access are not designed to provide thread safety.

Once you begin to consider aspects such as managing a database connection that can be reused for multiple queries during the execution of a single web query, you should consider whether a static approach is best. Since you cannot save the connection in a static field as described above, you will have to pass it as a parameter for each static method. On the other hand, if you pass the connection to the constructor and save it in a (non-static) field, you can access it from several non-static methods of this instance, which will facilitate the management of IMO.

This is a pretty big topic, and overall class dependency management is pretty hard to get in OOP. Some programmers prefer to delegate this task to the "Inversion of Management" library. There are many available for. Net such as Microsoft Unity, StructureMap, AutoFac, etc.

+3
source

To answer your question:

So my question is: should I create this method as a static or non-stationary method? Note. This is just an example of a method, and this method is at my level of access to business.

I would make these methods static - considering what you provided. But I'm sure that you will have instance variables declared in your class, or methods in this class, which of course mean that it is not static.


Thus, the determining factor for me, if I decide to use the static method or not, is related to reuse and resources.

If I re-use the method many times, and I conclude that it does not need a state (stored in memory), I will make it a static method.

In addition, I usually set my methods static if they can be used in other applications, or if I think they will be useful in the future.

For example, I recently wrote a method that converts an excel file to a flat file. I made it a static method in my own static class (I can put it in a similar utility class in the future), because I will probably end up using it again in another project, so now I can just reference its class, not creating a new object to call the method. (I still don't need a fortune)

I am also quite new to programming, and I hope you find this helpful.

+2
source

If we talk about static, we need to introduce a dependency. In this case, it is a sql client. This is what the code you entered looks like. Since we are not going to go into the details of the sql client, it is used as an interface in a 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"); } } 

Enabling dependencies through an interface changes everything. Now the method is good as static, because it deals only with the interface and the string. Both are stateless. Since all components of the method have no state, they are completely safe for a static method, which can have only one global state.

Since your code was originally written, it is unsafe as static, since I can be sure that the sql client is ready to use, and after I checked that it was ready, it wasnโ€™t changed when I go to start the query? If I can add an sql client, I can manage it, since it has a local or global scope.

A better example might be something like a factory for sql client. For example, with nhibernate, only one factory session should be created. This factory session can create multiple secure sessions without streaming to execute sql queries. In this case, it is advisable that the factory session is displayed through the static method, because this describes the fact that only one factory session will be displayed once.

 var session = SessionFactory.OpenSession(); 
+2
source

The use cases for static and non-static methods are different, so you need to create them based on what they need to do:

  • The static method is not involved in inheritance-based polymorphism, while the non-static method. In other words, you cannot mark a static method as virtual or abstract, which means you cannot change its behavior. It also means that the caller of the static method knows exactly what this static method will do and how. Using a non-static method, you can call it in the base class, but due to polymorphism, you can call the derived class method with excessive behavior.
  • Both static and non-static methods can change the state of something (unlike others), but there is a difference. You can create a static class in which there are all static members (properties, methods, etc.), therefore methods can change the state of this static class (at the same time C# allows you to do this, I In any case, it is recommended to create such a class) . Using the non-static method, you can change the static and non-static state of a class. This entails differences between static and non-stationary classes, which briefly means: a static class is one specific 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 artificial restriction then - thatโ€™s why I have not recommended them before).
  • Another nice use of static methods is extension methods. They should be defined as static, but you can call them in an instance of the class that they distribute. They still serve as external labels for the instance, since they cannot do anything more than regular static methods (for example, they cannot access private or protected members).
  • And you're right, a static class works well when defining helper methods, as they are usually just shortcuts to some fixed functionality that are easily accessible to be re-run from many places. In Visual Basic, instead of the static you use the shared keyword, which perfectly explains the purpose of the static method.

Finally, I personally recommend creating static methods like "Pure Functions" that always produce the same output for the same input (no side effects like output depends on time or other implicit factors). You must have a good reason for designing it (for example, if you write Math.Random() ).

Now, to answer the questions from your question (I know, finally):

  • I think that the level of access to the business should not be static, because you will most likely need the benefits of non-static classes, such as dependency injection and unit checking.
  • There is no difference between static and non-stationary methods in terms of streaming / multi-threaded processing. Both of them can be called by several threads at the same time, and all of them will be executed simultaneously (except for the use of synchronization constructs). However, there is a general design recommendation that static methods should be thread safe if you expect race conditions. Non-static methods should not worry about this, as this puts them in too many assumptions.
+1
source

Using static methods is equivalent to global behavior. It has advantages: ease of access for simple scripts.

It also contains all the problems that have global data and status. Among them, you cannot replace the implementation with another one (for example, for tests). See https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil

Although you might think that you do not have a global state ... conceptually, you have. You have a unique, predefined, non-configurable, hard-coded way to access some behavior. You published it, and you cannot change it ... ever. You violate the open-close principle. You violate the principle of replacing Liskov.

Java has this, but scala has amended. More on this here: Why does scala have static members inside the class?

+1
source

All Articles