Validating order of method call - java

A class named OutgoingItems has 2 methods: getNextItem() and hasItems() .
In the current implementation getNextItem() is getting into a endless loop if hasItems() == true.
Is there a way to validate in the code that this method is not being called unless the condition for hasItems() == true has been checked first?
Maybe some sort of relevant annotation for static analysis?
Assume that implementation changing is hard and there's a change that one can't just do it.

What you describe sounds semantically weird, surely calling getNextItem() doesn't make sense unless hasItems() is true?
Anyway, the idea is the same, whichever way your logic works: wrap your OutgoingItems objects into a new class that checks the condition for you. I did the check with assert but you can choose whatever way you like.
public class OutgoingItemsDelegate {
private final OutgoingItems items;
public OutgoingItemsDelegate(OutgoingItems items) {
this.items = items;
}
public boolean hasItems() {
return items.hasItems();
}
public Object getNextItem() {
assert !items.hasItems();
// alternatively you can do this:
// if (items.hasItems()) throw new IllegalStateException("hasItems() must not be true");
return items.getNextItems();
}
}
There is of course a slight performance and space overhead you might have to pay with this solution, and the ideal solution is to fix OutgoingItems itself, but failing that, it's a viable option.
*Please note that for the assert statement to be evaluated, you need to use the -ea flag on the command line.

Related

Which design pattern to use to avoid if/else in validation classes?

I am currently using HibernateConstraintValidator to implement my validations. But my reviewer is not fine with having if/else in code or ! operators. Which design pattern can I use to remove the if/else in my validation logic?
public class SomeValidatorX implements ConstraintValidator<SomeAnnotation, UUID> {
#Autowired
SomeRepository someRepository;
#Override
public boolean isValid(UUID uuid, ConstraintValidationContext context) {
return !(uuid!=null && someRepository.existsById(uuid)); //The reviewer doesn't want this negation operator
}
}
And in below code, he doesn't want if/else
public class SomeValidatorY implements ConstraintValidator<SomeAnnotation, SomeClass> {
#Autowired
SomeRepository someRepository;
#Override
public boolean isValid(SomeClass someObject, ConstraintValidationContext context) {
if(someObject.getFieldA() != null) { //He doesn't want this if statement
//do some operations
List<Something> someList = someRepository.findByAAndB(someObject.getFieldA(),B);
return !someList.isEmpty(); //He doesn't want this ! operator
}
return false; // He was not fine with else statement in here as well
}
}
Side Note: We have to use Domain Driven Design (if it helps)
A long time ago, in the beginning of time. There was a guideline that said that methods should only have one exit point. To achieve that, developers had to track the local state and use if/else to be able to reach the end of the method.
Today we know better. By exiting a method as early as possible it's much easier to keep the entire flow in our head while reading the code. Easier code means less mistakes. Less mistakes equals less bugs.
In my opinion, that's why the reviewer doesn't like the code. It's not as easy to read as it could be.
Let's take the first example:
public boolean isValid(UUID uuid, ConstraintValidationContext context) {
return !(uuid!=null && someRepository.existsById(uuid)); //The reviewer doesn't want this negation operator
}
What the code says is "not this: (uuid should not be empty and it must exist)". Is that easy to understand? I think not.
The alternative: "Its OK if uuid do not exist, but if it do, the item may not exist".
Or in code:
if (uuid == null) return true;
return !someRepository.existsById(uuid);
Much easier to read, right? (I hope that I got the intention correct ;))
Second example
if(someObject.getFieldA() != null) { //He doesn't want this if statement
//do some operations
List<Something> someList = someRepository.findByAAndB(someObject.getFieldA(),B);
return !someList.isEmpty(); //He doesn't want this ! operator
}
return false; // He was not fine with else statement in here as well
Ok. Here you are saying:
If field A is not null:
Build a list where A and b is found
If that list is not empty fail, otherwise succeed.
Otherwise fail
A easier way to conclude that is to simply say:
It's ok if field A is not specified
If field A is specified it must exist in combination with B.
Translated to code:
if (someObject.getFieldA() == null)
return true;
return !someRepository.findByAAndB(someObject.getFieldA(),B).isEmpty();
In C# we have Any() which is opposite to isEmpty which I would prefer in this case as it removes the negation.
Sometimes negations are required. It doesn't make sense to write a new method in the repository to avoid it. However, if findByAAndB is only used by this I would rename it to ensureCombination(a,b) so that it can return true for the valid case.
Try to write code as you talk, it makes it much easier to create a mental picture of the code then. You aren't saying "Im not full, lets go to lunch", are you? ;)
You can check the Null-object pattern.
The general pattern is to ban null completely from your code. This eliminates the ugly null checks. In this point I agree with your code reviewer.
Following the below recommendations will result in:
public boolean isValid(SomeClass someObject, ConstraintValidationContext context) {
return someRepository.containsAAndB(someObject.getFieldA(), B);
}
Avoid null checks
Before introducing the Null-object pattern, simply apply the pattern or convention to enforce initialization of all references. This way you can be sure that there are no null references in your entire code.
So when you encounter a NullPointerException, you don't solve the issue by introducing a null check, but by initializing the reference (on construction) e.g., by using default values, empty collections or null objects.
Most modern languages support code analysis via annotations like #NonNull that checks references like arguments and will throw an exception, when a parameter is null/not initialized. javax.annotation for instance provides such annotations.
public void operation(#NonNull Object param) {
param.toString(); // Guaranteed to be not null
}
Using such annotations can guard library code against null arguments.
Null-Object Pattern
Instead of having null references, you initialize each reference with a meaningful value or a dedicated null-object:
Define the Null-object contract (not required):
interface NullObject {
public boolean getIsNull();
}
Define a base type:
abstract class Account {
private double value;
private List<Owner> owners;
// Getters/setters
}
Define the Null-object:
class NullAccount extends Account implements NullObject {
// Initialize ALL attributes with meaningful and *neutral* values
public NullAccount() {
setValue(0); //
setOwners(new ArrayList<Owner>())
#Override
public boolean getIsNull() {
return true;
}
}
Define the default implementation:
class AccountImpl extends Account implements NullObject {
#Override
public boolean getIsNull() {
return true;
}
}
Initialize all Account references using the NullAccount class:
class Employee {
private Account Account;
public Employee() {
setAccount(new NullAccount());
}
}
Or use the NullAccount to return a failed state instance (or default) instead of returning null:
public Account findAccountOf(Owner owner) {
if (notFound) {
return new NullAccount();
}
}
public void testNullAccount() {
Account result = findAccountOf(null); // Returns a NullAccount
// The Null-object is neutral. We can use it without null checking.
// result.getOwners() always returns
// an empty collection (NullAccount) => no iteration => neutral behavior
for (Owner owner : result.getOwners()) {
double total += result.getvalue(); // No side effect.
}
}
Try-Do Pattern
Another pattern you can use is the Try-Do pattern. Instead of testing the result of an operation you simply test the operation itself. The operation is responsible to return whether the operation was successful or not.
When searching a text for a string, it might be more convenient to return a boolean whether the result was found instead of returning an empty string or even worse null:
public boolean tryFindInText(String source, String searchKey, SearchResult result) {
int matchIndex = source.indexOf(searchKey);
result.setMatchIndex(matchIndex);
return matchIndex > 0;
}
public void useTryDo() {
SearchResult result = new Searchresult();
if (tryFindInText("Example text", "ample", result) {
int index = result.getMatchIndex();
}
}
In your special case, you can replace the findByAAndB() with an containsAAndB() : boolean implementation.
Combining the patterns
The final solution implements the Null-Object pattern and refactors the find method. The result of the original findByAAndB() was discarded before, since you wanted to test the existence of A and B. A alternative method public boolean contains() will improve your code.
The refactored implementation looks as followed:
abstract class FieldA {
}
class NullFieldA {
}
class FieldAImpl {
}
class SomeClass {
public SomeClass() {
setFieldA(new NullFieldA());
}
}
The improved validation:
public boolean isValid(SomeClass someObject, ConstraintValidationContext context) {
return someRepository.containsAAndB(someObject.getFieldA(), B);
}
You can try this
return Optional.ofNullable(uuid)
.map(someRepository::existsById)
.orElse(false);

Getter on nested objects without having NullPointerException [duplicate]

A web service returns a huge XML and I need to access deeply nested fields of it. For example:
return wsObject.getFoo().getBar().getBaz().getInt()
The problem is that getFoo(), getBar(), getBaz() may all return null.
However, if I check for null in all cases, the code becomes very verbose and hard to read. Moreover, I may miss the checks for some of the fields.
if (wsObject.getFoo() == null) return -1;
if (wsObject.getFoo().getBar() == null) return -1;
// maybe also do something with wsObject.getFoo().getBar()
if (wsObject.getFoo().getBar().getBaz() == null) return -1;
return wsObject.getFoo().getBar().getBaz().getInt();
Is it acceptable to write
try {
return wsObject.getFoo().getBar().getBaz().getInt();
} catch (NullPointerException ignored) {
return -1;
}
or would that be considered an antipattern?
Catching NullPointerException is a really problematic thing to do since they can happen almost anywhere. It's very easy to get one from a bug, catch it by accident and continue as if everything is normal, thus hiding a real problem. It's so tricky to deal with so it's best to avoid altogether. (For example, think about auto-unboxing of a null Integer.)
I suggest that you use the Optional class instead. This is often the best approach when you want to work with values that are either present or absent.
Using that you could write your code like this:
public Optional<Integer> m(Ws wsObject) {
return Optional.ofNullable(wsObject.getFoo()) // Here you get Optional.empty() if the Foo is null
.map(f -> f.getBar()) // Here you transform the optional or get empty if the Bar is null
.map(b -> b.getBaz())
.map(b -> b.getInt());
// Add this if you want to return null instead of an empty optional if any is null
// .orElse(null);
// Or this if you want to throw an exception instead
// .orElseThrow(SomeApplicationException::new);
}
Why optional?
Using Optionals instead of null for values that might be absent makes that fact very visible and clear to readers, and the type system will make sure you don't accidentally forget about it.
You also get access to methods for working with such values more conveniently, like map and orElse.
Is absence valid or error?
But also think about if it is a valid result for the intermediate methods to return null or if that is a sign of an error. If it is always an error then it's probably better throw an exception than to return a special value, or for the intermediate methods themselves to throw an exception.
Maybe more optionals?
If on the other hand absent values from the intermediate methods are valid, maybe you can switch to Optionals for them also?
Then you could use them like this:
public Optional<Integer> mo(Ws wsObject) {
return wsObject.getFoo()
.flatMap(f -> f.getBar())
.flatMap(b -> b.getBaz())
.flatMap(b -> b.getInt());
}
Why not optional?
The only reason I can think of for not using Optional is if this is in a really performance critical part of the code, and if garbage collection overhead turns out to be a problem. This is because a few Optional objects are allocated each time the code is executed, and the VM might not be able to optimize those away. In that case your original if-tests might be better.
I suggest considering Objects.requireNonNull(T obj, String message). You might build chains with a detailed message for each exception, like
requireNonNull(requireNonNull(requireNonNull(
wsObject, "wsObject is null")
.getFoo(), "getFoo() is null")
.getBar(), "getBar() is null");
I would suggest you not to use special return-values, like -1. That's not a Java style. Java has designed the mechanism of exceptions to avoid this old-fashioned way which came from the C language.
Throwing NullPointerException is not the best option too. You could provide your own exception (making it checked to guarantee that it will be handled by a user or unchecked to process it in an easier way) or use a specific exception from XML parser you are using.
Assuming the class structure is indeed out of our control, as seems to be the case, I think catching the NPE as suggested in the question is indeed a reasonable solution, unless performance is a major concern. One small improvement might be to wrap the throw/catch logic to avoid clutter:
static <T> T get(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
} catch (NullPointerException e) {
return defaultValue;
}
}
Now you can simply do:
return get(() -> wsObject.getFoo().getBar().getBaz().getInt(), -1);
As already pointed out by Tom in the comment,
Following statement disobeys the Law of Demeter,
wsObject.getFoo().getBar().getBaz().getInt()
What you want is int and you can get it from Foo. Law of Demeter says, never talk to the strangers. For your case you can hide the actual implementation under the hood of Foo and Bar.
Now, you can create method in Foo to fetch int from Baz. Ultimately, Foo will have Bar and in Bar we can access Int without exposing Baz directly to Foo. So, null checks are probably divided to different classes and only required attributes will be shared among the classes.
My answer goes almost in the same line as #janki, but I would like to modify the code snippet slightly as below:
if (wsObject.getFoo() != null && wsObject.getFoo().getBar() != null && wsObject.getFoo().getBar().getBaz() != null)
return wsObject.getFoo().getBar().getBaz().getInt();
else
return something or throw exception;
You can add a null check for wsObject as well, if there's any chance of that object being null.
You say that some methods "may return null" but do not say in what circumstances they return null. You say you catch the NullPointerException but you do not say why you catch it. This lack of information suggests you do not have a clear understanding of what exceptions are for and why they are superior to the alternative.
Consider a class method that is meant to perform an action, but the method can not guarantee it will perform the action, because of circumstances beyond its control (which is in fact the case for all methods in Java). We call that method and it returns. The code that calls that method needs to know whether it was successful. How can it know? How can it be structured to cope with the two possibilities, of success or failure?
Using exceptions, we can write methods that have success as a post condition. If the method returns, it was successful. If it throws an exception, it had failed. This is a big win for clarity. We can write code that clearly processes the normal, success case, and move all the error handling code into catch clauses. It often transpires that the details of how or why a method was unsuccessful are not important to the caller, so the same catch clause can be used for handling several types of failure. And it often happens that a method does not need to catch exceptions at all, but can just allow them to propagate to its caller. Exceptions due to program bugs are in that latter class; few methods can react appropriately when there is a bug.
So, those methods that return null.
Does a null value indicate a bug in your code? If it does, you should not be catching the exception at all. And your code should not be trying to second guess itself. Just write what is clear and concise on the assumption that it will work. Is a chain of method calls clear and concise? Then just use them.
Does a null value indicate invalid input to your program? If it does, a NullPointerException is not an appropriate exception to throw, because conventionally it is reserved for indicating bugs. You probably want to throw a custom exception derived from IllegalArgumentException (if you want an unchecked exception) or IOException (if you want a checked exception). Is your program required to provide detailed syntax error messages when there is invalid input? If so, checking each method for a null return value then throwing an appropriate diagnostic exception is the only thing you can do. If your program need not provide detailed diagnostics, chaining the method calls together, catching any NullPointerException and then throwing your custom exception is clearest and most concise.
One of the answers claims that the chained method calls violate the Law of Demeter and thus are bad. That claim is mistaken.
When it comes to program design, there are not really any absolute rules about what is good and what is bad. There are only heuristics: rules that are right much (even almost all) of the time. Part of the skill of programming is knowing when it is OK to break those kinds of rules. So a terse assertion that "this is against rule X" is not really an answer at all. Is this one of the situations where the rule should be broken?
The Law of Demeter is really a rule about API or class interface design. When designing classes, it is useful to have a hierarchy of abstractions. You have low level classes that uses the language primitives to directly perform operations and represent objects in an abstraction that is higher level than the language primitives. You have medium level classes that delegate to the low level classes, and implement operations and representations at a higher level than the low level classes. You have high level classes that delegate to the medium level classes, and implement still higher level operations and abstractions. (I've talked about just three levels of abstraction here, but more are possible). This allows your code to express itself in terms of appropriate abstractions at each level, thereby hiding complexity. The rationale for the Law of Demeter is that if you have a chain of method calls, that suggests you have a high level class reaching in through a medium level class to deal directly with low level details, and therefore that your medium level class has not provided a medium-level abstract operation that the high level class needs. But it seems that is not the situation you have here: you did not design the classes in the chain of method calls, they are the result of some auto-generated XML serialization code (right?), and the chain of calls is not descending through an abstraction hierarchy because the des-serialized XML is all at the same level of the abstraction hierarchy (right?)?
As others have said, respecting the Law of Demeter is definitely part of the solution. Another part, wherever possible, is to change those chained methods so they cannot return null. You can avoid returning null by instead returning an empty String, an empty Collection, or some other dummy object that means or does whatever the caller would do with null.
To improve readability, you may want to use multiple variables, like
Foo theFoo;
Bar theBar;
Baz theBaz;
theFoo = wsObject.getFoo();
if ( theFoo == null ) {
// Exit.
}
theBar = theFoo.getBar();
if ( theBar == null ) {
// Exit.
}
theBaz = theBar.getBaz();
if ( theBaz == null ) {
// Exit.
}
return theBaz.getInt();
Don't catch NullPointerException. You don't know where it is coming from (I know it is not probable in your case but maybe something else threw it) and it is slow.
You want to access the specified field and for this every other field has to be not null. This is a perfect valid reason to check every field. I would probably check it in one if and then create a method for readability. As others pointed out already returning -1 is very oldschool but I don't know if you have a reason for it or not (e.g. talking to another system).
public int callService() {
...
if(isValid(wsObject)){
return wsObject.getFoo().getBar().getBaz().getInt();
}
return -1;
}
public boolean isValid(WsObject wsObject) {
if(wsObject.getFoo() != null &&
wsObject.getFoo().getBar() != null &&
wsObject.getFoo().getBar().getBaz() != null) {
return true;
}
return false;
}
Edit: It is debatable if it's disobeyes the Law Of Demeter since the WsObject is probably only a data structure (check https://stackoverflow.com/a/26021695/1528880).
If you don't want to refactor the code and you can use Java 8, it is possible to use Method references.
A simple demo first (excuse the static inner classes)
public class JavaApplication14
{
static class Baz
{
private final int _int;
public Baz(int value){ _int = value; }
public int getInt(){ return _int; }
}
static class Bar
{
private final Baz _baz;
public Bar(Baz baz){ _baz = baz; }
public Baz getBar(){ return _baz; }
}
static class Foo
{
private final Bar _bar;
public Foo(Bar bar){ _bar = bar; }
public Bar getBar(){ return _bar; }
}
static class WSObject
{
private final Foo _foo;
public WSObject(Foo foo){ _foo = foo; }
public Foo getFoo(){ return _foo; }
}
interface Getter<T, R>
{
R get(T value);
}
static class GetterResult<R>
{
public R result;
public int lastIndex;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
WSObject wsObject = new WSObject(new Foo(new Bar(new Baz(241))));
WSObject wsObjectNull = new WSObject(new Foo(null));
GetterResult<Integer> intResult
= getterChain(wsObject, WSObject::getFoo, Foo::getBar, Bar::getBar, Baz::getInt);
GetterResult<Integer> intResult2
= getterChain(wsObjectNull, WSObject::getFoo, Foo::getBar, Bar::getBar, Baz::getInt);
System.out.println(intResult.result);
System.out.println(intResult.lastIndex);
System.out.println();
System.out.println(intResult2.result);
System.out.println(intResult2.lastIndex);
// TODO code application logic here
}
public static <R, V1, V2, V3, V4> GetterResult<R>
getterChain(V1 value, Getter<V1, V2> g1, Getter<V2, V3> g2, Getter<V3, V4> g3, Getter<V4, R> g4)
{
GetterResult result = new GetterResult<>();
Object tmp = value;
if (tmp == null)
return result;
tmp = g1.get((V1)tmp);
result.lastIndex++;
if (tmp == null)
return result;
tmp = g2.get((V2)tmp);
result.lastIndex++;
if (tmp == null)
return result;
tmp = g3.get((V3)tmp);
result.lastIndex++;
if (tmp == null)
return result;
tmp = g4.get((V4)tmp);
result.lastIndex++;
result.result = (R)tmp;
return result;
}
}
Output
241
4
null
2
The interface Getter is just a functional interface, you may use any equivalent.
GetterResult class, accessors stripped out for clarity, hold the result of the getter chain, if any, or the index of the last getter called.
The method getterChain is a simple, boilerplate piece of code, that can be generated automatically (or manually when needed).
I structured the code so that the repeating block is self evident.
This is not a perfect solution as you still need to define one overload of getterChain per number of getters.
I would refactor the code instead, but if can't and you find your self using long getter chains often you may consider building a class with the overloads that take from 2 to, say, 10, getters.
I'd like to add an answer which focus on the meaning of the error. Null exception in itself doesn't provide any meaning full error. So I'd advise to avoid dealing with them directly.
There is a thousands cases where your code can go wrong: cannot connect to database, IO Exception, Network error... If you deal with them one by one (like the null check here), it would be too much of a hassle.
In the code:
wsObject.getFoo().getBar().getBaz().getInt();
Even when you know which field is null, you have no idea about what goes wrong. Maybe Bar is null, but is it expected? Or is it a data error? Think about people who read your code
Like in xenteros's answer, I'd propose using custom unchecked exception. For example, in this situation: Foo can be null (valid data), but Bar and Baz should never be null (invalid data)
The code can be re-written:
void myFunction()
{
try
{
if (wsObject.getFoo() == null)
{
throw new FooNotExistException();
}
return wsObject.getFoo().getBar().getBaz().getInt();
}
catch (Exception ex)
{
log.error(ex.Message, ex); // Write log to track whatever exception happening
throw new OperationFailedException("The requested operation failed")
}
}
void Main()
{
try
{
myFunction();
}
catch(FooNotExistException)
{
// Show error: "Your foo does not exist, please check"
}
catch(OperationFailedException)
{
// Show error: "Operation failed, please contact our support"
}
}
NullPointerException is a run-time exception, so generally speaking is not recommended to catch it, but to avoid it.
You will have to catch the exception wherever you want to call the method (or it will propagate up the stack). Nevertheless, if in your case you can keep working with that result with value -1 and you are sure that it won't propagate because you are not using any of the "pieces" that may be null, then it seems right to me to catch it
Edit:
I agree with the later answer from #xenteros, it wil be better to launch your own exception instead returning -1 you can call it InvalidXMLException for instance.
Have been following this post since yesterday.
I have been commenting/voting the comments which says, catching NPE is bad. Here is why I have been doing that.
package com.todelete;
public class Test {
public static void main(String[] args) {
Address address = new Address();
address.setSomeCrap(null);
Person person = new Person();
person.setAddress(address);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
try {
System.out.println(person.getAddress().getSomeCrap().getCrap());
} catch (NullPointerException npe) {
}
}
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime) / 1000F);
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
if (person != null) {
Address address1 = person.getAddress();
if (address1 != null) {
SomeCrap someCrap2 = address1.getSomeCrap();
if (someCrap2 != null) {
System.out.println(someCrap2.getCrap());
}
}
}
}
long endTime1 = System.currentTimeMillis();
System.out.println((endTime1 - startTime1) / 1000F);
}
}
public class Person {
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
package com.todelete;
public class Address {
private SomeCrap someCrap;
public SomeCrap getSomeCrap() {
return someCrap;
}
public void setSomeCrap(SomeCrap someCrap) {
this.someCrap = someCrap;
}
}
package com.todelete;
public class SomeCrap {
private String crap;
public String getCrap() {
return crap;
}
public void setCrap(String crap) {
this.crap = crap;
}
}
Output
3.216
0.002
I see a clear winner here. Having if checks is way too less expensive than catch an exception. I have seen that Java-8 way of doing. Considering that 70% of the current applications still run on Java-7 I am adding this answer.
Bottom Line For any mission critical applications, handling NPE is costly.
If efficiency is an issue then the 'catch' option should be considered.
If 'catch' cannot be used because it would propagate (as mentioned by 'SCouto') then use local variables to avoid multiple calls to methods getFoo(), getBar() and getBaz().
It's worth considering to create your own Exception. Let's call it MyOperationFailedException. You can throw it instead returning a value. The result will be the same - you'll quit the function, but you won't return hard-coded value -1 which is Java anti-pattern. In Java we use Exceptions.
try {
return wsObject.getFoo().getBar().getBaz().getInt();
} catch (NullPointerException ignored) {
throw new MyOperationFailedException();
}
EDIT:
According to the discussion in comments let me add something to my previous thoughts. In this code there are two possibilities. One is that you accept null and the other one is, that it is an error.
If it's an error and it occurs, You can debug your code using other structures for debugging purposes when breakpoints aren't enough.
If it's acceptable, you don't care about where this null appeared. If you do, you definitely shouldn't chain those requests.
The method you have is lengthy, but very readable. If I were a new developer coming to your code base I could see what you were doing fairly quickly. Most of the other answers (including catching the exception) don't seem to be making things more readable and some are making it less readable in my opinion.
Given that you likely don't have control over the generated source and assuming you truly just need to access a few deeply nested fields here and there then I would recommend wrapping each deeply nested access with a method.
private int getFooBarBazInt() {
if (wsObject.getFoo() == null) return -1;
if (wsObject.getFoo().getBar() == null) return -1;
if (wsObject.getFoo().getBar().getBaz() == null) return -1;
return wsObject.getFoo().getBar().getBaz().getInt();
}
If you find yourself writing a lot of these methods or if you find yourself tempted to make these public static methods then I would create a separate object model, nested how you would like, with only the fields you care about, and convert from the web services object model to your object model.
When you are communicating with a remote web service it is very typical to have a "remote domain" and an "application domain" and switch between the two. The remote domain is often limited by the web protocol (for example, you can't send helper methods back and forth in a pure RESTful service and deeply nested object models are common to avoid multiple API calls) and so not ideal for direct use in your client.
For example:
public static class MyFoo {
private int barBazInt;
public MyFoo(Foo foo) {
this.barBazInt = parseBarBazInt();
}
public int getBarBazInt() {
return barBazInt;
}
private int parseFooBarBazInt(Foo foo) {
if (foo() == null) return -1;
if (foo().getBar() == null) return -1;
if (foo().getBar().getBaz() == null) return -1;
return foo().getBar().getBaz().getInt();
}
}
return wsObject.getFooBarBazInt();
by applying the the Law of Demeter,
class WsObject
{
FooObject foo;
..
Integer getFooBarBazInt()
{
if(foo != null) return foo.getBarBazInt();
else return null;
}
}
class FooObject
{
BarObject bar;
..
Integer getBarBazInt()
{
if(bar != null) return bar.getBazInt();
else return null;
}
}
class BarObject
{
BazObject baz;
..
Integer getBazInt()
{
if(baz != null) return baz.getInt();
else return null;
}
}
class BazObject
{
Integer myInt;
..
Integer getInt()
{
return myInt;
}
}
Giving answer which seems different from all others.
I recommend you to check for NULL in ifs.
Reason :
We should not leave a single chance for our program to be crashed.
NullPointer is generated by system. The behaviour of System
generated exceptions can not be predicted. You should not leave your
program in the hands of System when you already have a way of handling
it by your own. And put the Exception handling mechanism for the extra safety.!!
For making your code easy to read try this for checking the conditions :
if (wsObject.getFoo() == null || wsObject.getFoo().getBar() == null || wsObject.getFoo().getBar().getBaz() == null)
return -1;
else
return wsObject.getFoo().getBar().getBaz().getInt();
EDIT :
Here you need to store these values wsObject.getFoo(),
wsObject.getFoo().getBar(), wsObject.getFoo().getBar().getBaz() in
some variables. I am not doing it because i don't know the return
types of that functions.
Any suggestions will be appreciated..!!
I wrote a class called Snag which lets you define a path to navigate through a tree of objects. Here is an example of its use:
Snag<Car, String> ENGINE_NAME = Snag.createForAndReturn(Car.class, String.class).toGet("engine.name").andReturnNullIfMissing();
Meaning that the instance ENGINE_NAME would effectively call Car?.getEngine()?.getName() on the instance passed to it, and return null if any reference returned null:
final String name = ENGINE_NAME.get(firstCar);
It's not published on Maven but if anyone finds this useful it's here (with no warranty of course!)
It's a bit basic but it seems to do the job. Obviously it's more obsolete with more recent versions of Java and other JVM languages that support safe navigation or Optional.

Is it a good practice to return a boolean/value instead of null in case of no-ops?

This observation was made after looking at addNode code in DirectedGraph.java. The coder has used a true and a false to distinguish a no-op from an op. A similar example is the code below custom made simply to ask my question easily. Is it a recommended / good practice to return boolean to differentiate and no-op from an op to give more visibility to the client of code ?
public class FreeMain {
private List<Integer> fooList;
FreeMain ( ) { }
/**
* Lazy init - either set a value of no-op.
*
* #param barList
*/
public void putList(List<Integer> barList) {
if (this.fooList == null) {
this.fooList = barList;
}
}
/**
* Boolean returned as an indication to the user of operation status
*
* #param barList
* #return true if putLists sets the value, false is no-op.
*/
public boolean putListWithBoolean(List<Integer> barList) {
if (this.fooList == null) {
this.fooList = barList;
return true;
}
return false;
}
}
I will set it this way, is the responsibillity of the putList in this case to tell you whether the list you try to put is accepted or not by returning a boolean? In my opinion no, this is because the putList should handle only the single module of replacing the list pointer and not return something.
If you actually want to know whether the conditions are granted or not(or for any ubnormal behavior that could occur), use Exceptions. Then simply catch those exceptions into your main when the putList is used(with try-catch blocks) and do whatever you wish.
For example:
public void putList(List<Integer> barList) throws new MyListException{
if (this.fooList == null) {
this.fooList = barList;
} else {
throw new MyListException("The pointer of fooList can not be changed because the fooList is not null");
}
}
public class MyListException extends Exception {
public MyListException(String s) {
super(s);
}
}
On the other hand, the case that the method would return a true/false is when it should actually handle that module and determine whether a list will be accepted or not by testing the condition. Thus, the method name will be 'isListAccepted()' (a parameter is not needed since it doesnt play any role). However, in java it is noticed (i.e See LinkedList click here) that sometimes methods like public boolean add(E e) returns true/false. This is because those methods are implemented under the collection interface and there are some preconditions in the way the collection works. Additionally, in this case as well oracle documentation says:
public boolean add(E e) Ensures that this collection contains the specified element
(optional operation). Returns true if this collection changed as a result of the
call. (Returns false if this collection does not permit duplicates and
already contains the specified element.)
If a collection refuses to add a particular element for any reason
other than that it already contains the element, it must throw an
exception (rather than returning false).
So based on that, I believe that these operations, handle the module of telling you if your collection has changed or not after their use rather than adding the element(even if they do in some cases).
An example:
private boolean isListAccepted() {
return this.fooList == null;
}
Finally, since I am not sure too about what do you mean with "instead of null in case of no-operations", I am gonna say that: when you use the putList(..) and the condition is not granted, it doesnt return null, but rather it is doing nothing. However, it is always preferable in this case as well to use Exceptions as I already demonstrate(in the first example) so that you will know what went wrong in case you expect the putList() to actually replace the pointer. And this is because you wont always have the chance to spend time searching the code to understand what went wrong. This is not really important with the code example you provided since it is simple but what if you had a putList that was more complex and multiple things could go wrong ?
Overall, i can not say if putListWithBoolean() is a bad practice because it depends on the way it is used(as shown with the java example), while the putList() without exceptions can be considered as a bad practice, because your classes wont be that simple always, and many things could go wrong, so you better know what went wrong and where.

How to refactor to avoid passing "special values" into a Java method?

I'm sure there must be a standard way to do this, but my attempts to search Stackoverflow have failed.
I have a method like:
public void processSomeWidgetsForUser(int userItemId) {
Iterator<Widgets> iter = allWidgets.values().iterator();
while(iter.hasNext()) {
Widget thisWidget = iter.next();
if (userItemId == -1 || thisWidget.getUsersItemId() == userItemId) {
widget.process();
}
}
}
As you can see -1 is a "special value" meaning process all. Doing this saves repeating the loop code in another method called processSomeWidgetsForAllUsers.
But I dislike special values like this because they are easy to misuse or misunderstand, which is exactly the situation what I'm having to fix now (where someone thought -1 meant something else).
I can only think of two ways to improve this.
have a constant, containing -1 called something like
Widget.ALLWIDGETS which at least is self-documenting, but doesn't
stop code from using a -1 (if someone integrates old code in, for
example)
change the method to take a list of all user ids to
process, which can be empty, but that doesn't seem great
performance-wise (would need to retrieve all user ids first and then loop through
removing. Also what happens if the number of widgets in the list changes between
retreiving the ids and removing
Is there a better way? I'm sure I'm missing something obvious.
The above code has been changed slightly, so may not compile, but you should get the gist.
Although somewhat redundant, a fairly neat self-documenting approach could be to have 3 methods rather than one;
Make your original method private, and make one small change which would be to add your static final int EXECUTE_ALL = -1 and use that in your original method, then add the two new methods;
public void processWidget(int wID) throws IllegalArgumentException {
if(wID == EXECUTE_ALL) throw new IllegalArgumentException();
originalMethod(wID);
}
public void processAllWidgets() {
originalMethod(EXECUTE_ALL);
}
It makes your class a little more cluttered, but as far as the exposed methods go, it is clearer and hopefully foolproof. You could alter it not to throw an exception and just ignore any invalid ids, that just depends on your situation.
This approach of course has the major downside that it changes how the class appears to other classes, breaking everything that currently uses the, now private, originalMethod().
Number 1 would work very nicely. Be sure to document what the variable is though, so future coders (possibly yourself) know what it means.
/**This is the explanation for the below variable*/
public final static int ALL_WIDGETS = -1;
Have an external method like so:
static boolean idRepresentsAll(int id) {
return id == -1;
}
In this case, if you decide to replace it with a different mechanism, you only replace your magic number one place in your code.
At the very least, you would want to do something like this:
public static final int ID_REPRESENTING_ALL = -1;
You can change the method signature to accept a boolean for when you want to process them all.
public void processSomeWidgets(boolean doAll, int userItemId) {
Iterator<Widgets> iter = allWidgets.values().iterator();
while(iter.hasNext()) {
Widget thisWidget = iter.next();
if (doAll || thisWidget.getUsersItemId() == userItemId) {
widget.process();
}
}
}
This makes it more explicit, and easier to read in my opinion as there are no special values.

How to consolidate validity checking and exception throwing in Java?

I am implementing an interface which defines a method that can throw an exception if the parameters are not valid. What constitutes valid parameters depends on the implementing class. The interface also defines an isValid() method which can be used to check the parameters but returns a boolean rather than throwing an exception. I have found that implementing both methods will cause a lot of duplication. Consider this made up example:
public class Something implements SomeInterface {
// Other class stuff
public void doTheThing(SomeParameter sp) throws SpecificRuntimeException {
if(sp == null) throw new ParameterCannotBeNullException();
if(sp.getNonZeroInt() == 0) throw new ShouldBeNonZeroException();
if(!sp.someOtherCondition()) throw new SomeConditionNotMetException();
...
}
public boolean isValid(SomeParameter sp) {
if(sp == null) return false;
if(sp.getNonZeroInt() == 0) return false;
if(!sp.someOtherCondition()) return false;
...
return true;
}
}
The problem is the checks in both methods must be consistent, and are essentially duplicated logic. I've been trying to consolidate the checks so that both methods use the same checks but the behaviour is still retained. Some things I considered:
in doTheThing() have the line if(!isValid(sp) throw new RuntimeException();
separate the exception throwing part into a separate, private method, say checkParameter() and in isValid() do: try { checkParameter(sp); return true; } catch (SpecificRunTimeException e) { return false; }
The problem with 1. is that the specific exception is lost, and I want to provide as detailed an exception as possible. The problem with 2. is using the exception mechanism seems... wrong somehow. This part of the code may be performance sensitive, and I don't want to depend on something that's fundamentally slower than it needs to be (if I have to do it this way and profiling doesn't show a problem, fair enough... but what if is a problem?). Or has the performance hit of using exceptions this way been shown to be negligible?
What is the best way to refactor this code to use the same validity checking logic?
What if your create a isValidParam method that returns a bean like:
class ValidBean {
private boolean isValid;
private Exception exceptionOnInvalid;
public ValidBean(boolean isValid, Exception exceptionOnInvalid) {...}
// accessors
}
With the method being:
private ValidBean isValidParam(SomeParameter sp) {
if (sp == null) {
return new ValidBean(false, new ParameterCannotBeNullException());
}
if (sp.getNonZeroInt() == 0) {
return new ValidBean(false, new ShouldBeNonZeroException());
}
if (!sp.someOtherCondition()) {
return new ValidBean(false, new SomeConditionNotMetException());
}
…
return new ValidBean(true, null);
}
And then you do:
public boolean isValid(SomeParameter sp) {
return isValidParam(sp).isValid();
}
And
public void doTheThing(SomeParameter sp) throws SpecificRuntimeException {
ValidBean validbean = isValidParam(sp);
if (! validBean.isValid()) {
throw validBean.getExceptionOnInvalid();
}
...
}
I don't know if it's the best way, but a way is to have an internal method like this:
private boolean isValidInternal(SomeParameter sp, boolean throwIfInvalid)
throws SpecificRuntimeException
Then you call isValidInternal with true from the doTheThing method, and false from the public isValid method.
Edit: And then to implement isValidInternal, you have the logic for testing validity once, but either return false or throw an exception as per the throwIfInvalid flag.
This can be a murky issue; when it comes to exceptions in APIs I've never found a really clear, logical, satisfactory answer to every case.
Do you expect every user of isValid() to be using it to guard a subsequent call to doTheThing()? If so, the client code would be clearer to use the standard try/catch idiom instead, and you may not need an isValid() method at all.
(You'd still have to ponder whether the exception should be checked or unchecked; the line can be a fine one and I won't go into it here.)
And if you don't see isValid() being used this way, then just implement it with a try/catch of your own; I know it feels dirty, but it's better than the alternatives!
Your urge to "say it once and only once" is laudable. Good thinking; it'll be worth the effort.
Maybe you can create an abstract class that implements the interface and provides the default implementation for isValid().
If your object is mutable and has setters, perhaps you could move the check that throws IllegalArgumentException into each one and then call them. You'll have a more fine-grained view of what went wrong that way.
The fact that your code checks the arguments for sanity and returns runtime exceptions is a strong indication that you want to report programming error, i.e. your API is used/called in a way it should not be used/called. Since you could expect that your API is called with valid arguments, I wouldn't expect that your second solution to be problematic.
P.S.: You should not use runtime exception types in a method's throws declaration. But you should state those runtime exceptions in the method's Javadoc #throws documentation.

Categories

Resources