3

For example,

public class ClassA {
    // no instance fields
    public int method1(int x, int y) {
        // do things...
        return x+y;
    }
}

I feel a strong urge to declare public static void int method(int x, int y), but it seems like "people in Java" do not like to use static method unless there is a good reason. What do you guys think?

gdlamp
  • 613
  • 1
  • 6
  • 24
  • Resist the urge to declare both `void` and `int`. – Tyler Jun 17 '16 at 21:03
  • 1
    `static` is underrated. One argument is that mocking is not possible. But if you own the entire codebase you don't need to mock methods. I say use static as much as possible, making your code more functional-style. – Sridhar Sarnobat Jan 20 '17 at 22:53

1 Answers1

0

Static methods are fine under the correct context.

Try to figure out if it makes sense to call a method, even if a class has not been declared.

For example, the Math methods in the java API. You want the convenience of being able to simply type:

Math.abs(value)

and not have to worry about pointlessly creating a class just to perform this function.

That being said, for your example:

public class ClassA {
// no instance fields
public int method1(int x, int y) {
    // do things...
    return x+y;
}

}

If that is all the code is doing, I don't see a reason why you would want to create a class with no instance fields just for the utilization of one method.

I would declare this as static.

Chris
  • 9
  • 3