Java 8 Replace two null check with Optional - java

Below is my code which is working as expected. But I need to replace it with Optional.ofNullable
if (getFirstData != null && getSecondData !=null {
... doing my work here
} else {
... doing my else work here
}
How can I use Optionals.ofNullable(..) to replace two AND null checks?

It may be a bit overkill, but if there's need to check multiple values for nulls, it may be done like this using Optional:
static boolean allNonNullsOptional(Object ... items) {
return Stream.of(items).map(Optional::ofNullable).allMatch(Optional::isPresent);
}
But the same may be achieved with much shorter Object::nonNull:
static boolean allNonNulls(Object ... items) {
return Stream.of(items).allMatch(Objects::nonNull);
}

Just technically what you want can be achieved the following way
if (Optional.ofNullable(getFirstData).isPresent() && Optional.ofNullable(getSecondData).isPresent() ) {
... doing my work here
} else {
... doing my else work here
}
But as other commenters have already pointed out, it does not seem wise to do so.

Related

What's the advantage of Optional.ofNullable(itemKey) over itemKey == null

I was just wondering when do we need to choose Optional over if else or nested null check. say for example is there any advantage of one another below or do you think the Optional could be an overkill
String.valueOf(Optional.ofNullable(itemKey).map(ItemKey::getId).orElse(null));
vs
String.valueOf(itemKey == null ? null : itemKey.getId());
I always keen to use the Optional.of or Optional.ofNullable when I had to pick nested item of a given object like below,
private String formatCurrency(String symbol, BigDecimal value) {
return Optional.ofNullable(value)
.map(BigDecimal::doubleValue)
.map(Object::toString)
.map(val -> symbol + val.replaceAll(REGEX_REMOVE_TRAILING_ZEROS, "$2"))
.orElse("");
}
Can I please know where in the code the Optional is absolutely unnecessary.
If you already have itemKey in your code, there is no meaning of transforming it to an Optional, it just makes the code more complex. However, if you want to use optionals, I think it'd be more appropriate to do something like this:
public Optional<ItemKey> getItemKey() {
if (...) {
return Optional.of(new ItemKey());
}
return Optional.empty()
}
public void mainCode() {
String id = getItemKey().map(ItemKey::getId).orElse(null);
}

Stop a chain of methods without returning booleans

I have not doubt that there is a solution posted for this, but I can't find the search term retrieve it, so if it does exist please point me to the duplicate and mark this as such.
I have a chain of methods performing various validation checks on a button click event, I display a message if the validation has failed, currently my solution is to then pass back a boolean so that if the method failed the remaining methods will not run.
I don't like this, when I have several methods all passing back booleans my code starts to smell.
is there a better solution to this? (I'd don't want to use a instance variable)
Example of the code as it currently stands:
private void SUBMIT_BUTTON_CLICK(){
if(validate()){
//Do Stuff
}
}
private boolean validate(){
return checkOne() && checkTow() && checkThree() && checkFour();
}
private boolean checkOne(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
private boolean checkTow(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
private boolean checkThree(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
private boolean checkFour(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
Convenionally you would use exceptions:
void check1(Foo value) {
if(some test on value) {
throw new ValidationException(...);
}
}
try {
check1(value);
check2(value);
} catch (ValidationException e) {
// deal with validation failure
}
A bonus here is that the exception can carry information about the failure. Your boolean false just says "it failed", with no explanation.
Another bonus, of course, is that you're free to pass the exception higher up the call stack, where some other code can deal with it.
Some people worry about the cost of building exceptions (or more accurately, collecting that stack trace contained within). I'd advise not worrying about it unless you get performance problems and profiling points the finger at exceptions.
There are alternatives though. For example your validation could return Optional<ValidationError>:
Optional<ValidationError> check1(Foo value) {
if(some test on value) {
return Optional.of(new ValidationError(...));
} else {
return Optional.empty();
}
}
Then...
Optional<ValidationError> validationResult =
check1(value)
.orElseGet( () -> check2(value))
.orElseGet( () -> check3(value));
You could, of course, loop through a list of validators, rather than hard-code like this.
Some of the functional programming libraries (e.g. vavr) include an Either class, which can be used in a similar way, where instead of being either an error or empty(), it's an error or a success value.
Or you could stick with methods returning boolean, but use them as Predicates:
List<Predicate<Foo>> checks = Arrays.asList(
f -> check1(f),
f -> check2(f),
f -> check3(f)
);
(Or the equivalent with method references e.g. this::check1)
checks.stream().allMatch(check -> check.test(value));
As you can see, there are tons of possibilities. But think about whether you're over-complicating. There's mostly nothing inherently wrong with the simple approach you already have -- although it is better, and more testable, to return a failure reason, rather than print it as a side-effect.
Chaining like you are currently doing is generally the best solution. It is easy to understand, efficient and (relatively) concise.
A couple of other ideas would be:
build an array of predicates and then iterate and call them, or
use exceptions and exception handling
but both of these have performance implications, and they will only give "cleaner" code if you have a vast number of predicates to evaluate.
Sometimes an inelegant solution is more elegant than looking for a clever solution.
Consider this: if I use exceptions, I can rewrite the validate() method
private boolean validate(){
return checkOne() && checkTow() && checkThree() && checkFour();
}
as
private void validate() throws ValidationException {
checkOne(); checkTow(); checkThree(); checkFour();
}
But how much have I actually gained here? It is still two lines of code. And if I were to follow Java's style rules it would be:
private void validate() throws ValidationException {
checkOne();
checkTow();
checkThree();
checkFour();
}
which is more lines than we started with. And we haven't considered the predicates themselves or the code that handles the validation exception.
Based on my comment: you're probably after exceptions.
Example (pseudo code):
void checkOne() {
if( check_fails ) {
throw new CheckOneException();
}
}
void checkTwo() {
if( check_fails ) {
throw new CheckTwoException();
}
}
void validate() {
checkOne();
checkTwo();
}
void SUBMIT_BUTTON_CLICK() {
try {
validate();
//Do Stuff
} catch( CheckOneException | CheckTwoException ) {
//handle the exceptions
}
}
Note that you might have to either declare the exceptions to be thrown or make them runtime exceptions.
Additionally you might want to use multiple catch-blocks if the handling depends on the type of exception. Alternatively you could also throw the same type of exception if that fits your needs.

Shortening if() with string.equals method

Is there any way to shorten this if() statement? To avoid repeating string.equals() somehow?
if (extension.equals("jpg") || extension.equals("JPG") || extension.equals("png") || extension.equals("PNG") || extension.equals("bmp") || extension.equals("BMP") || extension.equals("jpeg") || extension.equals("JPEG"))
{
tmp.setIcon(new ImageIcon(getClass().getResource("/menage/Resources/imageIco.png")));
}
To something looking similar to this :
if (extension.equals(("jpg")||("JPG")||("png")||("PNG")||("bmp")||("BMP")||("jpeg")||("JPEG")))
{
tmp.setIcon(new ImageIcon(getClass().getResource("/menage/Resources/imageIco.png"));)
}
I am aware that this question looks odd, however if() with such long conditions list is unclear and requires a lot of writing as well.
Start by changing equals(...) to equalsIgnoreCase(...).
Other options, create a HashSet of lower case Strings (or upper case if desired) with your image extensions and see if it contains your String of interest, changed to lower case:
if (imageExtSet.contains(myExtension.toLowerCase()) {
}
Here is short version with predefined image types:
Set<String> imgTypes = new HashSet<>() {{
add("jpg"); add("JPG");
add("png"); add("PNG");
add("bmp"); add("BMP");
add("jpeg"); add("JPEG");
}};
public boolean isImgType(String type) {
return imgTypes.contains(type);
}
You can keep all values in a list and then asks if contains. If it's only a one liner (you don't need to ask for this condition anywhere else), you can do:
if (Arrays.asList("jpg", "JPG", "png", "PNG", "bmp", "BMP", "jpeg", "JPEG").contains(extension))
You can of course save the list as an object and then anywhere you need to ask for this condition reference it.
Use HashSet
Like this
Set<String> extSet= new HashSet<String>();
// Add All in Lower case .. to save your efforts
extSet.add("jpg");
extSet.add("png");
//...etc etc
and just check if it is present in the Set
if(extSet.contains(extension==null?null:extension.toLowerCase()))
{
/// True
}
else
{
// False
}
One thing you can do to eliminate some checks, is to convert the string to lower case:
String ext = extension.toLowerCase();
Now you have shorten the statement to:
if (ext.equals("jpg") || ext.equals("png") || ext.equals("bmp") || ext.equals("jpeg"))
if (Arrays.asList("jpg", "jpeg", "png", "bmp").contains(extension.toLowerCase))
The other answers give lots of good low-level ideas, but the basic principle here is to prevent code reuse.
If you are doing this test more than once, create a method that does the test for you:
boolean isValidImageExtenstion(String extension) {
return (extension.equals("jpg") || extension.equals("JPG") ||
extension.equals("png") || extension.equals("PNG") ||
extension.equals("bmp") || extension.equals("BMP") ||
extension.equals("jpeg") || extension.equals("JPEG"));
}
Call the method whenever you need it. If you like you can use one of the approaches described in the other answers within the method, (and the 'ignore case' suggestion is certainly worth it) but the rest become less important now that you have prevented the code repetition. As a bonus, if you decide you want to support gif extensions you only have to make the change in one place.
The advantages of this approach over the others are that it is self-documenting. It's pretty obvious what the method does, and some of the other answers are pretty obscure.
If you are only doing this once, and don't intend to do it again, then you have already created working code, so don't waste your time modifying working code.
Add in some methods...
private static boolean isJpeg(String ext) {
return java.util.Arrays.asList("jpg", "jpeg").contains(ext.toLowerCase());
}
private static boolean isPng(String ext) {
return "png".equalsIgnoreCase(ext);
}
private static boolean isBmp(String ext) {
return "bmp".equalsIgnoreCase(ext);
}
And change it to...
else if (isJpeg(extension) || isPng(extension) || isBmp(extension))
{
tmp.setIcon(new ImageIcon(getClass().getResource("/menage/Resources/imageIco.png")));
}
The isJpeg will throw a NullPointerException if the extention is null, so ensure it's not null by adding extension != null || ... or something.
The above is slightly different for your specific case as it allows JpEg and all other mixed capitalizations to slip through. If you don't want that, use these. Plus, the below have the added benefit of never throwing NullPointerException if the extension is null.
private static boolean isJpeg(String ext) {
return java.util.Arrays.asList("jpg", "JPG", "jpeg", "JPEG").contains(ext);
}
private static boolean isPng(String ext) {
return java.util.Arrays.asList("png", "PNG").contains(ext);
}
private static boolean isBmp(String ext) {
return java.util.Arrays.asList("bmp", "BMP").contains(ext);
}

Is there a simpler way to derefence nullable references in Java?

Consider the following Code Snippet:
if (foo != null
&& foo.bar != null
&& foo.bar.boo != null
&& foo.bar.boo.far != null)
{
doSomething (foo.bar.boo.far);
}
My question is simple: is there a more simple\shorter way to do this ?
In detail: is there a more simple way to validate each part of the chain, I'd imagine similar to this ..
if (validate("foo.bar.boo.far"))
{
doSomething (foo.bar.boo.far);
}
Maybe like that ?
if (FooUtils.isFarNotEmpty(foo)){
doSomething (foo.bar.boo.far);
}
and in FooUtils :
boolean isFarNotEmpty (Foo foo){
return foo != null &&
foo.bar != null &&
foo.bar.boo != null &&
foo.bar.boo.far != null;
}
In my opinion this expression is perfect, nothing can be simpler
why you are using public instance variable, encapsulate your public variables and create getter and setter for them and you can perform these check in your getter, and you can return new Object() if any of them is null, or you can run this statement in try-catch block but not recommended,
If this is your API please consider some advice.
"I call it my billion-dollar mistake." - Sir C. A. R. Hoare, on his
invention of the null reference
There's not much you can do with this, unfortunately. If you ask me, it's a problem with the Java language. Groovy has something called the Safe Navigation Operator ?. that is specifically for this purpose. Here are two things I've done in the past.
The answer that Grisha already gave, so I won't repeat it
Naively wrote code that accesses it, and surround it in a try/catch for a NPE. Here's an example:
try {
if (foo.bar.boo.far != null) {
//do something
}
} catch (NullPointerException e) {
//do what you would do in an else
}
I don't particularly like the 2nd option, but I say if it actually makes the code cleaner, consider using it.
One time I was working with a library that is a very thin wrapper over an XML schema and I decided to use the 2nd option for this case. If I didn't, the code would have been harder to maintain because it would be so easy to forget a null check and they cluttered up the important logic. I think that's a valid case for using it.
Please try this code
try {
if (foo.bar.boo.far != null) {
//No object is null
}
} catch (Exception e) {
// some object is null and causes null point exception.
}

How to make complex conditions look nice and save the number of statements?

In my java application I have a huge set of conditions which decides just one action. My question is how to make it look nice (I use NetBeans so I'd prefer solution that will not be broken by its code formatting function). I'd also like to have there as low amount of if/else statements as possible, because I think it will make it faster.
My original code was a mess, so I made an action diagram:. Take a copy if you want to play with it. Please keep in mind that the diagram is not perfect as to UML syntax, partly because I made it using google docs.
This is the code:
if (!config.get("checkForSpecials") || event.isNotSpecial()) {
if (config.get("filterMode").equals("blacklist")) {
if (!itemFilter.contains(event.getItem().getName())) {
item.process();
}
} else if (config.get("filterMode").equals("whitelist")) {
if (itemFilter.contains(event.getItem().getName())) {
item.process();
}
} else {
item.process();
}
}
There are two things I don't like about it - the conditions are not too clear (especially when I unfold full method names and config strings), and the fact that the process method call is there three times.
Factoring booleans out and caching return values from method calls can help clarify code.
In addition, plotting all the outcomes on a logic table can help. I use this tool to help.
With the linked tool:
A: config.get("filterMode").equals("blacklist")
B: config.get("filterMode").equals("whitelist")
C: filterContainsName (see below)
The tool churns out:
(!A && !B) || (!A && C) || (A && !C)
Which leads to the code below (with a small tweak that replaces (!A && C) with (B && C)):
boolean filterContainsName = itemFilter.contains(event.getItem().getName());
boolean useBlacklist = config.get("filterMode").equals("blacklist");
boolean useWhitelist = config.get("filterMode").equals("whitelist");
if (!config.get("safeMode") || event.isSafe()) {
if((!useBlackList && !useWhiteList) ||
( useWhiteList && filterContainsName) ||
( useBlackList && !filterContainsName)) {
item.process();
}
}
Use maps. The key of the map is the condition/case, the value is a single method class/anonymouse interface that contains the logic for that condition. Whenever you encounter a certain condition/case, you simply do a lookup in the map and execute the related function. This way you can even split up your logic-by-condition into seperate classes (if needed for sake of code beauty). As an added bonus you'll probably gain a performance bonus when the # of conditions > 10.
Looks good as it is to me. Perhaps you can isolate the valid conditions for calling item.process() to a method to make it more easier to understand.
if (!config.get("safeMode") || event.isSafe()) {
if (isItemValidForProcess(config, itemFilter, event)) {
item.process();
}
}
boolean isItemValidForProcess(config, itemFilter, event) {
String filterMode = config.get("filterMode");
if (filterMode.equals("whitelist")) {
return itemFilter.contains(event.getItem().getName());
}
if (filterMode.equals("blacklist")) {
return !itemFilter.contains(event.getItem().getName());
}
return true;
}
Believe it or not, the diagram is not that complex:)
There is no loop, and it is rather linear.
Here's a pseudo code that implements it
void action()
if <sort out specials>
if <is it special>
return;
if <check for unsafe items>
if not <safe items list contains item>
return;
if <filter status = on>
if < filter mode = whitelist>
if not <item is on filter>
return;
else // black list
if not <item is on filter>
return;
// finally!
[process item]
For really complex diagram, the answer is ... goto ...

Categories

Resources