A
A
Archy9012016-06-22 13:25:01
Java
Archy901, 2016-06-22 13:25:01

There is a message with a field of type string, can I parse this field?

there is a field (string type) "value": "OK" / "Error" - that is, two possible values. Can I deduce something appropriate based on the value. For example, if "OK" came, write "everything is good", and if "Error" came, write "something wrong". Is it generally normal practice to parse a string? Or do you need to use boolean type or int for this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
Fat Lorrie, 2016-06-22
@Archy901

if(value.equals("OK"))  { ... }

switch(value) {
    case "OK": ... break;
    case "Error": ... break;
}

It is better to avoid string parameters for checking some limited list of values ​​(it will be necessary to provide for situations with different cases, spaces inside, typos that cannot be tracked during compilation, etc.), booleanor enum-types can be used instead (if more than two values).
enum Status {
    Ok,
    Error,
    Warning
}

class Foo {
    static void bar(Status status) {
        if (status == Status.Ok) {
            ... 
        }
        ...
    }
}

K
Konstantin Malyarov, 2016-06-22
@Konstantin18ko

If the final result will have the value yes/no, OK/error, true/false it is better to use boolean, if there are more than two values ​​- int.
In general, using string as a success/fail indicator is a bad idea.
It's better to use string as value decoding. Let's say boolean value is false, string value "Operation failed, boolean - true, string value "Operation completed successfully".

A
Andrey Shishkin, 2016-06-22
@compiler

Make the method void. In case something can go wrong in the logic of the method, neither boolean nor int should be returned. Throw an exception.
As a result, you will get:
If OK - just execute the logic
If Error - throw Exception

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question