Avoid null checks? - java

I wonder if it would be possible to 'avoid' null checks in Java, take an example from this code:
#Override
public List<AccountBean> search(AccountConstraint... c) {
if (c.length == 0) {
throw new IllegalArgumentException("dao.AccountDAO.search: c.length == 0");
}
try {
List<AccountBean> beans = new ArrayList<>();
for (AccountConstraint ac : c) {
Builder builder = new QueryBuilder.Builder("SELECT * FROM accounts");
if (ac.getAccountId() != null) {
builder.clause("accountId >= " + ac.getAccountId().getMin() + " AND accountId <= " + ac.getAccountId().getMax());
}
if (ac.getUsername() != null) {
builder.clause("username = \"" + ac.getUsername() + "\"");
}
if (ac.getPassword() != null) {
builder.clause("password = \"" + ac.getPassword() + "\"");
}
if (ac.getEmail() != null) {
builder.clause("email = \"" + ac.getEmail() + "\"");
}
PreparedStatement ps = connection.prepareStatement(builder.build().getQuery());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
beans.add(new AccountBean(rs));
}
}
return beans;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
It has to check 4 times for the != null because else the code would fail.
Is it possible to turn the if (object != null) statements into one-liners that only execute if there is no NullPointerException? When there is an exception, the line should just be ignored.
I am not talking about a general language feature here, I am talking about a feature that would only be turned in when you explicitely decide to do so.
For example: NullCheck(builder.clause("username = \"" + ac.getUsername() + "\"")); would be a snippet of the suggested code.
Is something like that possible in Java?
Also if it is not possible, might it be possible in Java 8 to use methods (voids) directly in methods?
So then code like this could actually work?
public static NullCheck(Void void) {
try {
void.execute();
}
catch (NullPointerException e) {
//ignore
}
}
I know I could put the method inside it's own class that extends an interface that has method execute() and then pass that class around, but that would defeat the purpose of getting rid of the null checks or anything that would be even more complicated.
Regards.
WARNING: The way I used PreparedStatement here is prone to SQL Injection. Do not reuse this code.

You can avoid these checks by assuming that these methods do not return null values.
How can you assume this? By having the specification for the AccountConstraint say so. The code in AccountConstraint is then responsible for ensuring the values are not null, rather than your search method being responsible for handling null values. You might have to change the design of AccountConstraint to do this.
And what happens if your assumption is wrong? That is, if AccountConstraint is buggy. An exception will be thrown, which you were not expecting. But that is what can happen when you have a bug: an unexpected exception is thrown. Debugging the code will be easy, because the stacktrace will show you which method of AccountConstraint is returning an invalid null value.

Yes and No.
There are two approaches to tackle the null problem:
Special Operators like the Safe Navigation Operator in Groovy. If x.y throws a NullPointerException x?.yreturns just null. Since Java does not allow creation of new operators, you can't do this in Java. Operators like this where considered for JDK8 but where dropped. If you want have something like this, switch to Groovy or one of the many other languages having this feature.
Special Class many languages have a special interface for representing a value that might be null. In Scala it is called Option. Option has two implementations: None + Some. None replaces null. Whenever you want to do something with the value, you don't use it directly, but you call map on the Option with a function as an argument. If it is actually a None, nothing happens, you just get back None. If it is a Some, the function gets executed on the value and you get an Option with the result. That way you can work with Options all the time, without worrying about nulls.
Actually it is in now way special, so you can create such a class yourself with Java. The problem is only, that Java doesn't have functions, so you have to use anonymous classes. This makes the whole thing really cumbersome and only a theoretical option.
JDK8 has a Option class. As far as I know it is missing the map method which makes the whole thing a bad joke in my opinion. But since the most important tool (anonymous functions) are there will be a proper Option implementation provided by one of the usual suspects (Google, Apache ...)

As it stands, you could probably write a method like
public void clauseIfNotNull(Builder builder, String format, Object o) {
if (o != null) {
builder.clause(String.format(format, o));
}
}
and then that'd look like clauseIfNotNull(builder, "username = \"%s\"", ac.getUsername());
Other than that, there's not much you can do with Java 7.

Make a minimal adaptor object on the Builder
class NotNullClauseAdapter
{
private final Builder builder;
public NotNullClauseAdapter(Builder builder) {
this.builder = builder;
}
public void clause(String format, Object o) {
if (o != null) {
builder.clause(String.format(format, o));
}
}
}
Use this in your code:
for (AccountConstraint ac : c) {
Builder builder = new QueryBuilder.Builder("SELECT * FROM accounts");
NotNullClauseAdapter adapter = new NotNullClauseAdapter(builder);
if (ac.getAccountId() != null) {
builder.clause("accountId >= " + ac.getAccountId().getMin() + " AND accountId <= " + ac.getAccountId().getMax());
}
adapter.clause("username = \"%s\"", ac.getUserName());
adapter.clause("password = \"%s\"", ac.getPassword));
adapter.clause("email = \"%s\"", ac.getEmail());
PreparedStatement ps = connection.prepareStatement(builder.build().getQuery());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
beans.add(new AccountBean(rs));
}
}
You can expand by adding further clause-methods to the adapter to handle specific objects like ranges in order to convert things like the accountId as well, e.g.
public void clauseMinMax(String format, Range r) {
if (r != null) {
builder.clause(String.format(format, r.getMin(), r.getMax()));
}
}
The accountId row then becomes (if getAccountId() returns a Range object):
adapter.clauseMinMax("accountId >= %d AND accountId <= %d", ac.getAccountId());

Use JSR305 and use the appropriate #Nonnull annotations and you don't have to do null checks, the annotations do them for you.
The use of #Nonnull and #CheckReturnValue annotations from JSR305 help to express the needs for null and return value checks. It is a good practice that the developer describes the expected behavior of the implementation for the later use and the static code analysis.

Related

Better condition in java for conditional code [duplicate]

I used spring boot to develop a shell project used to send email, e.g.
sendmail -from foo#bar.com -password foobar -subject "hello world" -to aaa#bbb.com
If the from and password arguments are missing, I use a default sender and password, e.g. noreply#bar.com and 123456.
So if the user passes the from argument they must also pass the password argument and vice versa. That is to say, either both are non-null, or both are null.
How do I check this elegantly?
Now my way is
if ((from != null && password == null) || (from == null && password != null)) {
throw new RuntimeException("from and password either both exist or both not exist");
}
There is a way using the ^ (XOR) operator:
if (from == null ^ password == null) {
// Use RuntimeException if you need to
throw new IllegalArgumentException("message");
}
The if condition will be true if only one variable is null.
But I think usually it's better to use two if conditions with different exception messages. You can't define what went wrong using a single condition.
if ((from == null) && (password != null)) {
throw new IllegalArgumentException("If from is null, password must be null");
}
if ((from != null) && (password == null)) {
throw new IllegalArgumentException("If from is not null, password must not be null");
}
It is more readable and is much easier to understand, and it only takes a little extra typing.
Well, it sounds like you're trying to check whether the "nullity" condition of the two is the same or not. You could use:
if ((from == null) != (password == null))
{
...
}
Or make it more explicit with helper variables:
boolean gotFrom = from != null;
boolean gotPassword = password != null;
if (gotFrom != gotPassword)
{
...
}
Personally, I prefer readable to elegant.
if (from != null && password == null) {
throw new RuntimeException("-from given without -password");
}
if (from == null && password != null) {
throw new RuntimeException("-password given without -from");
}
Put that functionality in a 2 argument method with the signature:
void assertBothNullOrBothNotNull(Object a, Object b) throws RuntimeException
This saves space in the actual method you are interested in and makes it more readable. There is nothing wrong with slightly verbose method names and there is nothing wrong with very short methods.
A Java 8 solution would be to use Objects.isNull(Object), assuming a static import:
if (isNull(from) != isNull(password)) {
throw ...;
}
For Java < 8 (or if you don't like using Objects.isNull()), you can easily write your own isNull() method.
Here is a general solution for any number of null checks
public static int nulls(Object... objs)
{
int n = 0;
for(Object obj : objs) if(obj == null) n++;
return n;
}
public static void main (String[] args) throws java.lang.Exception
{
String a = null;
String b = "";
String c = "Test";
System.out.println (" "+nulls(a,b,c));
}
Uses
// equivalent to (a==null & !(b==null|c==null) | .. | c==null & !(a==null|b==null))
if (nulls(a,b,c) == 1) { .. }
// equivalent to (a==null | b==null | c==null)
if (nulls(a,b,c) >= 1) { .. }
// equivalent to (a!=null | b!=null | c!=null)
if (nulls(a,b,c) < 3) { .. }
// equivalent to (a==null & b==null & c==null)
if (nulls(a,b,c) == 3) { .. }
// equivalent to (a!=null & b!=null & c!=null)
if (nulls(a,b,c) == 0) { .. }
Since you want to do something special (use defaults) when both sender and password are absent, handle that first.
After that, you should have both a sender and a password to send an e-mail; throw an exception if either is missing.
// use defaults if neither is provided
if ((from == null) && (password == null)) {
from = DEFAULT_SENDER;
password = DEFAULT_PASSWORD;
}
// we should have a sender and a password now
if (from == null) {
throw new MissingSenderException();
}
if (password == null) {
throw new MissingPasswordException();
}
An added benefit is that, should either of your defaults be null, that will be detected as well.
Having said that, in general I think that use of XOR should be permissible when that is the operator you need. It is a part of the language, not just some trick that works because of an arcane compiler-bug.
I once had a cow-orker who found the ternary operator too confusing to use...
I would like to suggest another alternative which is how I would actually write this piece of code:
if( from != null )
{
if( password == null )
error( "password required for " + from );
}
else
{
if( password != null )
warn( "the given password will not be used" );
}
To me this seems to be the most natural way to express this condition which makes it easy to understand for somebody who might have to read it in the future. It also allows you to give more helpful diagnostic messages and treat the unnecessary password as less serious and it makes it easy to modify which is rather likely for such a condition. I.e. you may find out that giving a password as a command line argument is not the best idea and may want allow reading the password from standard input optionally if the argument is missing. Or you may want to silently ignore the superfluous password argument. Changes like these would not require you to rewrite the whole thing.
Besides that it executes only the minimum number of comparisons, so it's not more expensive than the more "elegant" alternatives. Although performance is very unlikely a problem here because starting a new process is already much more expensive than a extra null check.
I think a correct way to handle this is to consider three situations: both 'from' and 'password' are provided, neither are provided, a mix of the two are provided.
if(from != null && password != null){
//use the provided values
} else if(from == null && password == null){
//both values are null use the default values
} else{
//throw an exception because the input is not correct.
}
It sounds like the original question wants to break the flow if it is incorrect input, but then they will have to repeat some of the logic later. Perhaps a good throw statement might be:
throw new IllegalArgumentException("form of " + form +
" cannot be used with a "
+ (password==null?"null":"not null") +
" password. Either provide a value for both, or no value for both"
);
Here's a relatively straight-forward way that does not involve any Xor og lengthy ifs. It does however require you to be slightly more verbose, but on the upside, you can use the custom Exceptions I suggested to get a more meaningful error message.
private void validatePasswordExists(Parameters params) {
if (!params.hasKey("password")){
throw new PasswordMissingException("Password missing");
}
}
private void validateFromExists(Parameters params) {
if (!params.hasKey("from")){
throw new FromEmailMissingException("From-email missing");
}
}
private void validateParams(Parameters params) {
if (params.hasKey("from") || params.hasKey("password")){
validateFromExists(params);
validatePasswordExists(params);
}
}
Nobody seems to have mentioned the ternary operator:
if (a==null? b!=null:b==null)
Works nicely for checking this particular condition, but doesn't generalize well past two variables.
As I see your intentions, there is no need to always check both exclusive nullities but to check if password is null if and only if from is not null. You can ignore the given password argument and use your own default if from is null.
Written in pseudo must be like this:
if (from == null) { // form is null, ignore given password here
// use your own defaults
} else if (password == null) { // form is given but password is not
// throw exception
} else { // both arguments are given
// use given arguments
}
I'm surprised nobody mentioned the simple solution of making from and password fields of a class and passing a reference to an instance of that class:
class Account {
final String name, password;
Account(String name, String password) {
this.name = Objects.requireNonNull(name, "name");
this.password = Objects.requireNonNull(password, "password");
}
}
// the code that requires an account
Account from;
// do stuff
Here from could be null or non-null and if it's non-null, both its fields have non-null values.
One advantage of this approach is that the error of making one field but not the other field null gets triggered where the account is initially obtained, not when the code using the account runs. By the time the code using the account is executed, it's impossible for the data to be invalid.
Another advantage to this approach is more readable as it provides more semantic information. Also, it's likely that you require the name and password together in other places so the cost of defining an additional class amortizes over multiple usages.
if ((from == null) == (password == null)){ //if both are true or both are false
}
(Source: Intellij IDEA)

How to perfectly catch the Java NullPointerException in o = objectA.objectB.objectC operation?

Not like C or C++, o = objectA.objectB.objectC will throw a NullPointerException if either object(A, B) is null in Java. In Java 1.7, I can't do anything like lambda expression to run this command with try-catch protection.
So, how will you perfectly cache the exception there?
Sadly there is no sort of "propagate null" operator in Java, although it was talked about some while ago. (The notation o = objectA?.objectB?.objectC was mooted).
In your case you need to check each part in turn:
if (objectA == null){
o = null;
} else {
/*OType*/ p = objectA.objectB;
o = p == null ? null : p.objectC;
}
Using purely the ternary conditional operator is also a possibility, but that means you need to write objectA.objectB in more than one place.
Enclosing the expression around a try catch block seems crude to me as it could smother legitimate NullPointerExceptions if the chain comprises functions (although that is a moot point for direct field access). But it is easy to read, and scales better for long chains:
try {
o = objectA.objectB.objectC;
} catch (final java.lang.NullPointerException e){
o = null;
}
how will you perfectly cache[catch?] the exception there?
I hope you mean avoid the null exception; not catching it.
You can write a utility that somewhat makes the check easier; i.e. a static utility method that takes variables arguments (array in diguise) and check if all are not null or not.
Example
public static boolean allNotNull(Object... objects) {
for (Object o : objects) {
if (o == null) {
return false;
}
}
return true;
}
if(allNotNull(objectA, objectB, objectC))
Here's a one-line version after which o will either be null or the value of objectA.objectB.objectC:
Object o = (objectA != null && objectA.objectB != null) ? objectA.objectB.objectC : null;
I would also recommend against using try/catch here

Check if returned value is not null and if so assign it, in one line, with one method call

Java is littered with statements like:
if(cage.getChicken() != null) {
dinner = cage.getChicken();
} else {
dinner = getFreeRangeChicken();
}
Which takes two calls to getChicken() before the returned object can be assigned to dinner.
This could also be written in one line like so:
dinner = cage.getChicken() != null? cage.getChicken() : getFreeRangeChicken();
But alas there are still two calls to getChicken().
Of course we could assign a local variable then use the ternary operator again to assign it if it is not null, but this is two lines and not so pretty:
FutureMeal chicken = cage.getChicken();
dinner = chicken != null? chicken : getFreeRangeChicken();
So is there any way to say:
Variable var = some value if some value is not null OR some other
value;
And I guess I'm just talking syntax here, after the code is compiled it probably doesn't make much difference how the code was written in a performance sense.
As this is such common code it'd be great to have a one-liner to write it.
Do any other languages have this feature?
Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.
dinner = Optional.ofNullable(cage.getChicken())
.orElse(getFreerangeChicken());
Note: This usage of Optional is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
You can use the result variable as your temporary, like this:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
Since Java 9 you have Objects#requireNonNullElse which does:
public static <T> T requireNonNullElse(T obj, T defaultObj) {
return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}
Your code would be
dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());
Which is 1 line and calls getChicken() only once, so both requirements are satisfied.
Note that the second argument cannot be null as well; this method forces non-nullness of the returned value.
Consider also the alternative Objects#requireNonNullElseGet:
public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
which does not even evaluate the second argument if the first is not null, but does have the overhead of creating a Supplier.
If you don't mind to use commons-lang you can use org.apache.commons.lang3.ObjectUtils#defaultIfNull
Your code would be:
dinner = ObjectUtils.defaultIfNull(cage.getChicken(),getFreeRangeChicken())
Using Java 1.8 you can use Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken to return either Optional.empty() instead of null, or Optional.of(myReturnObject), where myReturnObject is your chicken.
Then you can call getChicken() and if it would return Optional.empty() the orElse(fallback) would give you whatever the fallback would be, in your case the second method.
Use your own
public static <T> T defaultWhenNull(#Nullable T object, #NonNull T def) {
return (object == null) ? def : object;
}
Example:
defaultWhenNull(getNullableString(), "");
Advantages
Works if you don't develop in Java8
Works for android development with support for pre API 24 devices
Doesn't need an external library
Disadvantages
Always evaluates the default value (as oposed to cond ? nonNull() : notEvaluated())
This could be circumvented by passing a Callable instead of a default value, but making it somewhat more complicated and less dynamic (e.g. if performance is an issue).
By the way, you encounter the same disadvantage when using Optional.orElse() ;-)
You could use
Objects.requireNonNullElse(cage.getChicken(), getFreerangeChicken())
even nicer with static import:
import static java.util.Objects.requireNonNullElse;
requireNonNullElse(cage.getChicken(), getFreerangeChicken())
dinner = cage.getChicken();
if(dinner == null) dinner = getFreeRangeChicken();
or
if( (dinner = cage.getChicken() ) == null) dinner = getFreeRangeChicken();
Alternatively in Java8 you can use Nullable or NotNull Annotations according to your need.
public class TestingNullable {
#Nullable
public Color nullableMethod(){
//some code here
return color;
}
public void usingNullableMethod(){
// some code
Color color = nullableMethod();
// Introducing assurance of not-null resolves the problem
if (color != null) {
color.toString();
}
}
}
public class TestingNullable {
public void foo(#NotNull Object param){
//some code here
}
...
public void callingNotNullMethod() {
//some code here
// the parameter value according to the explicit contract
// cannot be null
foo(null);
}
}
http://mindprod.com/jgloss/atnullable.html

calling function should return default value, if object (or any function result) is null

Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}

NullPointerExceprion at recursive method

I have this recursive method:
public Hund getMor(int id) {
Hund barn = getHund(id);
int idMor = barn.getId_mor();
Hund mor = getHund(idMor);
return mor;
}
public String getMorTre(int id) {
if (id == 0) {
return null;
}
if (!existHund(id)) {
return "Hunden du søkte etter finnes ikke";
} else {
if (id == 0) {
return null;
} else {
Hund mor = getMor(id);
MinRamme.jta.append(mor.toString() + "\n");
int morId = mor.getId();
return getMorTre(morId);
}
}
}
I have tried to remove the nullpointer by returning null if the id is 0 but this does not work. Does anyone have a solution?
NPE:
Exception in thread "AWT-EventQueue -0" java.lang.nullpointerexception
at Arkiv.getMorTre(Arkiv.java:209)
at Arkiv.getMorTre(Arkiv.java:211)
at Arkiv.getMorTre(Arkiv.java:211)
at MinRamme$4.actionPerformed(MinRamme.java:89) <37 internal calls>
Where does the NullPointerException occur? That would help... That being said:
Inside your else clause, your
if (id==0) {
is useless, since you're testing that at the beginning and the id isn't changed.
I think you need to check if
getMother(id)
returns null, that is probably where you're getting the NullPointer... but you could confirm that now, couldn't you?
It is likely (but difficult to confirm until you let us know what line is throwing the NPE) that the line that generates the NPE is
MyFrame.jta.append(mother.toString() + "\n");
because mother is null. You could change your code into this:
Dog mother = getMother(id);
if (mother == null) {
//do something
}
There really isn't enough information here. What line are you getting the null pointer on?
if, as I suspect, it's here:
MyFrame.jta.append(mother.toString() + "\n");
Then you need to determine, through debugging, that it's definitely mother that is null. If you have done that, then you can be absolutely positive that your getMother(id); returns null, for the id that you are passing in.
If I were you I would create a unit test for the getMother(id) method and pass in the id that is causing the failure.
If you don't know what id value is causing the problem, then at the very least stick in some System.out.print() statement to find out what is going on. Although, you'd be better using some logging framework, such as log4j.
Hope this helps.
Its because your exception is at mother.toString() method..
try this
try
{
MyFrame.jta.append(mother.toString() + "\n");
}catch(NullPointerException ignore){}

Categories