Development Tip

Java 메소드는 기본적으로 정적이어야합니까?

yourdevel 2020. 11. 17. 21:14
반응형

Java 메소드는 기본적으로 정적이어야합니까?


foo()클래스 A에서 메소드 작성한다고 가정 해 보겠습니다 . foo는 A의 상태에 액세스하지 않습니다. foo가 무엇을하는지, 어떻게 동작하는지에 대해서는 아무것도 모릅니다. 그것은 무엇이든 할 수 있습니다.

다른 고려 사항에 관계없이 foo는 항상 정적이어야합니까? 왜 안돼?

작업을 나누고 한 번만 작성하는 원칙을 적용하기 때문에 내 클래스는 항상 많은 개인 도우미 메서드를 축적하는 것 같습니다. 이들 중 대부분은 객체의 상태에 의존하지 않지만 클래스 자체 메서드 외부에서는 유용하지 않습니다. 기본적으로 정적이어야합니까? 많은 수의 내부 정적 메서드로 끝나는 것이 잘못입니까?


제목에 대한 질문에 답하려면 일반적으로 Java 메서드가 기본적으로 정적 이어서는 안됩니다 . Java는 객체 지향 언어입니다.

그러나 당신이 말하는 것은 약간 다릅니다. 특히 도우미 메서드에 대해 이야기합니다.

값을 매개 변수로 사용하고 상태에 액세스하지 않고 값을 반환하는 도우미 메서드 의 경우 static이어야합니다 . 개인 및 정적. 강조하겠습니다.

상태에 액세스하지 않는 도우미 메서드는 정적이어야합니다.


1. 주요 장점 : 코드가 더 표현력이 뛰어납니다.

이러한 메서드를 정적으로 만드는 것은 적어도 큰 이점이 있습니다. 메서드가 인스턴스 상태를 알 필요가 없다는 것을 코드에서 완전히 명시 적으로 만듭니다 .

코드는 그 자체로 말합니다. 여러분의 코드를 읽을 다른 사람들과 미래의 어느 시점에서 여러분에게도 상황이 더욱 분명해집니다.

2. 또 다른 장점 : 코드는 추론하기 더 간단 할 수 있습니다.

메서드가 외부 또는 전역 상태에 의존하지 않는지 확인하면 순수 함수 , 즉 수학적 의미 의 함수 입니다. 동일한 입력에 대해 항상 동일한 출력을 얻을 수 있습니다.

3. 최적화 장점

방법은 정적 및 순수 함수 인 경우, 어떤 경우에는 수 memoized (메모리를 사용하는 변화)에 일부 성능 이득을 얻었다.

4. 바이트 코드 수준의 차이

바이트 코드 수준에서 도우미 메서드를 인스턴스 메서드 나 정적 메서드로 선언하면 완전히 다른 두 가지를 얻을 수 있습니다.

이 섹션을 더 쉽게 이해할 수 있도록 예제를 사용하겠습니다.

public class App {
    public static void main(String[] args) {
        WithoutStaticMethods without = new WithoutStaticMethods();
        without.setValue(1);
        without.calculate();

        WithStaticMethods with = new WithStaticMethods();
        with.setValue(1);
        with.calculate();
    }
}

class WithoutStaticMethods {

    private int value;

    private int helper(int a, int b) {
        return a * b + 1;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int calculate() {
        return helper(value, 2 * value);
    }
}

class WithStaticMethods {

    private int value;

    private static int helper(int a, int b) {
        return a * b + 1;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int calculate() {
        return helper(value, 2 * value);
    }
}

우리가 관심있는 라인 helper(...)은 클래스 WithoutStaticMethodsWithStaticMethods.

정적 메서드없이

첫 번째 경우 정적 메서드없이 도우미 메서드를 호출 할 때 JVM은 인스턴스에 대한 참조를으로 전달해야합니다 invokespecial. calculate()메소드 의 코드를 살펴보십시오 .

 0 aload_0
 1 aload_0
 2 getfield #2 <app/WithoutStaticMethods.value>
 5 iconst_2
 6 aload_0
 7 getfield #2 <app/WithoutStaticMethods.value>
10 imul
11 invokespecial #3 <app/WithoutStaticMethods.helper>
14 ireturn

0 (또는 1)의 명령어 aload_0는 스택의 인스턴스에 대한 참조를로드하고 나중에에서 사용됩니다 invokespecial. 이 명령어는 해당 값을 helper(...)함수 의 첫 번째 매개 변수로 지정하며 여기에서 볼 수 있듯이 사용되지 않습니다.

0 iload_1
1 iload_2
2 imul
3 iconst_1
4 iadd
5 ireturn

아니 iload_0? 불필요하게로드되었습니다.

정적 메서드 사용

이제 헬퍼 메서드를 static으로 선언하면 calculate()메서드는 다음과 같습니다.

 0 aload_0
 1 getfield #2 <app/WithStaticMethods.value>
 4 iconst_2
 5 aload_0
 6 getfield #2 <app/WithStaticMethods.value>
 9 imul
10 invokestatic #3 <app/WithStaticMethods.helper>
13 ireturn

차이점은 다음과 같습니다.

  • aload_0지시 사항 이 하나 적습니다
  • 도우미 메서드는 이제 다음과 같이 호출됩니다. invokestatic

헬퍼 함수의 코드도 약간 다릅니다. this첫 번째 매개 변수가 없으므로 여기에서 볼 수 있듯이 매개 변수는 실제로 위치 0과 1에 있습니다.

0 iload_0
1 iload_1
2 imul
3 iconst_1
4 iadd
5 ireturn

결론

코드 디자인의 관점에서 헬퍼 메서드를 정적으로 선언하는 것이 훨씬 더 합리적입니다. 코드는 그 자체로 말하고 더 유용한 정보를 포함합니다. 작동하는 데 인스턴스 상태가 필요하지 않음을 나타냅니다.

바이트 코드 수준에서 무슨 일이 일어나고 있는지 훨씬 더 명확하고 쓸모없는 코드가 없습니다 (JIT가이를 최적화 할 방법이 없다고 생각하지만 상당한 성능 비용이 발생하지 않습니다).


메서드가 인스턴스 데이터를 사용하지 않는 경우 정적이어야합니다. 함수가 공용이면 함수를 호출하기 위해 개체의 불필요한 인스턴스를 만들 필요가없는 중요한 효율성 향상을 제공합니다. 아마도 더 중요한 것은 자기 문서화의 이점입니다. 함수를 static으로 선언하면이 함수가 인스턴스 데이터를 사용하지 않는다는 것을 독자에게 알립니다.

Java 프로그램에서 정적 함수를 사용하는 데 문제가 있다는 많은 포스터의 감정을 이해하지 못합니다. 함수가 논리적으로 정적 인 경우 정적으로 만듭니다. Java 라이브러리에는 많은 정적 기능이 있습니다. Math 클래스는 거의 정적 함수로 채워져 있습니다.

예를 들어 제곱근을 계산하는 함수가 필요한 경우이를 수행하는 합리적인 방법은 다음과 같습니다.

public class MathUtils
{
  public static float squareRoot(float x)
  {
    ... calculate square root of parameter x ...
    return root;
  }
}

물론 다음과 같은 "더 많은 OOPy"버전을 만들 수 있습니다.

public class MathUtils
{
  private float x;
  public MathUtils(float x)
  {
    this.x=x;
  }
  public float squareRoot()
  {
    ... calculate square root of this.x ...
    return root;
  }
}

그러나 가능할 때마다 OOP를 사용하는 추상적 인 목표를 달성하는 것 외에 어떻게 더 좋을까요? 더 많은 코드 라인이 필요하고 유연성이 떨어집니다.

(예, 이제 표준 Math 클래스에 제곱근 함수가 있습니다.이 함수를 편리한 예로 사용했습니다.)

정적 함수가 사용되는 유일한 장소가 특정 클래스 내에서 사용되는 경우, 예, 해당 클래스의 멤버로 만드십시오. 클래스 외부에서 호출하는 것이 이치에 맞지 않으면 비공개로 설정하십시오.

정적 함수가 논리적으로 클래스와 연결되어 있지만 외부에서 합리적으로 호출 될 수있는 경우 공용 정적 함수로 만듭니다. 마찬가지로 Java의 parseInt 함수는 정수와 관련이 있기 때문에 Integer 클래스에 있으므로 합리적 장소였습니다.

반면에 클래스를 작성하고 정적 함수가 필요하다는 것을 깨닫는 경우가 종종 있지만 함수는 실제로이 클래스에 연결되어 있지 않습니다. 이것은 당신이 그것을 필요로한다는 것을 깨달은 처음에 불과하지만, 당신이 지금하고있는 일과 아무 관련이없는 다른 클래스에서 꽤 합리적으로 사용될 수 있습니다. 예를 들어, 제곱근 예제로 돌아가려면 위도와 경도가 포함 된 "Place"클래스가 있고 두 장소 사이의 거리를 계산하는 함수를 원했고 계산의 일부로 제곱근이 필요한 경우 ( 표준 라이브러리에서 사용할 수있는 제곱근 함수가없는 척), 더 큰 논리에 포함하는 것보다 별도의 제곱근 함수를 만드는 것이 좋습니다. 그러나 그것은 실제로 당신의 Place 클래스에 속하지 않습니다.

"foo는 다른 고려 사항에 관계없이 항상 정적이어야합니까?" 나는 "거의,하지만 정답은 아니다"라고 말할 것입니다.

정적이 아닌 것으로 생각할 수있는 유일한 이유는 하위 클래스가이를 재정의하려는 경우입니다.

다른 이유는 생각할 수 없지만 가능성을 배제하지는 않습니다. 나는 누군가가 보통 어떤 특별한 경우를 생각 해낼 수 있기 때문에 "어떤 상황에서도 결코"라고 말하는 것을 꺼린다.


흥미로운 질문입니다. 실제적으로 클래스 A의 개인 도우미 메서드를 정적 으로 만드는 것이 중요하지 않습니다 ( A물론 에서 공개적으로 액세스 할 수있는 정적 메서드와 관련이없는 경우 ). 당신은 아무것도 얻지 못하고 있습니다. 정의에 따라 그것들을 필요로 할 수있는 모든 메소드는 이미 A인스턴스를 가지고 있습니다. 그리고 그들은 비하인드 헬퍼 방법이기 때문에, 당신 (또는 다른 동료)이 결국 상태를 알지 못하는 상태에서 도움을받을 수 있다는 것을 결정하지 않을 것이라고 말할 것도 없습니다. 리팩토링 성가신.

많은 수의 내부 정적 메서드로 끝나는 것이 잘못 이라고 생각 하지 않지만 그로부터 어떤 이점을 얻을 수 있는지도 모르겠습니다. 타당한 이유가없는 한 기본적으로 비 정적이라고 말합니다.


아뇨. 정적 메서드는 예외 여야합니다. OO는 객체의 상태를 중심으로 동작하는 객체를 갖는 것입니다. Imho, 이상적으로는 정적 메서드가 없어야합니다. 왜냐하면 객체의 상태와 관련이없는 모든 것은 모듈에서 평범한 오래된 함수에 배치 될 수 있기 때문입니다 (그리고 객체 광고의 개념을 선도하는 것을 피하기 위해). 수평. Complex.fromCartesian (wikipedia 예제를 사용하기 위해)이 너무 잘 읽기 때문에 공장에 대한 가능한 예외입니다.

물론 이것은 (편집 : 모듈 수준 함수) 단일 패러다임 OO 언어 (편집 : Java와 같은)에서는 불가능합니다. 그렇기 때문에 제가 다중 패러다임 언어 디자인의 헌신적 인 옹호자입니다. 그러나 독점적으로 OO 언어에서도 대부분의 메서드는 객체의 상태를 중심으로 회전하므로 비 정적입니다. 즉, 디자인이 OO와 관련이없는 경우가 아니면이 경우 잘못된 언어를 사용하고 있습니다.


나는 보통

필요에 따라 다음 단계를 순서대로 수행하십시오.

a) 멤버 메서드에 일부 코드를 작성하고이 코드 중 일부를 다시 사용할 수 있는지 확인하고

비 정적 방법으로 추출

b) 이제이 메서드가 상태에 액세스해야하는지 아니면 하나 또는 두 개의 매개 변수와 return 문에 그 요구를 맞출 수 있는지 살펴 보겠습니다. 후자의 경우 :

메서드 (개인)를 정적으로 만듭니다.

c) 같은 패키지의 다른 클래스에서이 코드를 사용할 수 있다는 것을 알게되면

메서드를 공개하고 메서드를 기본 가시성을 가진 패키지 도우미 클래스로 이동합니다.

예를 들어 패키지 com.mycompany.foo.bar.phleeem에서 클래스 PhleeemHelper또는 PhleeemUtils기본 가시성을 만들 것 입니다.

d) 애플리케이션 전체에이 기능이 필요하다는 것을 알게되면

도우미 클래스를 전용 유틸리티 패키지로 이동

예 : com.mycompany.foo.utils.PhleeemUtils

일반적으로 나는 최소한의 가시성 개념을 좋아합니다. 내 방법이 필요하지 않은 사람들은 그것을 보지 말아야합니다. 그렇기 때문에 프라이빗 액세스로 시작하고 패키지 액세스로 이동하고 전용 패키지에있는 경우에만 항목을 공개합니다.


객체 참조를 전달하지 않는 static한 클래스의 메서드는에 대한 액세스 권한이 없기 때문에 메서드 자체가 객체를 변경할 수 없도록 강제합니다 this. 이와 관련하여 static수정자는 메소드의 의도, 부작용이없는 것에 대한 정보를 프로그래머에게 제공합니다.

정전기 방지 순수 주의자들은 그것들을 공익 방지 순수 주의자들이 확실히 반대하는 유틸리티 등급으로 제거하기를 원할 수 있습니다. 그러나 실제로 이러한 메서드를 유일한 호출 사이트에서 인위적으로 이동하면 새로운 유틸리티 클래스와의 긴밀한 결합을 제외하고는 달성 할 수 있습니다.

일반 유틸리티 메서드를 자체 클래스로 맹목적으로 추출하는 문제는 원래 코드에서만 사용 되더라도 이러한 유틸리티를 새로운 공용 API로 처리해야한다는 것입니다. 리팩토링을 수행 할 때이를 고려하지 않는 개발자는 거의 없습니다. 엉뚱한 유틸리티 클래스를 사용하여 다른 개발자에게 빨리 감기. 나중에 누군가 자신에 맞게 확장을 변경합니다. 운이 좋으면 시험 한두 번 휴식을 취하지 만 아마도 그렇지 않을 것입니다.


나는 일반적으로 그것들을 정적으로 만들지 않지만 아마도 그럴 것입니다. 이 메서드는 개체의 상태를 수정할 수 없다는 것을 다음 코더에게 알리는 힌트로 유용하며 메서드의 특성을 변경하는 멤버에 액세스하도록 메서드를 수정할 때 경고를 표시하는 것이 중요합니다.

코딩은 다음 코더와 통신하는 것입니다. 코드 실행에 대해 걱정하지 마세요. 간단합니다. 따라서 의사 소통을 극대화하려면 그러한 도우미가 정말로 필요하다면 정적으로 만드는 것이 좋은 생각이라고 말하고 싶습니다. 수학을하지 않는 한 비공개로 설정하는 것도 중요합니다. 수업처럼.


Java는 모듈, 네임 스페이스, adt 및 클래스의 개념을 결합하여 일부 클래스 지향 OO 순수성이 Java 클래스를 모듈, 네임 스페이스 또는 adt로 사용하는 것을 방지해야한다고 주장합니다.

예, 메서드는 정적이어야합니다. 순전히 내부 지원 방법은 비공개 여야합니다. 보호되는 도우미 메서드; 유틸리티 기능은 공개되어야합니다. 또한 정적 필드, 정적 상수 및 공용 정적 메서드 간에는 차이가 있습니다. 첫 번째는 '전역 변수'에 대한 또 다른 단어입니다. 거의 항상 피해야합니다. 심지어 접근 자 방법에 의한 중재조차 피해를 거의 제한하지 않습니다. 두 번째는 Java 클래스를 완벽하게 수용 가능한 기호 상수에 대한 네임 스페이스로 취급하는 것입니다. 세 번째는 Java 클래스를 함수의 모듈로 취급하는 것입니다. 일반적인 규칙의 부작용을 피해야하거나 필요한 경우 함수에 전달 된 매개 변수로 제한해야하기 때문입니다. 정적을 사용하면 개체의 구성원에 액세스하여 실수로이 문제를 해결하는 데 도움이됩니다.

정적 메소드가 귀중한 다른 상황은 Java로 함수 코드를 작성할 때입니다. 이 시점에서 OO 제안자들이 개발 한 대부분의 경험 규칙은 창 밖으로 나갑니다. 정적 메서드로 가득 찬 클래스와 익명의 내부 펑터에 바인딩 된 공용 정적 함수 상수를 사용하게 될 것입니다.

궁극적으로 Java는 동일한 '클래스'및 '인터페이스'구문으로 수많은 개념을 결합하는 매우 약한 범위 지정 구조를 가지고 있습니다. 네임 스페이스, ADT, 모듈 등을 제공하기 위해 Java가 제공하는 기능을 자유롭게 사용할 수 있으므로 정적에 대한 '기본'을 많이 사용해서는 안됩니다.


나는 그러한 회피 정적 방법 이론을 구독하기가 어렵다는 것을 알았다. 그들은 객체 관계에서 벗어난 모든 일탈을 반격 리적으로 정화 한 완전히 위생적인 ​​객체 지향 모델을 촉진하기 위해 존재합니다. 나는 객체 지향을 실천하는 데있어서 반격 파적으로 순수하기 위해 필수적인 방법을 보지 못한다.

어쨌든 모든 java.util.Arrays 클래스는 정적입니다. 숫자 클래스 Integer, Boolean, String에는 정적 메서드가 있습니다. 많은 정적 메서드. 해당 클래스의 모든 정적 메서드는 해당 클래스 인스턴스로 또는 해당 클래스 인스턴스에서 변환됩니다.

좋은 오래된 Gosling 등이 정적 메서드를 갖는 유용한 역할 모델임을 입증했기 때문에 피할 이유가 없습니다. 나는 내 답변에 투표 할만큼 당황한 사람들이 있다는 것을 알고 있습니다. 많은 프로그래머가 멤버를 정적으로 변환하는 것을 좋아하는 이유와 습관이 있습니다.

I once worked in an establishment where the project leader wanted us to make methods static as much as possible and finalize them. On the other hand, I am not that extreme. Like relational database schema design, it all depends on your data modelling strategy.

There should be a consistent reason why methods are made static. It does not hurt to follow the standard Java library pattern of when methods are made static.

The utmost importance is programming productivity and quality. In an adaptive and agile development environment, it is not only adapting the granularity of the project to respond effectively to requirements variation, but also adapting programming atmosphere like providing a conformable coding model to make best use of the programming skill set you have. At the end of the day (a project almost never ends), you want team members to be efficient and effective, not whether they avoided static methods or not.

Therefore, devise a programming model, whether you want MVP, injection, aspect-driven, level of static-avoidance/affinity, etc and know why you want them - not because some theoretical nut told you that your programming practice would violate oo principles. Remember, if you work in an industry it's always quality and profitability not theoretical purity.

Finally what is object-oriented? Object-orientation and data normalization are strategies to create an orthogonal information perspective. For example, in earlier days, IBM manuals were written to be very orthogonal. That is, if a piece of info is written somewhere in a page within those thousands of manuals, they avoid repeating that info. That is bad because you would be reading learning how to perform a certain task and frequently encounter concepts mentioned in other manuals and you would have to be familiar with the "data model" of the manuals to hunt those connecting pieces of info thro the thousands of manuals.

For the same reason, OS/2 failed to compete with Microsoft because IBM's concept of orthogonality was purely machine and data based and IBM was so proudly declaring their true object-orientedness vs Microsoft's false object-orientedness pandering to human perspective. They had forgotten we humans have our own respective varying orthogonal perspectives of information that do not conform to data and machine based orthogonality or even to each other.

If you are familiar with the topology of trees, you would realise that you could pick any leaf node and make it the root. Or even any node, if you don't mind having a multi-trunk tree. Everyone thinks his/her node is the root when in fact any could be the root. If you think your perspective of object-orientation is the canon, think again. More important is to minimise the number of nodes that are accepted as candidate roots.

There needs to be a compromise between effectiveness and efficiency. There is no point in having an efficient data or object model that can be hardly effectively used by fellow programmers.


If it does nothing with objects of this class, but actually belong to this class (I would consider moving it elsewhere), yes it should be static.


Don't use static if you can avoid it. It clashes with inheritance ( overriding ).

Also, not asked but slightly related, don't make utility methods public.

As for the rest, I agree with Matt b. If you have a load of potentially static methods, which don't use state, just put them in a private class, or possibly protected or package protected class.


It depends i.g. java.lang.Math has no method which isn't static. (You could do a static import to write cos() instead of Math.cos()) This shouldn't be overused but as some code that is intented to be called as a utility it would be acceptable. I.g Thread.currentThread()


A static method is used to identify a method (or variable for that matter) that does not have to do with the objects created from that class but the class itself. For instance, you need a variable to count the number of objects created. You would put something like: 'private static int instances = 0;' and then put something in the constructor for that class that increments 'instances' so you may keep count of it.


Do think hard before creating a static method, but there are times when they are a good solution.

Joshua Bloch in "Item 1: Consider Static Factory Methods Instead of Constructors" in Effective Java makes a very persuasive case that static methods can be very beneficial. He gives the java.util.Collections class's 32 static factory methods as an example.

In one case, I have a hierarchy of POJO classes whose instances can be automatically serialized into XML and JSON, then deserialized back into objects. I have static methods that use Java generics to do deserialization: fromXML(String xml) and fromJSON(String json). The type of POJO they return isn't known a priori, but is determined by the XML or JSON text. (I originally packaged these methods into a helper class, but it was semantically cleaner to move these static methods into the root POJO class.)

A couple of other examples:

  • Using a class as a namespace to group related methods (eg, java.lang.Math).
  • The method truly is a private class-specific helper method with no need to access instance variables (the case cited here). Just don't sneak a this-equivalent into its argument list!

But don't use statics unthinkingly or you run the danger of falling into a more disorganized and more procedural style of programming.


No, the use of statics should be quite niche.

In this case the OP is likely 'hiding' state in the parameters passed into the static method. The way the question is posed makes this non-obvious (foo() has no inputs or outputs), but I think in real world examples the things that should actually be part of the object's state would fall out quite quickly.

At the end of the day every call to obj.method(param) resolves to method(obj, param), but this goes on at a way lower level than we should be designing at.


If it's only ever used by methods in A and wouldn't have any use outside it, then it should be static (and, probably, be placed in a Helper Class. It doesn't have any use outside A now, but there's no guarantee it will never have. Otherwise, it shouldn't.

If it doesn't have anything to do with the state of A, it could be useful at other places...

Anyway, that doesn't make a good reason for Java methods to be static by default.

Talking about this last issue, they shouldn't be static by default, because having to write 'static' make people think before writing static methods. That's a good practice when you have heterogeneous teams (the ones where Java is most useful).


If foo is private, it may be anything, static or not. But, most of the time it will be not static as these is one less word to type. Then, if you need to use the state because you've changed your code, you can do it right away.

When it is protected or public, it depends on what it does. A rule of thumb is to make it not static when it isn't a part of the instance's behaviour, and make it static when it makes sense to call it without any object. If you are unsure, ask yourself if it makes sense to override the method in a subclass.


I think letting the methods in Java to be static will result in a rather chaotic implementation by beginner who haven't understand OO correctly. We've been there and think about it. If the methods were static as default how hard it is for us to understand the OO principle?

So yes, once you mastered the concept, it is a bit itchy to have static all over the methods (as result of refactoring). Nothing we ca do about that I think.

NB: Let me guess, are you by any chance have read Clean Code?


When you write a static method you should keep in mind that you'r gonna use it at use-site with static-import (make it look class free) and thus it should behave just like a function which doesn't something and may or may not return something and is isolated with the state of class it belongs to. So static methods should be a rare situation.

If you seem to be making a lot of helper methods, then consider using package-private instance methods instead of private ones. Less typing, less boilerplate since you can re-use them as a helper to other classes in the same package.


I think "private static" (edit: for methods) is kind of an oxymoron in Java. The main point of static methods in my mind is to provide access to functions outside of the context of object instances. In other words, they're practically only ever useful if they're public. If you're only calling a method from within the context of a single object instance, and that method is private, it makes no sense to make it static. (edit: but, it makes no practical difference).

In this sort of case, I usually try to make the methods abstract enough that they're useful in other contexts, and I make them public in a utility class. Look at it as writing supporting library code, and think hard about your api.


Most static methods are written because

  1. You break down a complex method into submethods, or
  2. You wish String (or Date, or...) had some functionality that it doesn't have

The first is not bad per se, but it's often a sign that you're missing objects. Instead of working with default types such as String or List, try inventing your own classes and move the static methods to those classes.

The second reason produces the always-popular StringUtil, DateUtil, FooUtil classes. These are problematic because you have no way to discover that they exist, so programmers often write duplicates of these utility methods. The solution, again, is to avoid using String and Date all the time. Start creating your own objects, perhaps by wrapping the original object. The static methods become non-static methods of the new object.


If foo() doesn't have anything to do with Object A then why is the method in there?

Static methods should still be relevant. If there isn't anything going on then why have you written a method that has no association with it?


Plenty of interesting answers.

If you desperately seek a rule, then use this:

If the code is only ever used by instance methods of a single class, then make it an instance method - it is simply an extraction of code out of an instance context - which could be refactored back into (or out of) methods that access instance state.

If the code is used by MORE THAN ONE class, and contains no access to instance variables in the class in which the method resides, then make it static.

End of story.

참고URL : https://stackoverflow.com/questions/3346764/should-java-methods-be-static-by-default

반응형