C
C
cyberorg2013-06-13 09:01:44
Java
cyberorg, 2013-06-13 09:01:44

How to correctly organize the output of an error message in a Java program?

Good afternoon, Habr!
The question arose: how to properly respond to incorrect input arguments?
The situation is this:
I'm writing a launcher for one web server. By design, it can be launched in two modes:
1) In embedded mode (then it is configured in the main application)
2) In standalone mode (then parameters are passed to it via the command line)
Now it's done like this:
All arguments are validated in one place (in object setters configuration) and if the parameter is critical (for example, the port on which the server starts), then an exception is thrown outside.
The situation is aggravated by the fact that validation occurs in the constructor, it turns out that even the constructor throws an exception (which, to put it mildly, should not be, judging by the advice in the Perfect Code book).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
serso, 2013-06-13
@serso

You are doing everything right. Only if your application is launched from the console, I would suggest using the Commons CLI to parse the input arguments.
I don’t see the problem of validation in the constructor ( for example ), but if you really want to change it, enter a static factor method in which you place all the validation, and make the constructor private.
I would probably do this: Input in the form of Commons CLI Options, then convert it to a class-structure of the setting (independent of the CLI, in the case of embedded mode, also filling in this structure) without validation, a static factor method with this setting, where all validation and setting of business object parameters takes place.

K
KEKSOV, 2013-06-13
@KEKSOV

“Usually I write like this” (c)
1. In the constructor, all configuration parameters are set to default values
​​2. By any means - from environment variables, command line arguments, configuration files, etc. we are trying to clarify our configuration
3. We create the validate () method - only in it we check our configuration for validity and only in it we write errors related to this
4. We start the main branch of the program
In pseudocode, it looks like this
service = new TService ();
service.loadConfig()
service.validateConfig();
service.doJob();
And everything is correctly written in the book - no exceptions in the constructors!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question