Overloaded constructors, final and assert
I am having some difficulties of using final variables and still have the ability to check parameters in the constructor.
For example take this class:
class MyObject {
final String id;
final String value;
public MyObject(String id, String value) {
assert id != null : "error";
assert value != null : "error";
this.id = value;
this.value = value;
}
public MyObject(Wrapper wrapper) {
assert wrapper != null : "error";
this(wrapper.getId(), wrapper.getValue());
}
The above code won't compile because the assert is not allowed before the call to the other constructor.
I cannot do the initializing of variables in a normal method, because I cannot assign to the variables at that point.
I can use a static method that created to object, but is that really a good idea?
Any suggestions?
I do not know if it is the best solution, but I use to solve it as follows.
class MyObject {
final String id;
final String value;
public MyObject(String id, String value) {
init(id, value);
}
public MyObject(Wrapper wrapper) {
assert wrapper != null : "error";
init(wrapper.getId(), wrapper.getValue());
}
private void init(String id, String value) {
this.id = value;
this.value = value;
}
}
parza at 2007-7-15 23:01:55 >

Sorry, I forgot two of the assertions.
class MyObject {
final String id;
final String value;
public MyObject(String id, String value) {
init(id, value);
}
public MyObject(Wrapper wrapper) {
assert wrapper != null : "error";
init(wrapper.getId(), wrapper.getValue());
}
private void init(String id, String value) {
assert id != null : "error";
assert value != null : "error";
this.id = value;
this.value = value;
}
}
parza at 2007-7-15 23:01:55 >

I think its time to turn in, too many mistakes :). I realize now that my solution will not work and I know of no one that does.Sorry again ...
parza at 2007-7-15 23:01:55 >

> Any suggestions?The construction process is not complete until the constructor method exits.So it doesn't matter where the actual check occurs.
public MyObject(Wrapper wrapper) {
assert wrapper != null : "error"; //<- this is not recommended
init(wrapper.getId(), wrapper.getValue());
}
Generally, assert in parameters of public methods is not recommended. Assertion is for situations that are even more exceptional than Exceptions, for example, to detect bugs in the code. Theoretically, in public methods you don磘 have to use assert to verify if the parameter is null or not null. You have to use if statement and throw NullPointerException, for example. If the method were private, like your init( ) method, so that磗 ok and you could use assertion.
> The construction process is not complete until the constructor method exits.
> So it doesn't matter where the actual check occurs.
Not sure what you mean by this, because if I set the assert on the second line like this:
public MyObject(Wrapper wrapper) {
this(wrapper.getId(), wrapper.getValue());
assert wrapper != null : "error";
}
I will get a NullPointerException.
My IDE als warns me that wrapper != null is always true (which is what I expected).
Please explain further if you can.
> Generally, assert in parameters of public methods is not recommended.
> Assertion is for situations that are even more exceptional than Exceptions,
> for example, to detect bugs in the code.
> Theoretically, in public methods you don磘 have to use assert to verify if the
> parameter is null or not null. You have to use if statement and throw
> NullPointerException,for example. If the method were private, like your
> init( ) method, so that磗 ok and you could use assertion.
It does not make sense to me why I would use asserts in private methods
and not for public ones. Especially since the same parameters might
end up in a private method anyway.
For me asserts are about pre-conditions, post-conditions and constraints.
I especially find them useful for pre-conditions and making very clear
to the caller what I expect of him.
A good article about assert can be found at javaworld
http://www.javaworld.com/javaworld/jw-12-2001/jw-1214-assert.html
Anyway, it's kinda off-topic, because if I would use an if statement
and throw an exception, I have the exact same problem!
This does not compile:
public MyObject(Wrapper wrapper) {
if (wrapper != null)
throw NullPointerException("error");
this(wrapper.getId(), wrapper.getValue());
}
> This does not compile:
> > public MyObject(Wrapper wrapper) {
>if (wrapper != null)
> throw NullPointerException("error");
>this(wrapper.getId(), wrapper.getValue());
> }
>
Sorry, but I doubt what you are saying. If it does not compile, the compile error certainly is not in:
if (wrapper != null)
throw NullPointerException("error");
The compile error is in other place certainly.
Besides, I think you are commiting an mistake. The comparison you need is (wrapper == null), not (wrapper != null), don磘 you? And one more thing, I was wrong, there is other exception, more appropriate for this kind of situation. I think what you need is this:
if (wrapper != null)
throw IllegalArgumentException("invalid parameter");
Oh, sorry. I see now where the error is. You have to use new keyword:
if (wrapper != null)
throw new IllegalArgumentException("invalid parameter");
> It does not make sense to me why I would use asserts
> in private methods
> and not for public ones. Especially since the same
> parameters might
> end up in a private method anyway.
See this:
[url]http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html[/url]
Do not use assertions for argument checking in public methods.
Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled. Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException). An assertion failure will not throw an appropriate exception.
I think the justification for that can be the idea that public methods theoretically can be used by any programmer (they are public, so they are available for everyone). So, if a programmer pass a null value as a parameter for the method, it cannot be considered a bug in the application, because it doesn磘 depend on the programmer responsible for maintain this method, it depends on the other programmers.
After some more thought there is one solution, but it is not perfect.
Id and value is not final from within the class, but from every where
else they are.
class MyObject {
private String id;
private String value;
public MyObject(String id, String value) {
init(id, value);
}
public MyObject(Wrapper wrapper) {
assert wrapper != null : "error";
init(wrapper.getId(), wrapper.getValue());
}
private void init(String id, String value) {
assert id != null : "error";
assert value != null : "error";
this.id = value;
this.value = value;
}
public final String getId() {
return id;
}
public final String getValue() {
return value;
}
}
parza at 2007-7-15 23:01:55 >

Marcelo, sorry for not being more clear.
The code below does not compile because the call to the other constructor is not on the first line.
public MyObject(Wrapper wrapper) {
if (wrapper == null)
throw new NullPointerException("error");
this(wrapper.getId(), wrapper.getValue());
}
http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.htmlI read it, but I just don't agree with it fully.Read the article I posted to understand why.Note however that using either assert or exceptions have no effect on my question.
After some more thought there is one solution, but it is not perfect.
Id and value is not final from within the class, but from every where
else they are.
class MyObject {
private String id;
private String value;
public final String getId() {
return id;
}
public final String getValue() {
return value;
}
}
This will just prevent the two methods from being overridden. It has no effect on making id and value immutable.
Ok I will post the only 'solution' I know, but I prefer a constructor.
class MyObject {
private final String id;
private final String value;
public MyObject(String id, String value) {
assert id != null : "error";
assert value != null : "error";
this.id = value;
this.value = value;
}
public static MyObject createObject(Wrapper wrapper) {
assert wrapper != null : "error";
return new MyObject(wrapper.getId(), wrapper.getValue());
}
Yes, but seen from any other class then MyObject, they are
immutable and if you make sure to use getId() and getValue()
when using id and value from within MyObject, you can not
change them by mistake. The final result will then be exactly
the same.
If it looks like a cat, sound like a cat, and behaves like
a cat, it must be cat. :)
parza at 2007-7-20 17:56:44 >

I was responding to > This will just prevent the two methods from being overridden. > It has no effect on making id and value immutable.
parza at 2007-7-20 17:56:44 >

> Yes, but seen from any other class then MyObject, they are
> immutable and if you make sure to use getId() and getValue()
> when using id and value from within MyObject, you can not
> change them by mistake. The final result will then be exactly
> the same.
That is true, but the same can be said when you make the getId() and getValue() not final.
Final variables are (just) a convenience for me as a programmer to be 100% sure I made an immutable class.
> Marcelo, sorry for not being more clear.
> The code below does not compile because the call to
> the other constructor is not on the first line.
>
> > public MyObject(Wrapper wrapper) {
>if (wrapper == null)
> throw new NullPointerException("error");
>this(wrapper.getId(), wrapper.getValue());
> }
>
You are right! I forgot this important characteristic when you call constructors! So, instead of call the constructor using this( ), continue using your init( ) method, as you was doing before.
Because even if you use assertion, the compile error you notice (not calling the constructor firts), will continue to happen, since you will continue not calling the constructor first.
> Note however that using either assert or exceptions
> have no effect on my question.
Yes, I was just trying to give you some advices.
And, indeed, using either assert or exception have no effect on your question, since assert is some kind of exception. When you are using assert, you are using exception, too! Have you already seen [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/AssertionError.html]AssertionError[/url]? So, the important question is: when use assert and when not?
These two codes below are equivalent:
assert something != null : "error";
///this line of code above has the same effect of this
if (something == null) {
throw new AssertionError("error");
}
But in the case of assert, you have the advantage of enabling or disabling assertion.
Sorry, I did not pay attention on your first question, I just saw the use of assert.
One solution for what you want could be this, if you would like to continue using assert in your public constructors:
public class MyObject {
final String id;
final String value;
public MyObject(String id, String value) {
assert id != null : "error";
assert value != null : "error";
this.id = value;
this.value = value;
}
public MyObject(Wrapper wrapper) {
assert (wrapper != null ||
wrapper.getId() != null ||
wrapper.getValue() != null) :
"error";
this.id = wrapper.getId();
this.value = wrapper.getValue();
}
}
> That is true, but the same can be said when you make the getId()
> and getValue() not final.
No, because the getId() and getValue() can be altered by extending
MyObject if they are not final. You must look on how the MyObject
is perceived from the outside.
> One solution for what you want could be this, if you would like
> to continue using assert in your public constructors:
This will force you to have redundant parameter checking.
parza at 2007-7-20 17:56:44 >

> This will force you to have redundant parameter
> checking.
Since the fields are final, I cant think in other solution. Can you think? Besides, although this "redundant parameter checking", I dont think that the solution I presented is so bad. It is good, and I would do that if I were him/her without any regret.
> public MyObject(Wrapper wrapper) {
>if (wrapper == null)
> throw new NullPointerException("error");
>this(wrapper.getId(), wrapper.getValue());
> }
>
> You are right! I forgot this important characteristic when you call
> constructors! So, instead of call the constructor using this( ), continue
> using your init( ) method, as you was doing before.
Because you cannot set the variables in another method if they are final.
> Because even if you use assertion, the compile error you notice (not calling
> the constructor firts), will continue to happen, since you will continue not
> calling the constructor first.
Yes I know, that's why I asked for help.
> Since the fields are final, I cant think in other solution.
> Can you think?
My suggestion in reply 11 gives you an equivalent behavior
under the assumption that the getId() getValue() methods are
used from within the class. It should be quite simple to uphold
this assumption.
> I dont think that the solution I presented is so bad. It is
> good, and I would do that if I were him/her without any regret.
In this simple case I agree, but if the validation is a lot
more complex, redundancy is not good.
parza at 2007-7-20 17:56:44 >

Just an ugly 'solution', but it must work...
public class MyObject {
final String id;
final String value;
public MyObject(String id, String value) {
this(getStupidObject(id, value));
}
public MyObject(Wrapper wrapper) {
this(getStupidObject(wrapper));
}
private MyObject(StupidObject so) {
this.id = so.getId();
this.value = so.getValue();
}
private static StupidObject getStupidObject(String id, String value) {
assert id != null : "error";
assert value != null : "error";
return new StupidObject(id, value);
}
private static StupidObject getStupidObject(Wrapper wrapper) {
assert wrapper != null : "error";
return getStupidObject(wrapper.getId(), wrapper.getValue());
}
}
class StupidObject {
private String id;
private String value;
public StupidObject(String id, String value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public String getValue() {
return value;
}
}
> Just an ugly 'solution', but it must work...
Cool, I did not know that it is possible to call static methods before
calling this(...). Using this, I think following is the best solution.
public class MyObject {
final String id;
final String value;
public MyObject(String id, String value) {
if (id==null || value==null) {
throw new RuntimeException("Id and value may not be null.");
}
this.id = id;
this.value = value;
}
public MyObject(Wrapper wrapper) {
this(nullFilter(wrapper).getId(), nullFilter(wrapper).getValue());
}
private static Wrapper nullFilter(Wrapper wrapper) {
if (wrapper==null) {
throw new RuntimeException
("The wrapper parameter can not be null.");
}
return wrapper;
}
}
parza at 2007-7-20 17:56:44 >

I too didn't know you could call static methods before this.I was hoping for something a bit more clean, butthe solution of parz seems acceptable.I assume you only need to call nullFilter on the first wrapper.
I think the justification for that can be the idea that public methods theoretically can be used by any programmer (they are public, so they are available for everyone). So, if a programmer pass a null value as a parameter for the method, it cannot be considered a bug in the application, because it doesnt depend on the programmer responsible for maintain this method, it depends on the other programmers.
Isn't the cart in front of the horse there? The writer of the method defines its contract. He or she a priori knows whether the method will or will not accept a null for one of its parameters. A caller of a method must honor the contract. However, the contract is defined by the person who wrote the method (or designed it). As such, when the method is written, shouldn't these types of checks (whether they are assertions or not) be performed then and there?
That having been said, I am fine with a class failing on a NPE if someone passes a null to a public method I wrote. The exception itself indicates the error. Of course, adding comments in Javadocs is advised so that callers do not find out a posteriori that null is not allowed for a given parameter.
- Saish
Saisha at 2007-7-20 17:56:44 >

@OP: I think the main difference between assertion and exception handling is about the difference between their objectives. Assertion makes sense only for programmers (or at least it should), and exception can make sense either for a programmer or a user. I mean, when you define a message in the moment of instantiation of the Exception:
//...
throw new TechnicalProblemException("Technical problems, sorry, please!");
//...
The message can be showed to a user of the system.
Well, you can do this too, if you want:
//...
assert theParam != null : "Technical problems, sorry, please!";
//...
But, would it be considered appropriate? Certainly it wouldnt.
Even this:
//...
assert theParam != null : "The param was null.";
//...
Even this example, with more technical message in the moment of the AssertionError instantiation, will not be considered a good use of assertion, if you dont use it in appropriate way, like to verify some param of some public method.
Why? Just imagine the situation. You know what this assertion means, but do the other programmers, who will use your method, know? When AssertionError occurs, the other programmers will consider you as the person responsible for the exception, because the idea about AssertionError already established in the world!
I can use your method one day, cant I? Of course yes, since It is public!!! And if the AssertionError happens, certainly I will accuse you for the bug. Not only me, but a lot of people too!
Look, the name of the exception contains ideas. What do you think when ArrayIndexOutOfBoundsException happens? Some specific ideas appear on your mind when this exception occur, dont they? And you even dont need to see the message of this exception! Can you throw ArrayIndexOutOfBoundsException when you are verifying the param of your public method, if you want? Of course you can! But would it make sense, would it be appropriate? Of course not! Thats why using assertion to verify params of public methods is not appropriate.
> @OP: I think the main difference between assertion
> and exception handling is about the difference
> between their objectives. Assertion makes sense only
> for programmers (or at least it should), and
> exception can make sense either for a programmer or a
> user.
I am not sure what you mean with 'user', but I certainly don't want to expose my users to exceptions. A NullPointerException makes no sense to them.
> I mean, when you define a message in the moment
> of instantiation of the Exception:
> >//...
> throw new TechnicalProblemException("Technical
> ical problems, sorry, please!");
>//...
>
> The message can be showed to a user of the system.
Yes, such custom exceptions can be used like that.
>
> Well, you can do this too, if you want:
> >//...
> assert theParam != null : "Technical problems,
> ems, sorry, please!";
>//...
>
> But, would it be considered appropriate? Certainly it
> wouldnt.
Yes, because assertions are not meant to be seen by the user. It is a bug if they ever happen.
> Even this:
> >//...
>assert theParam != null : "The param was null.";
>//...
>
> Even this example, with more technical message in the
> moment of the AssertionError instantiation, will not
> be considered a good use of assertion, if you dont
> use it in appropriate way, like to verify some param
> of some public method.
Uhmm but it is used to verify some param of some public method.
> Why? Just imagine the situation. You know what this
> assertion means, but do the other programmers, who
> will use your method, know?
Yes, because it means they break the pre-conditions of calling the method with the benefit that they get the error at the moment the break the condition, and not much later with a vague exception, which might happen in some private method. Plus they see exactly what rule they are breaking.
> When AssertionError
> occurs, the other programmers will consider you as
> the person responsible for the exception, because
> the idea about AssertionError already established
> in the world!
If they will get some vague exception later and they don't understand why, they will be annoyed much more.
I care about good design. Not what "the world" might expect.
> I can use your method one day, cant I? Of course
> yes, since It is public!!! And if the AssertionError
> happens, certainly I will accuse you for the bug. Not
> only me, but a lot of people too!
Weird for you to accuse someone when you can immediately see that you broke the pre-conditions.
> Look, the name of the exception contains ideas. What
> do you think when ArrayIndexOutOfBoundsException
> happens? Some specific ideas appear on your mind when
> this exception occur, dont they?
Yes, but the cause of it is not always that clear.
> And you even dont
> need to see the message of this exception!
> Can you
> throw ArrayIndexOutOfBoundsException when you are
> verifying the param of your public method, if you
> want? Of course you can! But would it make sense,
> would it be appropriate? Of course not!
In other words you don't want to verify parameters?
> Thats why
> using assertion to verify params of public methods is
> not appropriate.
Even just for myself it helped a great deal.
> That having been said, I am fine with a class failing
> on a NPE if someone passes a null to a public method
> I wrote. The exception itself indicates the error.
> Of course, adding comments in Javadocs is advised so
> o that callers do not find out a posteriori that null
> is not allowed for a given parameter.
>
> - Saish
I'm fine with a NPE too. However the problem with this is that the exception can occur much later. For example when another method is called on the object. Or it is triggered by some event. At that point the method fails, you get some exception and have to find the real cause. Would you not like the error at the moment you broke the design by contract rules?
I want my errors as fast a possible so I can fix them more easily.
It seems to me like we have to have quite a few unlucky coincidences happening at the same time for a genuine problem to arise:
If the fields in the original example weren't final the problem could be fixed by moving the initialization to a separate method.
The example gets an NPE anyway which I'd consider is a perfectly reasonable diagnostic. We could construct another example where the error occurs so deep in a chain of construction that it becomes difficult to figure out.
Let's pretend we wrote that different example. In some (many? most?) cases the inner constructor would check parameters, or get a "side effect" NPE, giving a reasonable enough error message.
We can in some (many? most?) situations move the parameter check after the this() call. Assuming there are no side effects in the inner constructor and it doesn't crash in hard-to-figure-out ways.
In the original example we could simply duplicate the two assignments. Won't be nice if the constructor needs to do complicated stuff. Unless we can factor out the complicated stuff into a method, leaving just the final field assignments duplicated.
The constructors need to be very complicated. If they are relatively simple then an NPE or something will be easy enough to figure out even if we can't have a parameter check in the very earliest possible place. Unless the users of our code are large crowds of unusually newbie programmers who pass lots of bad parameters all the time and can't figure out the error.
> I am not sure what you mean with 'user', but I
> certainly don't want to expose my users to
> exceptions. A NullPointerException makes no sense to
> them.
"Users" can be the programmers who will use your public method, so in this case, NullPointerException makes sense for them.
"Users" can be "normal" people, I mean, people who are not from Computing area. NullPointerException makes no sense for this kind of people. Actually, there isnt any exception that makes sense for them, even customized exceptions. For "normal" people, the only thing that can make sense for them is a message.
> > Why? Just imagine the situation. You know what
> this
> > assertion means, but do the other programmers, who
> > will use your method, know?
>
> Yes, because it means they break the pre-conditions
> of calling the method with the benefit that they get
> the error at the moment the break the condition, and
> not much later with a vague exception, which might
> happen in some private method. Plus they see exactly
> what rule they are breaking.
Maybe only for you. Imagine that I developed some method, like this:
public void verifyAccount(String account) {
assert account != null :
"The account param was null. It is a very serious bug," +
"and shouldnt never had happened.";
//etc...
}
And I make this public method available to you use it. Now imagine that, unfortunatelly, you pass a null value as a param for this method. And what would you think when this AssertionError will be thrown? Well, according to your thoughts, it would make sense for you, and you would react normally.
But, if I were in your place, I would think that some very, very, and very serious problem occurred, and this very serious problem occurred inside this method, and this problem is not related with any code I wrote. In other words, the only person who has to explain why this AssertionError occurred is the person who developed that public method. I dont need to explain nothing to anyone, because this is the idea that AssertionError exception contains.
> > When AssertionError
> > occurs, the other programmers will consider you as
> > the person responsible for the exception, because
> > the idea about AssertionError already
> established
> > in the world!
>
> If they will get some vague exception later and they
> don't understand why, they will be annoyed much
> more.
> I care about good design. Not what "the world" might
> expect.
Hmmm...so, why dont you do something like this?
public void verifyAccount(String account) {
if (account == null)
throw new IllegalArgumentException("account param was null.");
//etc...
}
IllegalArgumentException is for this usual kind of situations, and this exception is known by a lot of programmers. In my opinion, it would be perfect if you use IllegalArgumentException.
> > I can use your method one day, cant I? Of course
> > yes, since It is public!!! And if the
> AssertionError
> > happens, certainly I will accuse you for the bug.
> Not
> > only me, but a lot of people too!
>
> Weird for you to accuse someone when you can
> immediately see that you broke the pre-conditions.
Ok, Im joking a little, I will not accuse you or anyone because of the problem, but the first thing I would think is that something very bad and undesirable occurred. Because it is the idea of AssertionError, right? I would just say to my boss that AssertionError occurred, and Im not able to do nothing about it, in order to solve the problem. Although I can disable assertion verification, in order to not bother with that. But would you like if someone makes assertions as disabled when he/she run your code? How would you force people to always enable assertions?
> > Can you
> > throw ArrayIndexOutOfBoundsException when you are
> > verifying the param of your public method, if you
> > want? Of course you can! But would it make sense,
> > would it be appropriate? Of course not!
>
> In other words you don't want to verify parameters?
No, actually I verify params very often, but not in the way you do. In my phrase above what I mean is exactly thi code below:
public void theMethod(String param) {
//Can you do this?
//Of course you can, since the compile
//doesnt complain nothing.
//But obviously, this is not appropriate.
if (param == null)
throw new ArrayIndexOutOfBoundsException("The param was null.");
}
Suppose that for some reason, this code above makes sense for me. But, would it make sense for any programmer? Just notice the situation where I am using ArrayIndexOutOfBoundsException.
Of course, I am exagerating. But I am exageration just to try to make you understand that your use of assertion is not appropriate.
> Even just for myself it helped a great deal.
Ok!!! If this program is only for you, so no problem in using the assertion in the way you are doing, because it makes sense for you, But, just some more advices:
- if you decide to make your application available to the "normal people", and if you will be the only person who will maintain this application, then OK, you can continue to use the assertion in any way you desire. But, if other programmers maintain your app, certainly they will not consider your code so good.
- if you decide to make your app available only to programmers, I mean, the programmers will be able to use your public methods, so certainly they will have bad and negative opinions about the use of assertion in your app.
- Although these two advices above, I insist in advicing you to not use assertion assertion in the way you do.
Sorry for my bad English. Please, tell me if you can compreehend what I wrote.
There is a good pdf that explains assertion. Have you already read this?
[url]> http://java.sun.com/developer/Books/javaprogramming/jdk14/javapch06.PDF[/url]
This is just a repeat of what you told before.
It does not address the points in the article that I gave before.
Using 'normal' exceptions means that it will have a performance impact on the production environment. Which will make the programmer to not check the pre-condition at all.
Even without checking for parameter pre-conditions the exception will occur anyway (for example a NullPointerException).
Using assert in private methods to check parameters will automatically force you to check the parameters passed to the public method which will make the assert redundant in that case.
Therefore I will keep using it. Never had any complaints about it from other people anyway.
First, the check makes no sense. Why are you asserting on something guaranteed to throw a Null Pointer Exception? Dare I say you are asserting to prevent the NullPointerException? What does this gain you?
Nothing. Remember, assertions are for developers not end users. And as such any developer will have no more info from an assert than from an NPE.
Since the Recommended thing to do in this case is throw an NPE anyway, I think you should leave MyObject(Wrapper wrapper) constructor alone, and instead throw NPE also in the MyObject(String id, String value) constructor! This is how I handle it in my public and publicly useable classes.
Now if its more complicated than an NPE, then I think you go with the factory method that checks the preconditions before it instantiates the object. And you make the constructor private.
Mostly I use asserts for doing calculations. I dont use them for simple not null checks, unless for instance its a variable that wont be used right away.
Its fundamentally pointless to hide an NPE with an assertion.
> Its fundamentally pointless to hide an NPE with an
> assertion.
I guess the fundamental difference is to make a distinction between an error that the caller should/could try to catch and recover from, and something that the application must fail on and then prevent it from ever happening again.
That's what pre-conditions are for.
I do not feel comfortable to use such things as NullPointerExceptions to signal that a pre-condition has failed.
> A good article about assert can be found at javaworld
> http://www.javaworld.com/javaworld/jw-12-2001/jw-1214-assert.html
Yes it is a good article but you seem to have fixed on the mechanics of it and not the philosphical why.
The purpose of assert and a design by contract approach is the early detection of programming errors, not the detection of application user errors.
I think if you reread the sections Be assertive and Assert this you will find it highly consistent with what Marcelo9 & _dnoyeB have said.
The orginal code as presented also has an apparent cyclic dependency. The MyObject class is dependent its Wrapper. You should fix this by refering back to the first principle. What is the responsibility of MyObject. What is the responsibility of Wrapper.
I incidentically read this thread. I was figured out many new and interesiting stuff.
I have been read all refferences posted it this thread, and, IMHO, it is not appropriate to use assert in public method. It is about those reason:
- "Backward compatibility" - prior 1.4 runtme exception was thrown. Also no javadoc support.
- Unchecked exception caller shouldn't catch. If such exception is occured programm should crash.
- Asserting (throwing AssertionError) also is not catched and leads to programm crash. But is much less informative (see example with IndexOutOfBounds) and can be tuned off, that is awfull.