Question

I have an object with a method that reads a file and for each line that is read, it parses the data into an object.

For example:

public class test{
     private void processData{
        while((input = bf.readLine()) != null){
             test t = new test();
        }
    }
 }

Is it correct to do that in a method rather than the main method? Why or why not?

Was it helpful?

Solution 2

Yes, there are few design patterns that creates instance of itself or of inner class (Singleton, Builder, Factory pattern).

I dont think you example is usable, while you can create object outside, but haven't access to your private method.

Example from xdesperadox isn't complete as well. Missing private constructor and yes, you have to store instance in private static field for next consequence calls for newInstance() (to return same instance.

OTHER TIPS

It is not bad style to recursively create new objects if that is the best solution for your problem.

Yes its ok, You can create the instance of class any where.

but for a good practice avoid to create new objects, but you can create object if neccessory.

Mostly calling itself or in other words creating the same type of class you can see during parsing/generating XML, Json or if your Object represents tree of data where each Node can store other Nodes

From your example, since you don't call after processData that can cause to infinite loop, its ok.

No it is not because Singleton pattern is just based on this.

public static Test newInstance(){
    if(instance==null){
        instance = new Test();
    }
    return instance;
}

See singleton pattern for detail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top