development

Java에서 적용 가능한 경우 "최종"수정 자 사용

big-blog 2020. 5. 14. 20:38
반응형

Java에서 적용 가능한 경우 "최종"수정 자 사용


Java에서는 모든 변수 (로컬 또는 클래스)를 선언하는 연습이 있으며 실제로는 매개 변수 final입니다.이렇게하면 코드가 훨씬 더 장황하지만 코드를 쉽게 읽고 이해하는 데 도움이되고 의도가 명확하게 표시되어 실수를 방지 할 수 있습니다.이것에 대한 당신의 생각은 무엇입니까?


모든 것이 좋은 코딩 스타일과 관련이 있다고 생각합니다. 물론

final

어디에서나 많은 수정자를 사용하지 않고도 훌륭하고 강력한 프로그램을 작성할 수 있지만 생각할 때 ...변경 해서는 안되는

final

모든 것에 추가하면 코드를 작성하는 사고 과정을 잘못 해석하거나 오용 할 가능성이 좁아집니다. 그들이 이전에 불변의 것을 바꾸고 싶을 때 적어도 그것은 종을 울려 야합니다.처음에는

final

코드에서 많은 키워드 를 보는 것이 어색해 보이지만 곧 단어 자체에 대한

언급을

중단하고 간단히 생각할 것입니다. 에 (당신은 나에게서 그것을 취할 수 있습니다 ;-)좋은 습관이라고 생각합니다. 나는 항상 그것을 사용하지는 않지만, 할 수 있고 무언가에 레이블을 붙이는 것이 합리적

final

입니다.


집착 :

  • 최종 필드-필드를 최종으로 표시하면 구성이 끝날 때 필드를 강제 설정하여 해당 필드 참조를 변경할 수 없습니다. 이렇게하면 필드를 안전하게 게시 할 수 있으며 나중에 읽을 때 동기화 할 필요가 없습니다. (객체 참조의 경우 필드 참조 만 변경할 수 없습니다. 객체 참조가 참조하는 항목은 계속 변경 될 수 있으며 불변성에 영향을줍니다.)
  • 최종 정적 필드-정적 최종 필드를 사용했던 많은 경우에 지금 열거 형을 사용하지만.

신중하게 사용하십시오.

  • 최종 수업-프레임 워크 / API 디자인은 내가 생각하는 유일한 경우입니다.
  • 최종 방법-기본적으로 최종 클래스와 동일합니다. 미친 것과 같은 템플릿 방법 패턴을 사용하고 물건을 최종적으로 표시하는 경우 상속에 너무 의존하고 위임에 충분하지 않을 수 있습니다.

항문 느낌이 없으면 무시하십시오.

  • 메소드 매개 변수 및 로컬 변수-게으르고 코드가 복잡해지기 때문에 거의하지 않습니다. 수정하지 않을 마킹 매개 변수와 로컬 변수가 "보다 옳다"는 것을 완전히 인정합니다. 이것이 기본값이기를 바랍니다. 그러나 코드가 아니며 최종 코드로 이해하기가 더 어렵다는 것을 알았습니다. 다른 사람의 코드를 사용하는 경우 코드를 꺼내지 않지만 새 코드를 작성하는 경우 코드를 넣지 않습니다. 한 가지 예외는 최종 항목을 표시하여 액세스 할 수있는 경우입니다. 익명의 내부 클래스 내에서.

최종 키워드를 사용하기 전에 전체 사용법을 이해해야합니다. 변수, 필드, 메소드 및 클래스에 적용 할 수 있으며 다른 영향을 미칩니다.자세한 내용은 아래 링크 된 기사를 확인하는 것이 좋습니다.

최종 키워드 최종 단어


 

final

특히 변수에 대한 수정은 수단 컴파일러는 일반적으로 분별하는 규칙을 적용하는 것입니다 : 확실히 (로컬 또는 인스턴스) 변수 (더 이상 아무 이하) 정확히 한 번만 할당되지도하지 않습니다. 변수를 사용하기 전에 변수를 확실히 할당하면

NullPointerException

다음 과 같은 일반적인 경우를 피할 수 있습니다 .

final FileInputStream in;
if(test)
  in = new FileInputStream("foo.txt");
else
  System.out.println("test failed");
in.read(); // Compiler error because variable 'in' might be unassigned

변수가 두 번 이상 할당되지 않도록하여 범위 초과 범위를 권장하지 않습니다. 이 대신에 :

 String msg = null;
 for(int i = 0; i < 10; i++) {
     msg = "We are at position " + i;
     System.out.println(msg);
 }
 msg = null;

이것을 사용하는 것이 좋습니다.

 for(int i = 0; i < 10; i++) {
     final String msg = "We are at position " + i;
     System.out.println(msg);
 }

일부 링크 :


가능한 모든 변수를 선언하는 것에 대해 독단적

final

입니다. 여기에는 메소드 매개 변수, 로컬 변수 및 드물게 값 오브젝트 필드가 포함됩니다. 어디에서나 최종 변수를 선언해야하는 세 가지 주요 이유가 있습니다.

  1. 의도 선언 : 최종 변수를 선언 하여이 변수를 한 번만 작성해야한다고 말하고 있습니다. 다른 개발자에게는 미묘한 힌트이며 컴파일러에게는 큰 힌트입니다.
  2. 일회용 변수 시행 : 각 변수는 인생에서 단 하나의 목적을 가져야한다는 생각이 있습니다. 각 변수에 하나의 목적 만 부여하면 디버깅하는 동안 특정 변수의 목적을 달성하는 데 걸리는 시간이 줄어 듭니다.
  3. 최적화 허용 : 컴파일러가 변수 참조의 불변성에 특히 의존하는 성능 향상 트릭을 사용했음을 알고 있습니다. 나는이 오래된 성능 트릭 (또는 새로운 트릭) 중 일부가 컴파일러에서 사용될 것이라고 생각하고 싶습니다.

그러나 최종 클래스와 메소드는 최종 변수 참조만큼 유용하지 않다고 생각합니다.

final

이러한 선언과 함께 사용할 때 키워드는 단순히 자동화 된 테스트하고 예상 적이없는 수 방법으로 코드의 사용에 장애물을 제공합니다.


효과적인 Java에는 "Favour immutable objects"라는 항목이 있습니다. 필드를 최종으로 선언하면이를 향한 몇 가지 작은 단계를 수행하는 데 도움이되지만 물론 그보다 불변의 객체는 훨씬 더 많습니다.

If you know that objects are immutable they can be shared for reading among many threads/clients without synchronization worries, and it is easier to reason about how the program runs.


I have never been in a situation where having a final keyword on a variable has stopped me from making a mistake, so for the moment I think it's a giant waste of time.

Unless there is a real reason for doing it (as in you want to make a specific point about that variable being final) I would rather not do it since I find it makes the code less readable.

If, however, you don't find it makes the code harder to read or longer to write then by all means go for it.

Edit: As a clarification (and an attempt to win back down-votes), I'm not saying don't mark constants as final, I'm saying don't do stuff like:

public String doSomething() {
  final String first = someReallyComplicatedExpressionToGetTheString();
  final String second = anotherReallyComplicatedExpressionToGetAnother();

  return first+second;
}

It just makes code (in my opinion) harder to read.

It's also worth remembering that all final does is prevent you from reassigning a variable, it doesn't make it immutable or anything like that.


Final should always be used for constants. It's even useful for short-lived variables (within a single method) when the rules for defining the variable are complicated.

For example:

final int foo;
if (a)
    foo = 1;
else if (b)
    foo = 2;
else if (c)
    foo = 3;
if (d)        // Compile error:  forgot the 'else'
    foo = 4;
else
    foo = -1;

I use final all the time for object attributes.

The final keyword has visibility semantics when used on object attributes. Basically, setting the value of a final object attribute happens-before the constructor returns. This means that as long as you don't let the this reference escape the constructor and you use final for all you attributes, your object is (under Java 5 semantics) guarenteed to be properly constructed, and since it is also immutable it can be safely published to other threads.

Immutable objects is not just about thread-safety. They also make it a lot easier to reason about the state transitions in your program, because the space of what can change is deliberately and, if used consistently, thoroughly limited to only the things that should change.

I sometimes also make methods final, but not as often. I seldomly make classes final. I generally do this because I have little need to. I generally don't use inheritance much. I prefer to use interfaces and object composition instead - this also lends itself to a design that I find is often easier to test. When you code to interfaces instead of concrete classes, then you don't need to use inheritance when you test, as it is, with frameworks such as jMock, much easier to create mock-objects with interfaces than it is with concrete classes.

I guess I should make the majority of my classes final, but I just haven't gotten into the habbit yet.


Sounds like one of the biggest argument against using the final keyword is that "it's unnecessary", and it "wastes space".

If we acknowledge the many benefits of "final" as pointed out by many great posts here, while admitting it takes more typing and space, I would argue that Java should have made variables "final" by default, and require that things be marked "mutable" if the coder wants it to be.


I have to read a lot of code for my job. Missing final on instance variables is one of the top things to annoy me and makes understanding the code unnecessarily difficult. For my money, final on local variables causes more clutter than clarity. The language should have been designed to make that the default, but we have to live with the mistake. Sometimes it is useful particularly with loops and definite assignment with an if-else tree, but mostly it tends to indicate your method is too complicated.


final should obviously be used on constants, and to enforce immutability, but there is another important use on methods.

Effective Java has a whole item on this (Item 15) pointing out the pitfalls of unintended inheritance. Effectively if you didn't design and document your class for inheritance, inheriting from it can give unexpected problems (the item gives a good example). The recommendation therefore is that you use final on any class and/or method that wasn't intended to be inherited from.

That may seem draconian, but it makes sense. If you are writing a class library for use by others then you don't want them inheriting from things that weren't designed for it - you will be locking yourself into a particular implementation of the class for back compatibility. If you are coding in a team there is nothing to stop another member of the team from removing the final if they really have to. But the keyword makes them think about what they are doing, and warns them that the class they are inheriting from wasn't designed for it, so they should be extra careful.


Another caveat is that many people confuse final to mean that the contents of the instance variable cannot change, rather than that the reference cannot change.


Even for local variables, knowing that it is declared final means that I don't need to worry about the reference being changed later on. This means that when debugging and I see that variable later on, I am confident that it is referring to the same object. That is one less thing I need to worry about when looking for a bug. A bonus is that if 99% of variables are declared final, then the few variables which really are variable stand out better. Also, the final lets the compiler find some more possible stupid mistakes that might otherwise go unnoticed.


Choosing to type final for each parameter in each method will produce so much irritation both for coders and code readers.

Once irritation goes beyond reasonable switch to Scala where arguments are final by default.

Or, you can always use code styling tools that will do that automatically for you. All IDEs have them implemented or as plugins.


Final when used with variables in Java provides a substitute for constant in C++. So when final and static is used for a variable it becomes immutable. At the same time makes migrated C++ programmers pretty happy ;-)

When used with reference variables it does not allow you to re-reference the object, though the object can be manipulated.

When final is used with a method, it does not allow the method to be over-ridden by the subclasses.

Once the usage is very clear it should be used with care. It mainly depends on the design as using final on the method would not help polymorphism.

One should only use it for variables when you are damn sure that the value of the variable will/should never be changed. Also ensure that you follow the coding convention encouraged by SUN.for eg: final int COLOR_RED = 1; (Upper case seperated by underscore)

With a reference variable, use it only when we need a an immutable reference to a particular object.

Regarding the readability part, ensue that comments play a very important role when using the final modifier.


I never use them on local variables, there is little point for the added verbosity. Even if you don't think the variable should be reassigned, that will make little difference to the next person altering that code that thinks otherwise, and since the code is being changed, any original purpose for making it final may no longer be valid. If it is just for clarity, I believe it fails due to the negative effects of the verbosity.

Pretty much the same applies to member variables as well, as they provide little benefit, except for the case of constants.

It also has no bearing on immutability, as the best indicator of something being immutable is that it is documented as such and/or has no methods that can alter the object (this, along with making the class final is the only way to guarantee that it is immutable).

But hey, that's just my opinion :-)


I set up Eclipse to add final on all fields and attributes which are not modified. This works great using the Eclipse "save actions" which adds these final modifiers (among other things) when saving the file.

Highly recommended.

Check out my blog post of Eclipse Save Actions.


I hardly use final on methods or classes because I like allowing people to override them.

Otherwise, I only use finally if it is a public/private static final type SOME_CONSTANT;


For arguments I'm think they're not needed. Mostley they just hurt readabillity. Rreassigning an argument variable is so insanely stupid that I should be pretty confident that they can be treated as constants anyway.

The fact that Eclipse colors final red makes it easier to spot variable declarations in the code which I think improves readbillity most of the time.

I try to enforce the rule that any and all variables should be final it there isn't an extremley valid reason not to. It's so much easier to answer the "what is this variable?" question if you just have to find the initilization and be confident that that is it.

I actually get rather nervous around non-final variables now a days. It's like the differnce between having a knife hanging in a thread abouve your head, or just having it you kitchen drawer...

A final variable is just a nice way to lable values.

A non-final variable is bound to part of some bug-prone algorithm.

One nice feature is that when the option to use a variable in out of the question for an algorithm most of the time the sollution is to write a method instead, which usually improves the code significantly.


I've been coding for a while now and using final whenever I can. After doing this for a while (for variables, method parameters and class attributes), I can say that 90% (or more) of my variables are actually final. I think the benefit of NOT having variables modified when you don't want to (I saw that before and it's a pain sometimes) pays for the extra typing and the extra "final" keywords in your code.

That being said, if I would design a language, I would make every variable final unless modified by some other keyword.

I don't use final a lot for classes and methods, thought. This is a more or less complicated design choice, unless your class is a utility class (in which case you should have only one private constructor).

I also use Collections.unmodifiable... to create unmodifiable lists when I need to.


Using anonymous local classes for event listeners and such is a common pattern in Java. The most common use of the final keyword is to make sure that variables in scope are accessible to the even listener.

However, if you find yourself being required to put a lot of final statements in your code. That might be a good hint you're doing something wrong.

The article posted above gives this example:

public void doSomething(int i, int j) {
    final int n = i + j; // must be declared final

    Comparator comp = new Comparator() {
        public int compare(Object left, Object right) {
            return n; // return copy of a local variable
        }
    };
}

I use it for constants inside and outside methods.

I only sometimes use it for methods because I don't know if a subclass would NOT want to override a given method(for whatever reasons).

As far as classes, only for some infrastructure classes, have I used final class.

IntelliJ IDEA warns you if a function parameter is written to inside a function. So, I've stopped using final for function arguments. I don't see them inside java Runtime library as well.


Marking the class final can also make some method bindings happen at compile time instead of runtime. Consider "v2.foo()" below - the compiler knows that B cannot have a subclass, so foo() cannot be overridden so the implementation to call is known at compile time. If class B is NOT marked final, then it's possible that the actual type of v2 is some class that extends B and overrides foo().

class A {
    void foo() {
        //do something
    }
}
final class B extends A {
    void foo() {
    }
}
class Test {
    public void t(A v1, B v2) {
        v1.foo();
        v2.foo();
    }
}

Using final for constants is strongly encouraged. However, I wouldn't use it for methods or classes (or at least think about it for a while), because it makes testing harder, if not impossible. If you absolutely must make a class or method final, make sure this class implements some interface, so you can have a mock implementing the same interface.

참고URL : https://stackoverflow.com/questions/137868/using-the-final-modifier-whenever-applicable-in-java

반응형