Rewrite service request using optionals - java

I want to rewrite the code below using Optionals ( I do not control jpaConnector ):
public boolean deleteLockStatus() {
IMdss service = jpaConnector.getMdssService();
if ( service == null ) {
return false;
}
ServiceResponse response = null;
try {
response = service.deleteLockStatus();
} catch (Exception e) {
e.printStackTrace();
}
if ( response == null ) {
return false;
}
if ( response.isError() ) {
return false;
}
return true;
}
I have achievied this so far:
public boolean deleteLockStatus() {
Optional<IMdss> service = Optional.ofNullable(jpaConnector.getMdssService());
if (!service.isPresent()) { return false; }
Optional<ServiceResponse> response = Optional.empty();
try {
response = Optional.ofNullable(service.get().deleteLockStatus());
if ( response.isPresent() == false || response.get().isError() ) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Is there a better and more native java 8 way? Thank you!!!

We start with an Optional<Service>, flat map that to an Optional<ServiceResponse> (using the regular map function would give us Optional<Optional<ServiceResponse>>), then map that to an Optional<Boolean>.
The Optional<Boolean> represents success or failure of the response. If we don't have a value here, an exception was thrown so we return false with orElse(false).
It's a shame about the checked exception and having to print the stack trace, or else it could be a lot more concise.
public boolean deleteLockStatus() {
return Optional.ofNullable(jpaConnector.getMdssService())
.flatMap(service -> {
try {
return Optional.ofNullable(service.deleteLockStatus());
}
catch(Exception e) {
e.printStackTrace();
return Optional.empty();
}
})
.map(ServiceResponse::isError)
.orElse(false);
}
Side note: catching Exception is usually a bad idea. You should be as specific as possible. Consider using this syntax if there are multiple possible exceptions which may be thrown.
As mentioned in the comments by Federico, you can replace the flatMap with this slight simplification if you don't mind using null. I would personally prefer the version above.
.map(service -> {
try {
return service.deleteLockStatus();
}
catch(Exception e) {
e.printStackTrace();
return null;
}
})

Related

Handle object mapper exception and missing return statement

I am contemplating throwing a RuntimeException inside the catch block to solve the missing return statement.
What would be way to handle this situation?
I think throwing an exception of some kind instead of return some meaningless value. .
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//missing return statement
}
It depends on what you want to be the fallback/default value or error handling
You have 2 main options (with 2 sub options):
1.A.Throw the exception:
private String tryObjMapper(Object obj) throws JsonProcessingException {
return objectMapper.writeValueAsString(obj);
}
1.B.Rethrow RuntimeException (or custom unchecked exception)
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException("Failed to map obj +" obj, e);
}
}
2.A.Define a default value on error
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;//or other default value
}
2.B.Define a default value with a single return statement:
private String tryObjMapper(Object obj) {
String retVal = null;//or other default value
try {
retVal = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return retVal ;
}
Consider logging exception using logger and not using e.printStackTrace()
I think that the best way to handle it is to return null at both catch block ant the end of the function. You must check the returnee from the function whether null or not before usage.
Note: This solution is suitable if only you can't change the signature of the function to declare that it throws an exception. Otherwise, go with the signature update.

One method to capture most of the try catch statements

In my UI java test framework I have lots of methods that are doing try catch around element actions like click, send keys etc and return true when action is successful and false when any exception occurs. I was wondering is there any smarter way to pass the method as parameter and in that one method surround that code with try catch statement. So that code could be simpler and cleaner to read (may be Java 8 functional interfaces).
public boolean expandPanel(String panelHeading) {
boolean panelFound = false;
try {
getElement(PanelHeadings.fromString(panelHeading)).click();
panelFound = true;
} catch (Exception e) {
panelFound = false;
}
return panelFound;
}
I did try creating an actions class and defining different methods for click, sendKeys etc. But is there a way if i can just have one try catch method and pass code or behaviour to that method.
public boolean expandPanel(String panelHeading) {
return actions.click(getElement(PanelHeadings.fromString(panelHeading)));
}
public class WebElementActions {
public Boolean click(WebElement element) {
try {
element.click();
return true;
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
}
You could do something like
public boolean executeSafely(Runnable action) {
try {
action.run();
return true;
} catch (Exception x) {
return false;
}
}
And then call it with return executeSafely(element::click).

How to regroup catch finally into one method in java 8?

New to java 8, I would like to optimise my code bellow:
public Response create() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
public Response update() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
I have a lot of methods using this same way to catch exceptions and do the same finally, is that possible to replace the bellow common code by a method in java 8? So that I could optimise all my methods who use this common code.
} catch (Exception e) {
codeA;
} finally {
codeB;
}
Depends what you do in the .... You could do something like this:
private Response method(Supplier<Response> supplier) {
try{
return supplier.get();
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
and invoke like:
public Response create() { return method(() -> { ... for create }); }
public Response update() { return method(() -> { ... for update }); }
You could wrap your payload and put it to the separate method. One thing; what do you expect to return on exception catch. This time this is null, but probably you could provide default value.
public static <T> T execute(Supplier<T> payload) {
try {
return payload.get();
} catch(Exception e) {
// code A
return null;
} finally {
// code B
}
}
Client code could look like this:
public Response create() {
return execute(() -> new CreateResponse());
}
public Response update() {
return execute(() -> new UpdateResponse());
}
This could be a generic solution.
//here describe supplier which can throw exceptions
#FunctionalInterface
public interface ThrowingSupplier<T> {
T get() throws Exception;
}
// The wrapper
private <T> T callMethod(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (Exception e) {
//code A
}finally {
// code B
}
}

Java - How to setup validation with different error messages

I have a FileUtils class that I would like to call that does some validation, and if it's wrong, it needs to return a good error message as to why the validation failed. So I have:
public static boolean isValidFile(File file) throws Exception
{
if(something)
throw new Exception("Something is wrong");
if(somethingElse)
throw new Exception("Something else is wrong");
if(whatever)
throw new Exception("Whatever is wrong");
return true;
}
public void anotherMethod()
{
try
{
if(isValidFile(file))
doSomething();
} catch (Exception e) {
displayErrorMessage(e.getMessage());
}
}
But this just seems odd to me because the isValidFile call can never be false. Also if I reverse the order of the if condition to do a quick boot out of the code if it's false, it's even weirder looking. Plus I don't like having exception handling code as a way of passing an error message.
public void anotherMethod()
{
try
{
if(!isValidFile(file))
return;
doSomething();
..
doMoreThings();
} catch (Exception e) {
displayErrorMessage(e.getMessage());
}
}
Is there a way to do all this without using Exceptions to and still be able to have the isValidFile() method return an indication of what the error is without returning an int with an error code like you see in C, etc.
You can e.g. change your method to
public static List<String> isValidFile(File file)
When the file is valid return an empty list or null,
otherwise return a list with the validation problems. The
return value is your indication if validation failed or not.
You could do something like this:
public static String validateFile(File file)
{
String ret = null;
if(something) {
ret = "Something is wrong";
} else if(somethingElse) {
ret = "Something else is wrong";
} else if(whatever) {
ret ="Whatever is wrong";
}
return ret;
}
public void anotherMethod()
{
String errorMessage = validateFile(file);
boolean fileIsValid = errorMessage == null;
if (fileIsValid) {
doSomething();
} else {
displayErrorMessage(errorMessage);
}
}
Not really pretty, but it gets the job done.

Java How do you initialize Ehcache?

How do I surround a try catch around my Ehcache in the attempt to make sure it has started correctly?
You can write wrapper method which checks the status of cache with CacheManager e.g.,
/**
*
* #return true if Caching system is live otherwise false
*/
public boolean isAlive()
{
return net.sf.ehcache.Status.STATUS_ALIVE == cacheManager.getStatus();
}
You can always wrap your caching calls as
public Object getVal(Object aKey, Object aDefaultValue)
{
Element element = null;
if (Util.isAlive())
{
try
{
element = cache.get(aKey);
}
catch (IllegalStateException e)
{
//Log it
}
catch (RuntimeException r)
{
//Log it
}
}
return ((element == null) ? aDefaultValue : element.getObjectValue());
}
Hope this helps

Categories

Resources