82

The characteristic of being static is independent of the visibility. The reasons that you will want to have a static method (some code that does not depend on non-static members) will still be useful. But maybe you don't want anyone/anything else to use it, just your class.


42

A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance. I've done similar things ...


39

Then all tests of Foo.Do will depend on the success of TestToHex_Works. Yes. That's why you have tests for TextToHex. If those tests pass, the function meets the spec defined in those tests. So Foo.Do can safely call it and not worry about it. It's covered already. You could add an interface, make the method an instance method and inject it into Foo. Then ...


38

There is no reason why this needs to be injected. This is just a function, it has no dependencies, so just call it. It can even be static if you want as it looks to be pure. One can write unit tests against this with no difficulty. If it is used in other classes, unit tests can still be written. There is no need to abstract away functions with no ...


34

A trivial example: when the instance passed can legitimately be null and you want to incorporate the (non-trivial) handling of this into the method.


31

A fairly common reason (in Java) would be for initializing immutable field variables in a constructor by using a simple private static method to reduce constructor clutter. It is private: external classes should not see it. It is static: it can perform some operation, independent1 of the state of the host class. A somewhat contrived example follows... eg: ...


26

What's the difference between new CustomerReceiptCreator().createReceipt() and CustomerReceiptCreator.createReceipt()? Pretty much none. The only significant difference is that the first case has considerably more awkward syntax. If you follow the first in the belief that somehow avoiding static methods makes your code better OO, you are gravely mistaken. ...


23

Methods are not stored on a per-instance basis, even with virtual methods. They're stored in a single memory location, and they only "know" which object they belong to because the this pointer is passed when you call them. The only extra memory required in C++ is if you're using virtual methods, which require a single extra pointer per instance to point at ...


21

A common use-case for a private static method is a utility method which is only used by that one class is independent of the internal state of that class


20

In your example, the instance method is a clear winner. In the general case, I can think of a few reasons where a static method might be appropriate: You want to put the static method in another class, since you have a situation where it makes sense to separate the logic from the data (note: your example is not one of them). You are passing two or more ...


19

You see that you have a few lines of code that is repeated in a lot of your methods, so you decide to extract them to a single method, as duplicated code is not good. You make the method private as it is not designed for widespread usage and you don’t want unrelated code calling it. (Debate this point in the comments….) As the method does not access any ...


19

In my opition it's ridiculous to mock out a dependency on a static utility method for things such as string splitting. Yes, if the splitter method is wrong it might cause spurious failures in tests for methods that aren't about string splitting. But that's not the point of a test suite. The test suite must succeed 100%, period. If it doesn't, you fix what'...


18

In Java, private variables are visible to the whole class. They can be accessed from static methods and from other instances of the same class. This is, for example, useful in factory methods. A factory method usually does initializations to an object which are so complex that you do not want to leave them to the application code. In order to do the ...


15

With the static methods, there is no object to provide proper control of the override mechanism. The normal class/instance virtual method mechanism allows for finely tuned control of overrides as follows: each real object is an instance of exactly one class. That class determines the behavior of the overrides; it always gets the first crack at virtual ...


15

So, should such methods (and, in this case, the entire class) be static? No. Or at least, you shouldn't use them directly as statics. If you're working with various hardware components, you're very very likely to want to mock them, use new ones, and pick which one you're using. That all shouts for having an interface (or other abstraction) so the rest of ...


14

Avoid the Gang of Four Singleton pattern, for reasons cited in the other answers. Mainly it is an anti-pattern based on difficulties it creates for testing. Factory and Dependency Injection made Singleton obsolete. The best answer is to use a Factory that decides whether to instantiate one instance, or many, of a given class. That way, the class and its ...


13

Here's why class DOSClient { OrderParser orderParser; string orderCode; DOSClient(OrderParser orderParser, string ordercode) { this.orderParser = orderParser; this.ordercode = ordercode; } void DisplayOrderCode() { Console.Write( "Prefix: " + orderParser.GetStringPart(ordercode) ); ... } } class ...


12

Interesting question, I tested it this way: Superclass public class ClassA { public static void printStatic(){ System.out.println("hi static from A"); } public void printDynamic(){ System.out.println("hi dynamic from A"); } } Subclass public class ClassB extends ClassA { public static void ...


12

No, your first code snippet will not create a new weapon every time you reference it. The second example you posted is an example of the singleton pattern. Based on your comment at the bottom of your first example, it seems to indicate that you will have over 100 instances of different weapons. This is a lot. You're right that you don't necessarily want to ...


12

I think extension methods are more "discoverable". If I have a certain type, Intelli-sense will automatically give me the extension methods. When a static class and method, I have to know the name of the static class so I can reference it. In small projects, this may not make a difference, but this larger projects with several directories and many ...


10

On the other hand, these principles make using static methods and factories necessary. Since when? I think static methods should be out of any good object-oriented design, since they pollute the code with imperative programming practices that don't have anything to do with pure OOP. You could, but you'd be wrong. Modern OO design often includes static ...


10

Overriding depends on virtual dispatch: you use the runtime type of the this parameter to decide which method to call. A static method has no this parameter, so there's nothing to dispatch on. Some languages, notably Delphi and Python, have an "in-between" scope that allows for this: class methods. A class method is not an ordinary instance method, but it'...


10

Named Constructors in PHP Don't limit yourself by PHP's single constructor. Use static factory methods. The article is not about coupling. There is zero difference in coupling between using new Customer(/* some args */) and Customer::fromFoo(/* some args */). Where you put those expressions determines how coupled they are. All the "Factory Pattern"...


10

You have shown two extremes ("everything private and all (maybe unrelated) methods in one object" vs. "everything public and no method inside the object"). IMHO good OO modeling is none of them, the sweet spot is somewhere in the middle. One litmus test of what methods or logic belongs into a class, and what belongs outside, is to look at ...


9

If not every implementer of Foo is supposed to contain operation(), then operation() cannot be declared in Foo, plain and simple. Programming against interfaces rather than concrete classes is a good idea, but only if the interface actually is sufficient for your needs. If you need to call operation(), then you should declare FooImpl, or maybe a custom ...


9

Having static helper functions to create the constructor argument is a perfectly sane solution, but these functions are limited in what operations they can perform since they must produce exactly one argument each, and cannot communicate with each other. In the most general case where you want to adapt an interface Constructor(A, B, C) to a more usable ...


9

Is it conceptually static? Would the caller assume that the method relates to an instance and not to a class as a whole? Would the caller usually have an instance of the class available at the time of the call? Let's say I have a class for user interface buttons. And these buttons can have a title, a color, and a font for that title. But for some reasons, ...


9

Late answer but I can't resist. Is X most classes into Y good or an anti-pattern? In most cases, most rules, applied without thinking, will mostly go horribly wrong (including this one). Let me tell you a story about the birth of an object amid the chaos of some down right, quick and dirty, procedural code that happened, not by design, but out of ...


9

The biggest advantage for me is readability. Consider for a moment a typical LINQ statement that uses method chaining: var total = myList.Where(x => x.num > 5) .Select(x => x.num) .Distinct() .Aggregate((total, next) => total + next); Pretty easy to read. But you could use the static ...


9

Practically in 99.9% of cases: no. Theoretically: maybe. You won't be passing the implicit this parameter to every function, and not passing that could save you bytes and the time passing those bytes. The compiler may well optimise it away though in any case. If profiling has shown one of these functions is on your hot path, it might be worth considering. ...


Only top voted, non community-wiki answers of a minimum length are eligible