0

I have a class that has an explicit initialization method and some other methods that do the actual work:

public class Worker {

    public void init(Context context) { /* ... */ };

    public void doWork() { /* ... */ };
}

The Init method must be called before any actual work is done, which is documented in class and methods description.

I would like to throw an exception from DoWork method if initialization wasn't performed before the call. What would be the right exception type for this case? UnsupportedOperationException, IllegalStateException or something else?

3
  • There's means of an illegal state. Commented Jul 1, 2012 at 15:32
  • @BalusC: yes, thanks, I'm new to Java (hence the newbie question and naming problems). Don't worry, they do in actual code! Commented Jul 1, 2012 at 15:34
  • Note that standard Java exceptions usually describe their purpose very well in their javadocs. Commented Jul 1, 2012 at 15:34

1 Answer 1

3

IllegalStateException. But ideally, try to ensure that the object always has a valid state. :-) In this case, by requiring Context in the constructor rather than a separate "init" function:

public class Worker {

    // Note this is a constructor now, not a method
    public Worker(Context context) {
        /* ... */
    }

    public void doWork() {
        /* ... */
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

yes, I do try to ensure that. However, I'm reluctant to put code that performs complex computations or other long-running activities in the constructor, which unfortunally is the case.
Then don't expose a constructor. Expose a factory method.
In which case: have the init function return another object, on which you can call doWork(). This looks suspiciously like the factory pattern :).
@Dyppl: In general, it's fine to do anything in a constructor that you do in a method. If by "long running" you mean happening on another thread, and so you can have a semi-constructed instance, you can handle that with a factory that accepts a callback (public static void BuildWorker(Context context, IAcceptWorkers target)) where IAcceptWorkers is an interface with a function you call with the fully-constructed Worker. If by long-running you just mean it takes a while, that's fine, still a constructor. Document it, of course. :-)
@T.J.Crowder: I'm not sure I completely agree; at a VM level, sure, but I think there's benefit in separating actually creating the object from the work required to enable me to create the object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.