This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How can I stop the object to be created Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How can I stop the object to be created" Watch "How can I stop the object to be created" New topic
Author

How can I stop the object to be created

Lio Liov
Ranch Hand

Joined: Mar 21, 2012
Posts: 33
Hi.
How can I stop an object from creation
Lets say that I have object person with age and name
Is there any way to stop.So far If the object was over 99 I assigned 0 to the age .
Thanks
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Throw an exception from the constructor if bad data is passed in. IllegalArgumentException is usually the right choice for that.

But there are people and things over 100 years old in this world. Why do you not want to allow age > 99?
Lio Liov
Ranch Hand

Joined: Mar 21, 2012
Posts: 33
Thanks,I am just practicing ,it is not a real application
Whay the exeption is not printing out
Ernesto Arroyo
Greenhorn

Joined: Mar 06, 2011
Posts: 11

Although using the constructor is valid, this other solution is better because we can return null:

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60810
    
  65

Ernesto Arroyo wrote:Although using the constructor is valid, this other solution is better because we can return null


While using a Factory pattern is another viable way to do this, saying it is always "better" is specious. Both are viable approaches and each could be more appropriate depending upon circumstances.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Ernesto Arroyo wrote:Although using the constructor is valid, this other solution is better because we can return null:


In general, I don't think being able to return null makes it better. If I'm asking for an object, I expect to get that object. If there's a problem, I want to be made aware of it by an exception, so I can deal with it outside of my happy-path code. I don't want to have to check for null.

And in this particular case, it's almost certainly wrong to return null. If we're passing an age > 99, then we've violated a precondition of creating one of these objects, which is a bug, and which therefore should result in an unchecked exception.
Ernesto Arroyo
Greenhorn

Joined: Mar 06, 2011
Posts: 11

Well, you are right, my idea is not always better, but the question was: "How can I stop an object from creation",... anyway we can have this through exceptions.

Exceptions are a "controversial" yet, Runtime, checked,..... and using this pattern was one of my favorite options since I read it (maybe Mr.Fowler, I'm not sure)

Anyway both options could be appropiate, depending of circumstances.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Ernesto Arroyo wrote:
Anyway both options could be appropiate, depending of circumstances.


Can you explain why you think it would be more appropriate to return null than to throw an exception when we ask for an object to be created and pass an invalid parameter?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60810
    
  65

I can think of numerous occasions where I have used the Factory pattern rather than rely upon an exception. I would use an exception if the condition is indeed exceptional, but use a Factory if failure was something that could be expected and then an alternate approach taken.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Bear Bibeault wrote:I can think of numerous occasions where I have used the Factory pattern rather than rely upon an exception.


I don't think that's an either or, unless you're talking about returning null from a factory.

I would use an exception if the condition is indeed exceptional, but use a Factory if failure was something that could be expected and then an alternate approach taken.


Yes, I agree, for things like, e.g., trying to create a logger, and for some reason you can't create the one you want so you fall back on a default. My question is specifically:

1) When/why would you allow a factory to return null in general?

2) Why in this specific case (or in the general case of invalid args) would it be good for a factory to return null when the caller passed in bad data?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60810
    
  65

Again, if it's an exceptional condition that needs the stack to unwind, I'd throw an exception. If I just wanted to continue processing in the same method, I'd use a Factory that returns null on failure. An if statement is a lot clearer than a try-catch block that simply catches the exception and continues on its merry way.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Bear Bibeault wrote:Again, if it's an exceptional condition that needs the stack to unwind, I'd throw an exception.


I'd certainly consider the caller passing me a param that violates a precondition to be an exceptional condition.

If I just wanted to continue processing in the same method, I'd use a Factory that returns null on failure. An if statement is a lot clearer than a try-catch block that simply catches the exception and continues on its merry way.


True, but an if statement is less clear than a proper try catch block that properly handles the exception, and is less clear than simply letting the unchecked exception bubble up to the caller. Not having to check return values to know if a call succeeded is pretty much the driving force behind the existence of exceptions, after all. (And I'm sure you know this, so I expect that we just have two very different mental pictures of what the underlying assumptions are that define the context we're talking about.)
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60810
    
  65

Jeff Verdegan wrote:I'd certainly consider the caller passing me a param that violates a precondition to be an exceptional condition.

In this case perhaps. But it's just a toy program so there's really nothing to say about it.

In other cases, not so much. Business logic could dictate that when a failure occurs, a reasonable default alternate is to be used. Also, at least in web apps, validation errors are rarely handled by exceptions.

My point is that I'm not saying that one way or the other is better. I'm saying that it depends upon the circumstances.

True, but an if statement is less clear

I disagree with the absoluteness of this statement. Where the logic is representing a conditional, an if statement is usually more clear. And I say usually, because there might be rare circumstances where it is not.

Remember, I'm not talking about cases where the stack needs to be unwound. I'm talking about cases where upon failure, processing should continue, perhaps taking a different path.

I expect that we just have two very different mental pictures of what the underlying assumptions are that define the context we're talking about.)

Again, that's my point. Without any assumptions or context, it's impossible to say that one approach is better than the other.
Ernesto Arroyo
Greenhorn

Joined: Mar 06, 2011
Posts: 11

Oh!

Not only I prefer return null but I could prefer to return a NullPerson (Null Object Pattern)

It depends but a NullPerson who does nothing can be (or cannot, it depends) a great design.

yes, I love nil objects in Objective-C where you can take advantages of things like sending messages to nil and not having exceptions, only.... nothing happens...

Again it depends!
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60810
    
  65

Ernesto Arroyo wrote:I could prefer to return a NullPerson (Null Object Pattern)

Meh. Not a big fan of that. (Never come across a situation where it improves rather than clutters code clarity.)
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Ernesto Arroyo wrote:Oh!

Not only I prefer return null but I could prefer to return a NullPerson (Null Object Pattern)

It depends but a NullPerson who does nothing can be (or cannot, it depends) a great design.


So let me see if I understand this: You have this hypothetical factory method for creating a hypothetical Person or something like that, and, since you're just playing around for educational purposes, you've added the precondition that a Person's age cannot be > 99. And presumably in this hypothetical scenario you will have documented this precondition, so that any caller of your method knows that age must be <= 99 (and, I would assume, >=0).

So now, when a caller of your method has a bug whereby he's passing a value that violates the precondition, rather than use the mechanism that is specifically intended to handle that situation, you consider it better to return null--which he then has to explicitly check for in his "happy-path" code--or return a NullPerson, which he still has to check for if he wants to know if he's done anything wrong, or which he can go on using, with the mistaken impression that he has created a valid Person object of age > 99?

I'd love to hear a technical justification for that.

Or if that's not what you mean, I'd love to hear which of my assumptions are wrong.



[EDIT]
Well, one of my incorrect assumptions was that the person I was responding to was the OP. Apologies for the mixup.
Lio Liov
Ranch Hand

Joined: Mar 21, 2012
Posts: 33
Most of the posts are not from me ,who started the thread
I am just trying to learn and nobody answer why my code doesnt print the IllegalArgumentException,the code from the second post

Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Why should it print the exception? What I would expect is that the exception is not caught anywhere, so it causes your application to terminate. It's possible that whatever you are using to run your application might display that application's stack trace, but as far as I remember you haven't said anything about how you are running it.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Lio Liov wrote:Most of the posts are not from me ,who started the thread


Oops, sorry. I conflated your posts and Ernesto's
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Lio Liov wrote:
I am just trying to learn and nobody answer why my code doesnt print the IllegalArgumentException,the code from the second post



When I run that code, it throws the exception and the app terminates, just as I'd expect:

Lio Liov
Ranch Hand

Joined: Mar 21, 2012
Posts: 33
Thanks
I am using Eclipse and i doesnt show anithing
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60810
    
  65

Ditch the IDE for now and learn how to do things for real from the command line. IDEs, in my opinion, make great smart editors, but to use then to completely supplant the "real world" simply leaves you at their mercy and they become a crutch that hinders you rather than helps you.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Lio Liov wrote:Thanks
I am using Eclipse and i doesnt show anithing


I second Bear's sentiments. Until you're more experienced and are writing more complex code, an IDE will give you little or no benefit at a very high cost.

Having said that, I find it hard to believe that Eclipse doesn't give you the stack trace. Either you're not looking in the right place or you've misconfigured it.
Ernesto Arroyo
Greenhorn

Joined: Mar 06, 2011
Posts: 11

Myapologizes Lio, I didn't see your second post and begin the other conversation.

You throw the exception, but you have to catch it in your main ( or before ) and print a message (system.out or log4j better, but log4j maybe is a little more advanced now if you are learning)

So use a try-catch in the main and in the catch print the message you want.

In other case the exception goes uo to the JRE and the message is only showed in the runtime console ( and eclipse show you but not in the standard output but in a different window)

I agree, to start is better to use java in the command line, java, javac, etc
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Ernesto Arroyo wrote:
You throw the exception, but you have to catch it in your main ( or before )


No you don't. You can just let the program die. In particular, since this is an unchecked exception indicating a bug, letting the program die before any further damage is done might be the best course. (Typically, though, RuntimeException and its descendants are caught at a high level).

and print a message (system.out or log4j better, but log4j maybe is a little more advanced now if you are learning)


Simply printing a message is not good exception handling. If the program is to continue running, then the exception actually has to be handled. That is, we have to try again, or we have to provide some alternate execution that serves the same purpose as whatever it was that failed, or or program has to be able to function without that step.

So use a try-catch in the main and in the catch print the message you want.


Don't just print the message. Print the stack trace. And if you're just going to catch it in main, print the stack trace, and exit, then there's no point in catching it at all, as that's what will happen anyway.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How can I stop the object to be created
 
Similar Threads
simple web browser in java
How to store an image from a jsp page to Database
using html tag in java
How?
Passed test at 48 years 0 months