This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills: The software developer's life manual and have John Sonmez on-line!
See this thread for details.
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Some help on my method of building a sub-dialog

 
Jon Swanson
Ranch Hand
Posts: 216
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a sub-dialog that I reuse in my program. I have a class to create it and then I make it visible or not as needed. I also thought that I was handling the case where an error occurs trying to make it in the first place. Here is the simplest bit of code for illustration-



In 'real life' the constructor has a try-catch block. I stripped out everything except what I do if it fails. What has me troubled is that rd is not null if the initialization fails. So I get the error message, and then an empty dialog pops up.

Java complains if I change the return statement to 'return null.'

I was liking the fact that any graphical interaction was encapsulated in ReportDialog, so the routine that actually calls it could run without a GUI, if I preferred. I could call a method in ReportDialog that either did the initialization and returned a success/failure status or I could rethrow an exception for the calling routine to catch. I'm not short of ways to keep the dialog from appearing if the initialization fails. But before I choose a method that may end up being a bad habit, I thought I'd ask some advice from people with more experience. How should I structure things so I don't have a dialog pop-up if there is an error when I build it?
 
Tony Docherty
Bartender
Pie
Posts: 2878
59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't return anything from a constructor.
If you detect an error in a constructor and you don't want the object to be created you throw an exception.
 
Jon Swanson
Ranch Hand
Posts: 216
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class can have methods, however.



I was wondering whether rethrowing the exception was the only approach people use or there are other common ways of handling the situation.
 
Ranganathan Kaliyur Mannar
Bartender
Posts: 1101
10
Java Netbeans IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use the Builder pattern. That is quite common these days particularly to build GUI widgets. JavaFX uses a lot of builders.
 
Jon Swanson
Ranch Hand
Posts: 216
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I'll look into that.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic