Static methods in OOP

I always knew what static methods were by definition, but I always avoided using them at school because I was afraid of what I did not know.

I already understand that you can use it as a counter throughout the project.

Now that I am doing interning, I want to know when static methods are used. From my observations so far, static classes / methods have been used when it contains many functions that will be used in many different classes, and by itself does not contain too many critical local variables in the class, where there is no need to create an instant of it.

So, as an example, you can have a static class called Zip that zips up files and unpacks them and provides them with many different classes so that they can do something with it.

I'm right? Do I have a right idea? I am sure there are many ways to use it.

+5
source share
4 answers

Static functions are useful because they do not rely on a member instance of any class to which they are bound.

Static functions can provide functionality related to a particular class without requiring the programmer to instantiate this class.

Check out this comparison:

class Numbers { public int Add(int x, int y) { return x + y; } public static int AddNumbers(int x, int y) { return x + y; } } class Main { //in this first case, we use the non-static version of the Add function int z1 = (new Numbers()).Add(2, 4); //in the second case, we use the static one int z2 = Numbers.AddNumbers(3, 5); } 

I hope this example shows why static functions / methods are useful and useful for optimization, since they do not require you to create anything to use them.

+11
source

Technically, the answers above are correct. But the examples are wrong from the point of view of OOP.

For example, you have a class like this:

 class Zip { public static function zipFile($fileName) { // } public static function unzipFile($fileName) { // } } 

The truth is that there is nothing object oriented. You just defined two functions that you need to call using fancy syntax like Zip::zipFile($myFile) and not just zipFile($myFile) .

You are not creating any objects here, and the Zip class is used only as a namespace.

Therefore, in this case, it is better to simply define these functions outside the class, as ordinary functions. There are namespaces in php since version 5.3, you can use them if you want to group your functions.

Using the OOP approach, the class will look like this:

 class ZipArchive { private $_archiveFileName; private $_files; public function __construct($archiveFileName) { $this->_archiveFileName = $archiveFileName; $this->_files = []; } public function add($fileName) { $this->_files[] = $fileName; return $this; // allows to chain calls } public function zip() { // zip the files into archive specified // by $_archiveFileName } } 

And then you can use it as follows:

 $archive = new ZipArchive('path/to/archive.zip'); $archive->add('file1')->add('file2')->zip(); 

More importantly, you can now use the zip function in the OOP method.

For example, you can have an Archive base class and subclasses like ZipArchive , TarGzArchive , etc.

Now you can create an instance of a specific subclass and pass it to another code that does not even know if the files will be zip-ped or tag.gz-ipped. For instance:

 if ($config['archive_type'] === 'targz') { // use tar.gz if specified $archive = new TarGzArchive($path); } else { // use zip by default $archive = new ZipArchive($path); } $backup = new Backup($archive /*, other params*/); $backup->run(); 

Now the $backup object will use the specified archive type. Inside, he does not know and does not care about how the files will be archived. You can even have a CopyArchive class that simply copies files to another location.

This is easy to do because your archive support is written in OOP mode. You have a small object responsible for specific things, you create and combine them and get the desired result.

And if you just have a bunch of static methods instead of a real class, you will be forced to write a procedural style .

Therefore, I would not recommend using static methods to implement the real functions of your application.

Static methods can be useful to support logging, debugging, testing, etc. For example, if you want to count the number of objects created, you can use a static class counter, increment it in the constructor, and you can have a static method that reads the counter and prints it or writes it to the log file.

+2
source

Yes, static classes are used for problems requiring stateless computing. For example, adding two numbers. Pin file. Etc.

If your class needs a state in which you need to store connections or other longer live objects, you will not use static ones.

0
source

AFAIK. Static methods are independent of the class instance. Just this.

As an example: If you have one thread program that will have only one database connection and will make several database queries, it would be better to implement it as a static class (note that I indicated that you will not connect ever to multiple databases or multiple threads). Therefore, you do not need to create several connection objects, because you already know that you will use only one of them. And you will not need to create multiple objects. Singletones in this scenario are also an option.

There are other examples.

If you create a class to convert values.

 class Convert{ static std::string fromIntToString(int value); } 

That way, you won’t need to create a class conversion every time you need to convert from integer to string.

 std::string value = Convert::fromIntToString(10). 

If you have not already done so, you will need to instantiate this class several times through your program.

I know that you can find several other examples. It is up to you and your script to decide when you are going to do this.

0
source

Source: https://habr.com/ru/post/1241835/


All Articles