Java: alternative of passing "this" as a constructor argument to reference object creation

I spent some time thinking about the various solutions that I visited when I read (I am not very good at Java yet) that using this constructor argument is usually not good practice.

What I'm trying to do is create several objects of the JobGroupMod class and for each JobGroupMod I need to create a certain number of JobMod objects that should be able to refer to the JobGroupMod objects in which they were created.

To accomplish this, I pass "this" to the JobMod constructor, but even if it works, it doesn't feel right.

public class JobGroupMod implements JobGroup { public JobGroupMod(Node n,Set<Job> clusterJobs){ JobMod j=new JobMod(n,this); } } 

And now the JobMod class:

 public class JobMod implements Job { public JobMod(Node n, JobGroup jg){ setJobGroup(jg); } } 

My question is, is there a better way to solve this, or is it my solution in the proposed way?

+8
java constructor this
source share
3 answers

You should try using the static factory method ( Java Effective Link ).

This way you avoid skipping this in a constructor call, which is at least highly discouraged.
code example:

 public class JobGroupMod implements JobGroup { public static JobGroupMod createModeMod(Node n, Set<Job> clusterJobs) { JobGroup jg = new JobGroupMod(); JobMod j = new JobMod(n, jg); return jg; } } 
+7
source share

As long as it remains the only thing you do in the JobGroupMod constructor, it is safe enough until you understand the implications. In the real world, there is a lot of Java code that does this. This is still not what you really want to do, especially when you start talking about multithreading and concurrency.

The danger passes this to something else before the facility is fully built. If the constructor was supposed to throw an exception after you did this and did not completely construct, you might have an unpleasant problem. If another thread had to access the object you passed this before it was completely constructed, you would have an unpleasant problem.

What you often find in Java are people using the factory pattern to avoid this, a method like β€œinit” or dependency injection.

+4
source share

There is no magic at all. You can pass the parameter through the constructor or initialize it later using the setter / init method, etc.

If your JobMod class needs a reference to JobGroupMod and has nothing to do, passing it using the constructor. If sometimes it can stand without it, create an init() or setter method that can initialize this link.

Sometimes you need to create both a parameterized and a standard constructor: first for regular use of programs, and secondly, if you use XML, JSON or other serialization, which is easier for bean classes. In this case, at least create a javadoc that explains that the default constructor should not be used directly.

0
source share

All Articles