IT박스

자바 메소드 인수를 최종으로 만들기

itboxs 2020. 10. 7. 07:29
반응형

자바 메소드 인수를 최종으로 만들기


final아래 코드의 차이점은 무엇입니까? 인수를 final.

public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){  
    return ....
}

public String changeTimezone(final Timestamp stamp, final Timezone fTz, 
        final Timezone toTz){
    return ....
}

공식 메서드 매개 변수는 지역 변수이므로 final로 선언 된 경우에만 내부 익명 클래스에서 액세스 할 수 있습니다.

이렇게하면 메서드 본문에서 다른 지역 최종 변수를 선언하지 않아도됩니다.

 void m(final int param) {
        new Thread(new Runnable() {
            public void run() {
                System.err.println(param);
            }
        }).start();
    }

최종 키워드의 최종 단어에서 추출

최종 매개 변수

다음 샘플은 최종 매개 변수를 선언합니다.

public void doSomething(final int i, final int j)
{
  // cannot change the value of i or j here...
  // any change would be visible only inside the method...
}

final은 여기서 두 인덱스 i와 j가 메서드에 의해 실수로 재설정되지 않도록하는 데 사용됩니다. 매개 변수 값을 잘못 변경하는 교활한 버그로부터 보호 할 수있는 편리한 방법입니다. 일반적으로 짧은 메서드는 이러한 종류의 오류로부터 보호하는 더 좋은 방법이지만 최종 매개 변수는 코딩 스타일에 유용한 추가 기능이 될 수 있습니다.

최종 매개 변수는 메서드 서명의 일부로 간주되지 않으며 메서드 호출을 확인할 때 컴파일러에서 무시됩니다. 매개 변수는 메소드가 재정의되는 방법에 영향을주지 않고 최종 (또는 그렇지 않음)으로 선언 될 수 있습니다.


마지막은 변수에 새 값을 할당하는 것을 방지하며 오타를 포착하는 데 도움이 될 수 있습니다. 스타일 적으로 수신 된 매개 변수를 변경하지 않고 로컬 변수에만 할당 할 수 있으므로 final이 해당 스타일을 적용하는 데 도움이됩니다.

매개 변수에 대해 final을 사용하는 것을 거의 기억하지 못한다는 것을 인정해야합니다.

public int example(final int basicRate){
    int discountRate;

    discountRate = basicRate - 10;
    // ... lots of code here 
    if ( isGoldCustomer ) {
        basicRate--;  // typo, we intended to say discountRate--, final catches this
    }
    // ... more code here

    return discountRate;
}

큰 차이는 없습니다. 그것은 단지 당신이 쓸 수 없다는 것을 의미합니다 :

stamp = null;
fTz = new ...;

그러나 여전히 다음과 같이 작성할 수 있습니다.

stamp.setXXX(...);
fTz.setXXX(...);

그것은 당신을 따르는 유지 보수 프로그래머에게 당신이 명확하지 않고 혼란을 야기 할 수있는 당신의 방법 중간 어딘가에 매개 변수에 새로운 값을 할당하지 않을 것이라는 힌트입니다.


Java에서 매개 변수 / 변수에 사용되는 final 키워드는 참조를 final로 표시합니다. 객체를 다른 메서드로 전달하는 경우 시스템은 참조 변수의 복사본을 만들어 메서드에 전달합니다. 새 참조를 최종 참조로 표시하면 재 할당되지 않도록 보호 할 수 있습니다. 때로는 좋은 코딩 관행으로 간주됩니다.


For the body of this method the final keyword will prevent the argument references to be accidentally reassigned giving a compile error on those cases (most IDEs will complain straight away). Some may argue that using final in general whenever possible will speed things up but that's not the case in recent JVMs.


Its just a construct in Java to help you define a contract and stick to it. A similar discussion here : http://c2.com/cgi/wiki?JavaFinalConsideredEvil

BTW - (as the twiki says), marking args as final is generally redundant if you are following good programming principles and hance done reassign / redefine the incoming argument reference.

In the worst case, if you do redefine the args reference, its not going to affect the actual value passed to the function - since only a reference was passed.


I'm speaking of marking variables and fields final in general - doesn't just apply to method arguments. (Marking methods/classes final is a whole different thing).

It's a favor to the readers/future maintainers of your code. Together with a sensible name of the variable, it's helpful and reassuring to the reader of your code to see/understand what the variables in question represent - and it's reassuring to the reader that whenever you see the variable in the same scope, the meaning stays the same, so (s)he doesn't have to scratch his head to always figure out what a variable means in every context. We've seen too many abuses of "re-use" of variables, that makes even a short code snippet hard to understand.


- In the past (before Java 8 :-) )

Explit use of "final" keyword affected accessibility of the method variable for internal anonymous classes.

- In modern (Java 8+) lanaguage there is no need for such usage:

Java introduced "effectively final" variables. Local variables and method paramters are assummed final if the code does not imply changing of value of the variable. So if you see such keyword in Java8+ you can assume it is unecessary. Introduction of "effectively final" makes us type less code when using lambdas.


The final keyword prevents you from assigning a new value to the parameter. I would like to explain this with a simple example

Suppose we have a method

method1(){

Date dateOfBirth =new Date("1/1/2009");

method2(dateOfBirth);

method3(dateOfBirth); }

public mehod2(Date dateOfBirth) {
....
....
....
}

public mehod2(Date dateOfBirth) {
....
....
....
}

In the above case if the "dateOfBirth" is assigned new value in method2 than this would result in the wrong output from method3. As the value that is being passed to method3 is not what it was before being passed to method2. So to avoid this final keyword is used for parameters.

And this is also one of the Java Coding Best Practices.

참고URL : https://stackoverflow.com/questions/4162531/making-java-method-arguments-as-final

반응형