In object-oriented programming, static methods are the methods that are defined with static keyword. They don’t have access to non-static instance variables. This very limitation can be an easy cure for many programming pitfalls I’ve seen over the years.
- A static methods prevents you from using instance variables for passing information around, for example, as parameters to or as result from it. As a general rule, you should not define an instance variable if it’s not an intrinsic property of a class or type. It may seem obvious, but you’ll be surprised to see how much code with this issue. Using instance variables as parameters produces bad code because readers will have trouble to make sense of these variables.
- A static method is more modularized and portable. More often than not, you can move a static method from one class to another class without modification. This helps a lot when you need to refactor your code, which is a routine work in software development nowadays. With no implicit reference to instance variables, the input/out of a method is very clear.
Having said that, you can still define static variables in your class and use them to pass information into or out of your static methods. In theory, that is absolutely true. In practice, I’ve seen far less, if any, of such usage because most of us use static variables as constants with all upper case names.
- A static method is easier to test. Because the inputs and output are clear and direct, it’s easy to write unit tests. You don’t have to worry about what properties to set up before calling the methods to be tested.
I don’t suggest you put “static” keywords with all your methods. In fact, I think that is sometimes a little awkward and may go back to functional programming style. I do encourage you to code your methods like static ones whenever possible, even though there is no static keyword. In other words, your methods should be ready to add static keywords up front and still compile.
Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.