IT박스

자바에서 허용되는 메소드 호출에서 'this'를 전달하고 있습니다.

itboxs 2020. 8. 31. 07:35
반응형

자바에서 허용되는 메소드 호출에서 'this'를 전달하고 있습니다.


메서드 호출에서 현재 개체를 전달하는 것이 좋은 / 나쁜 / 용인 할 수있는 방법입니까? 에서와 같이 :

public class Bar{
    public Bar(){}

    public void foo(Baz baz){
        //  modify some values of baz
    }
}

public class Baz{
    //constructor omitted

    public void method(){
        Bar bar = new Bar();
        bar.foo(this);
    }
}

구체적으로, 라인이 bar.foo(this)허용됩니까?


사용하지 않을 이유가 없으며 this현재 인스턴스이며 사용하기에 완벽하게 합법적입니다. 사실 그것을 생략 할 수있는 깨끗한 방법은 종종 없습니다.

그래서 그것을 사용하십시오.

예없이 받아 들일 수 있다고 확신하기 어렵 기 때문에 (이러한 질문에 대한 부정적인 대답은 항상 논쟁하기 쉽습니다), 방금 가장 일반적인 java.lang클래스 중 하나 인 하나를 열었고 String물론이 사용 사례를 찾았습니다.

1084        // Argument is a String
1085        if (cs.equals(this))
1086            return true;

을 찾아 (this큰 "수용"프로젝트에, 당신은 그것을 찾기 위해 실패하지 않습니다.


그게 잘못이 아닙니다. 무엇인가 좋은 연습을하지 않는 것은 당신이 아직 완전 초기화되지 않은 개체에 대한 참조를 줄 것이기 때문에, 같은 내부의 생성자를하는 것입니다.

여기에 비슷한 포스트가 있습니다. Java가 생성자 에서 이것을 유출 하고 후자가 왜 나쁜 습관인지에 대한 설명을 제공합니다.


,하지만 두 가지에주의해야합니다.

  1. 전달 개체가 구성되지 않은 경우 아직 (즉 생성자에서)
  2. 살아 참조를 유지되고 방지하는 장수 객체에이 전달 쓰레기 수집되는 개체를.

그것은 완벽하게 정상적이고 완벽하게 수용 가능합니다.


이것은 현재 객체를 나타냅니다. 당신이하고있는 일은 체계적으로 정확하지만 동일한 클래스에서 메서드를 호출하는 경우 이것이 필요하지 않습니다.


동일한 동작을 달성하기위한 덜 복잡한 대안이있는 경우 메서드 호출에서 현재 개체를 전달하는 것은 좋지 않습니다 .

정의에 따라 양방향 연결은 this한 개체에서 다른 개체로 전달되는 즉시 생성됩니다 .

Martin Fowler의 리팩토링을 인용하려면 :

양방향 연결을 단방향으로 변경 (200)

양방향 연결은 유용하지만 가격이 있습니다. 가격은 양방향 링크를 유지하고 개체가 올바르게 생성 및 제거되도록하는 데 따른 추가 복잡성입니다. 양방향 연결은 많은 프로그래머에게 자연스럽지 않으므로 종종 오류의 원인이됩니다.

...

You should use bidirectional associations when you need to but not when you don’t. As soon as you see a bidirectional association is no longer pulling its weight, drop the unnecessary end.

So, theoretically, we should be hearing alarm bells when we find we need to pass this and try really hard to think of other ways to solve the problem at hand. There are, of course, times when, at last resort, it makes sense to do it.

Also it is often necessary to corrupt your design temporarily, doing 'bad practice things', during a longer term refactoring of your code for an overall improvement. (One step back, two steps forward).

In practice I have found my code has improved massively by avoiding bidirectional links like the plague.


Yes. you can use it.Its just common in programming to pass this.But there are pros and cons about using that.Still it is not hazardous to do so.


Just to add one more example where passing this is correct and follows good design: Visitor pattern. In Visitor design pattern, method accept(Visitor v) is typically implemented in a way it just calls v.visit(this).


Acceptable

Snippet from Oracle JAVA docs:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.


Everything in java is passed by value. But objects are NEVER passed to the method!
When java passes an object to a method, it first makes a copy of a reference to the object, not a copy of the object itself. Hence this is pefectly used method in java. And most commonly followed usage.

참고URL : https://stackoverflow.com/questions/17441871/is-passing-this-in-a-method-call-accepted-practice-in-java

반응형