Can Optional be used to as alternative to catch ConversionException

try_convert
try_parse vs try_convert
try_cast
try_parse is not a recognized built-in function name
try parse in sql server
sql cast
sql to string
sql convert

How to refactor the following code of reading properties file, so that it returns int, double or String depending on the read value?

    public static <T> T readFromConfig(String keyName) {
    PropertiesConfiguration config = new PropertiesConfiguration();
    String propertiesFilePath = "src/main/resources/application.properties";
    try {
        config.load(propertiesFilePath);
        try {
            Integer value = config.getInt(keyName);
            return (T) value;
        } catch (ConversionException notInteger) {
            try {
                Double value = config.getDouble(keyName);
                return (T) value;
            } catch (ConversionException notDouble) {
                return (T) config.getString(keyName);
            }
        }
    } catch (ConfigurationException e) {
        logger.warn("Could not parse " + propertiesFilePath);
        return (T) "";
    }
}

As the author figured himself: Optional<> isn't an option here, because, as the other answer shows: it would result in returning Optional<Object> which gives even less type information.

But honestly, from a clean code perspective, even the idea of

public static <T> T readFromConfig(String keyName) {

is kinda flawed. What does that method buy? Nothing. Because the caller says: I expect an Integer to come back, but you push back a Double or even String. You see, the compiler gets told "the method should return Integer, or Double, ...", and then it sees: "yes, possible". But that is totally decoupled from what happens at runtime.

If you go:

Integer intVal = readFromConfig("keyPointingToDoubleValue");

the compiler will not complain. Because it sees: you want an Integer; and hey, the method can return an Integer.

At runtime? When the value is retrieved, and isn't an Integer, a Double or String is returned. No idea what will happen here (class cast exception, or maybe some stack violation). But it should not work at runtime.

So, the real solution goes like this:

Either you have multiple methods, such as:

public static Integer readIntegerFromConfig(String keyName) throws SomeException ...
public static Integer readIntegerFromConfig(String keyName, Integer Default) throws SomeException ...

Or maybe:

public static Object readFromConfig(String keyName) {

or

public static <T> T readFromConfig(String keyName, T default)

In other words: you want an API that allows users of it to really say what they want, and always give them what they want. Or you totally avoid distinct types on that level, and return Strings, and have the client code make conversions.

Your current approach, as said: buys you nothing, at the cost of a misleading, complicated API.

Object Design: Roles, Responsibilities, and Collaborations, Common error logging or reporting mechanisms Data conversion Exception handlers . already implemented Unhappy path scenarios Optional features 1 Alternative It ' s easy to get caught up in a debate of what ' s core and what ' s in the rest . spend working in uninterrupted stretches , can be critical to your success . Sometimes, when an Optional value is not present, all you want to do is to throw an explicit exception. Starting with Java 10, if that exception is java.util.NoSuchElementException then simply rely on orElseThrow () method without arguments - item 5.

Here is what I can suggest you also this is a clear violation of Single Responsibility Principle (SRP) as it tries to convert to three different types which should be avoided for cleaner code :

public static Optional<Object> readFromConfig(String keyName) {
    PropertiesConfiguration config = new PropertiesConfiguration();
    String propertiesFilePath = "src/main/resources/opf.properties";
    try {
        config.load(propertiesFilePath);

        return Stream.<Supplier<Optional>>of(
                () -> Optional.of(config.getInt(keyName)),
                () -> Optional.of(config.getDouble(keyName)),
                () -> Optional.of(config.getString(keyName)))
                .map(Supplier::get)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .findFirst();

    } catch (Exception e) {
        return Optional.empty();
    }
}

TRY_PARSE, TRY_CONVERT And TRY_CAST In SQL Server, We can use TRY-CATCH inside Stored Procedure, Triggers to handle three functions which helps us to handle type conversion exception. Culture – It is an optional argument which helps to convert the value to in Culture format. in SQL Azure so use TRY_CAST or TRY_PARSE instead of that. Thirdly  You can also use the isPresent() method to find out whether a value is present in an Optional object. In addition, there's a get() method that returns the value contained in the Optional object, if it is present.

So, that's the end of deiscussion. The answer for question "Can Optional be used to as alternative to catch ConversionException?" is NO

Frequently Asked Questions, All dependencies are optional, XStream uses since version 1.4.1 by default You may also try to use the JavaBeanConverter as alternative to the Therefore XStream can handle quite any class, especially the ones referred as POJO with priority LOW that claims to handle any type and throw a ConversionException in  arrays, the length property can be used. On the whole, Optional adds unnecessary complexity. Constructor and method parameters. Although it might be tempting to consider Optional for not mandatory method parameters, such a solution pale in comparison with other possible alternatives.

SQL Server Data Type Conversion Methods and performance , The culture can be provided with the optional USING clause. Let us see practically how we can use these three conversion functions, addition to data type conversion exception handling mechanism to handle the The statements used for the three new conversion functions, which is very similar to the  Throwing exceptions – Alternative to try-catch. The previous program is the robust way of handling the exception. OK 1 is printed even if the def.txt file does not exist. Of course, everyone accepts writing a try-catch block is laborious. But no way if the coding is required robust.

5 Things About Scala (that I wish I knew 6 years ago), Option can be thought of as a special container, that can hold either exactly one for us to use Option where the compiler can check that we're using it right, and handle However, instead of having a pointer to the next item in the tail, a lazy list just has a whereas this will get you a conversion exception:. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Custom error reporting, A plug-in might do operations exactly as you require, but you might to customize the error reporting. is in the pre-validation operation when the pattern matching option is applied. and replace it with a different exception carrying your alternative error message. preValidate(data); } catch (ConversionException e) { if (e. The use of try-catch solves the problem, but the conciseness of a Lambda Expression is lost and it's no longer a small function as it's supposed to be. To deal with this problem, we can write a lambda wrapper for the lambda function. Let's look at the code to see how it works:

Comments
  • I don't see how an Optional can be used here to optimize the code. IMHO you have to try different conversions if you don't know which datatype is given within the properties. I think the code is easy to understand and does not see the ultimate need for optimization here.
  • OK, so Optional can catch only NPE, right?
  • Yes, an Optional is used to prevent returning null. Null checks and/or NPEs can be reduced though.
  • Note that this is also a bit strange use of PropertiesConfiguration. You should know in advance which type the property should have, and try to fetch only that type.
  • I noticed that your question is still "open": you didn't accept an answer. Please have a look and decide if you want to accept an answer. Or let me know if there is something I can do to enhance my input to make it accept worthy. Accepting helps future readers to determine if the problem is solved, and shows appreciation for the people who took the time answering you.
  • I agree with you completely, as you described there is no easy workaround for a better API in this purpose. and again From clean code perspective it's also worth to mention that, each method should be doing only one logic but the author tries to do 3 different things which violates clean code principals. Also for clear description your answer also deserves an up-vote :)
  • Which is not really an improvement.
  • @GhostCat from clean code perspective is an improvement otherwise no. this code has high cyclomatic complexity (3 level inner try catch) whereas mine not
  • But well, i get your point. Got my vote for that. Feel free to comment on my answer ;-)
  • @GhostCat thanks for that :) . sure, apart from cyclomatic complexity, the stream in my example has got O(n) if you mean time complexity of that and as n here is 3 which is a small amount could be ignore comparing to the readability and reducing cyclomatic factor. hope I described it clearly.
  • Yeah, well. Stream and "performance" I often cringe. A ton of things happen in the background when you call that such little methods like of(). Out of curiosity: when getInt() would throw ... that results in the Optional.of() getting null? Wouldnt that just throw up right there? Without a try/catch?