Is passing 'this' in a method call accepted practice in java

后端 未结 10 1155
无人共我
无人共我 2021-01-30 19:32

Is it good/bad/acceptable practice to pass the current object in a method call. As in:

public class Bar{
    public Bar(){}

    public void foo(Baz baz){
              


        
相关标签:
10条回答
  • 2021-01-30 19:58

    Yes, but you should be careful about two things

    1. Passing this when the object has not been constructed yet (i.e. in its constructor)
    2. Passing this to a long-living object, that will keep the reference alive and will prevent the this object from being garbage collected.
    0 讨论(0)
  • 2021-01-30 20:00

    It is bad practice to pass the current object in a method call if there less complex alternatives to achieve the same behaviour.

    By definition, a bidirectional association is created as soon as this is passed from one object to another.

    To quote Refactoring, by Martin Fowler:

    Change Bidirectional Association to Unidirectional (200)

    Bidirectional associations are useful, but they carry a price. The price is the added complexity of maintaining the two-way links and ensuring that objects are properly created and removed. Bidirectional associations are not natural for many programmers, so they often are a source of errors

    ...

    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.

    0 讨论(0)
  • 2021-01-30 20:00

    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).

    0 讨论(0)
  • 2021-01-30 20:03

    It's perfectly normal and perfectly acceptable.

    0 讨论(0)
提交回复
热议问题