How do I deal with problems during business object construction?

Hi Everyone.
I'm wondering about best practices for program control flow when business objects can't be constructed properly.
In my servlet I want to create a new Transaction business object based on the parameters of the HttpServletRequest.
transaction = new Transaction( request );The Transaction, in turn, has a Customer business object representing the Customer doing the transaction. The Customer is also constructed based on request parameters. So I have in the Transaction constructor,
public Transaction( HttpServletRequest request ) {
    customer = new Customer( request );
}In the Customer constructor I want to do some validation. For example, I want to check that the requested Customer exists in the database.
If the validation fails, should I throw an exception, which could then eventually be caught by the Servlet which would send back an "Invalid Customer" message to the end user?
But it seems to me like this violates the "never use exceptions for flow control" rule (as described for example at http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2).
It is a normal function of my application to deny a transaction to a non-valid customer... so it seems like I shouldn't need to bring in the exception handling overhead for this normal business process.
OK, so I guess put "is_valid" flags in the business objects and set them on constructor errors then check them??
public Transaction( HttpServletRequest request ) {
    customer = new Customer( request );  // customer.is_valid flagged false
    if ( !customer.get_is_valid( ) ) {
        this.is_valid = false; // transaction.is_valid is also false now because its Customer is not valid
    } else { // customer is valid
        // finish the rest of the Transaction construction business logic
        // of course this will turn into a mess of deeply nested "else valid" clauses
        // if there are many validation checks...
}...and then in the servlet...
transaction = new Transaction( request );
if ( !transaction.get_is_valid( ) ) {
    // Send back error message to user.
} else {
    // Finally do some business logic.  Maybe after another mess of nested "else valid" clauses.
}This gets so hard to read it seems like the throwing Exceptions as part of normal control flow option is preferble.
Is there third option I am missing?
What are your opinions?
Thanks,
Bishop

Build your Transaction and Customer objects based on the data in the request. Then validate the customer, since an invalid customer is "normal" for you.
I'd consider using some sort of factory-like method for creating these objects from the request, since you're tying (sort of) your business stuff to the fact you're currently using a webby (servlet-based) front end...but that's more an aside.
So, in pseudo-ish code:
Transaction t = createTransaction(request);
if (t.validCustomer()) do work;
else return to wherever;This is only a first-pass idea, and other requirements might knock it for six, but it's a startpoint.

Similar Messages

  • Has anyone experienced problems with Mackeeper? I did not complete downloading this software. Yet, occasionally when on the internet, I will have the MacKeeper multi-colored circle replace my pointer. How do you deal with this?

    Has anyone experienced problems with Mackeeper? I did not complete downloading this software. Yet, occasionally when on the internet, I will have the MacKeeper multi-colored circle replace my pointer. How do you deal with this?

    Welcome to Apple Support Communities
    Don't download MacKeeper. Users complain about this app and it damages OS X. Also, Mac OS X knows how to take care of itself, so you don't need any other cleaning application that may damage OS X. See > https://discussions.apple.com/docs/DOC-3691

  • It says that "there was a problem connecting to the server". What's wrong with this, and how can I deal with this problem?

    I just got my new iPad Mini2, and when I choose "sign in with your apple ID", it says that "there was a problem connecting to the server". What's wrong with this, and how can I deal with this problem?

    1. Turn router off for 30 seconds and on again
    2. Settings>General>Reset>Reset Network Settings

  • How do I deal with constant "error loading content" messages?

    I'm constantly seeing error messages on my Apple TV (2nd gen) on content I easily watch on my other iDevices. What gives? This thing is rapidly becoming a vy expensive paper weight. Possibly the worst Apple product I've yet purchased. Am I alone in this?  What can I do?

    You cannot connect to TC using USB.
    Plug the TC into the computer using ethernet.
    Press and hold the reset button on the TC for about 10sec.. until front led rapidly flashes.. release it.
    Open the airport utility and make sure you can locate the TC. Check the disk page that the disk started up without errors.
    When you say
    Sodrawi wrote:
    How do I deal with the error message at my Time Capsule saying "There is a problem to connect to server xxxx-Time-Capsule.local."
    I am guessing you mean Time Machine.
    If TM still cannot find the TC disk.. reset TM and redo the setup.
    Read A4 here.
    http://pondini.org/TM/Troubleshooting.html

  • HT1420 I purchased new computers twice within the same year because they old were damaged in a storm.  However, I can't deauthorize/reauthorize the new computers.  How do I deal with this situation.

    I purchased new computers twice within the same year because they were damaged in a storm.  However, I can't deauthorize/reauthorize the new computers because it has been less than a year.  How do I deal with this situation?

    BrianBlaze wrote:
    I have 3 Computers at home, I am studying computer sciences and am constantly rerformatting my computers, installing windows and linux over and over again.... EVERYTIME I reformat I have to authorize the same computer and so it takes up one of my 5 authorized computers... Anyways after deauthorizing all my computers in september I was not aware I couldn't do it for another year (why does APPLE assume these stupid tactics prevent piracy). Anywysw I need to reach apple and have them make it so I can do it again. I had a similar problem with Playstation and when I called them they fixed it for me... even windows (which you can only have one serial per computer) made it easy because all I had to do was call them and they fixed it for me. Now I need APPLE to do the same and this is the only place I could see to actually say what is going on... I can't believe I have to do this with my iPhone... I wanted an mp3 player and a phone together and if I can't put new songs until September 20, 2012 I am going to freak out!
    HELP!
    Brian
    Try this link: http://www.howtogeek.com/howto/23974/beginner-deauthorize-all-computers-associat ed-with-your-itunes-account/

  • How can I deal with long sql by the oo4o?

    I am using VB and oo4o to develop a sql executor which is a extention of an old system.
    For some reason, I have to use oo4o v8.1.7 to deal with Oracle Database 8i to 11g.
    But when I send a very long sql(11KB) to it I got a error in the VB enviroment.
    The Err.Description is "automention error. Started object is disconnected by the client.".
    The Err.Number is "-2147417848 ".
    The sql that I send it to the program is a simple select sql that like select a, b, c, substrb(d, 1, 2), substrb(e, 2, 3) .... from A_TBL where A=aa;
    This sql is normally executed by the sqlplus but I got an error by the oo4o.
    When I insert a '' between the 30Xth items, it got exectuted normally.
    ex. select a, b, c, substrb(d, 1, 2), substrb(e, 1, 2) ..... substrb(303th, 3, 4), '', substrb(304th, 1, 2) ... from A_TBL where A = aa;
    How can I deal with this problem? Thanks.

    So how can use this function correctly?By learning what exceptions are, how they're used, and what you can do to deal with them. There's a tutorial here: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.htmlAnd here's a quick overview:
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.

  • How do I deal with Tokenized strings that are blank?

    I'm writing a little application that writes data to a file. It sends data to the file as a "|" delineated string. Then I use tokenizer to break up the string as follows:
    try {
                                  String searchtext = SearchTxt.getText();
                                  String tokenString = "";
                                  String[] returnData = new String[8];
                                  File filedata = new File("bigbase.txt");
                                  BufferedReader in = new BufferedReader(
                                  new FileReader(filedata));
                                  String line = in.readLine();
                                  while ( line != null) {
                                  Pattern pat = Pattern.compile(searchtext);
                                  Matcher mat = pat.matcher(line);
                                       if ( mat.find() ) {
                                       StringTokenizer t = new StringTokenizer(line, "|");
                                       maintextArea.setText("");
                                       int count = 0;
                                            while (t.hasMoreTokens()) {
                                                 tokenString = t.nextToken();
                                                 returnData[count] = tokenString;
                                                 maintextArea.append(tokenString + " ");
                                                 System.out.println(tokenString);
    etc etc etc
    The problem is that when the tokens are blank, I get an endless loop when I try to print out the data on that last line. How do I deal with Tokens that are blank so they don't endlessly loop my output?
    Thanks
    MrThis

    Most people would probably tell you to use:
    String.split(...);
    But I'm not most people and I wrote this class before regex support was added to the String class which is based on StringTokenizer but supports empty tokens:
    http://www.discoverteenergy.com/files/SimpleTokenizer.java

  • How should I deal with it in the BMM Layer

    Hi all,
    I need a suggestion in a problem.
    Here is the scenario,
    In the physical layer, There are some fact to fact joins.
    ProductFact ----< PolicyFact ----< PolicyCoverFact ----< ClaimFact ----< ClaimPaymentFact ----< CorrespondenceFact
    There are some conformed dimension tables given below
    Geography is joined to ProductFact, ClaimFact
    Organisation is joined to PolicyCoverFact, CorrespondenceFact
    Currency is joined to PolicyFact, ClaimPaymentFact
    Also there are non-conformed dimensions such as,
    ProductType is joined to ProductFact
    PolicyCoverType is joined to PolicyCoverFact
    and there are many more......What I know is when there are fact to fact joins, we should make a logical table in the BMM layer and add both fact tables to the same LTS, But in this case, almost all the fact tables are joined directly.
    How should I deal with these fact to fact joins in the BMM layer? Any suggestions?
    Edited by: LavaRider on Aug 25, 2010 2:47 AM

    LavaRider wrote:
    I have to create many LTS for the fact table......
    1 LTS for ProductFact
    1 LTS for ProductFact & PolicyFact (which contain ProductFact and PolicyFact as sources)
    1 LTS for ProductFact , PolicyFact & PolicyCoverFact ........
    and so on.....
    have I understood correctly? Is that what you mean?Yes, the reason why I said to "keep" the firsts fact table in each source is to make the dimension work.
    For example, if the "product dimension" is only linked to "product fact", but not "policy fact" then you won't be able to do a report based on "product dimension" and "policy fact". Right ? To be able to do this report, OBIEE must do a join with "product fact" (this fact table become an intersection table). That's why you will add product fact in the "policy fact" source. Same for others source.
    But the name of "ProductFact & PolicyFact" source can be "policy fact". Because each row of this source is a policy fact.
    For the 3rd table, each row is a "policy cover fact". But to be able to join with "product dimension" and "policy dimension", you need to integrate "policy fact" and "product fact" tables in the logical source.
    and so on.

  • My iphone was disable and it say connect to itunes. but when i connect it to my computer, my computer cant detact my device. how do i deal with this situation?

    hi, i have a problems. my iphone is being disable after my daughter play with it and been entering all the wrong code. so my iphone is now disable and it say connect to itunes. i already plug my iphone to my computer, how ever my computer could not detact my devic. and because of that i cant connect it to my itunes. how do i deal with this problems?

    iOS: Device not recognized in iTunes for Windows

  • How does Essbase deals with multi-users

    How does Essbase deals with multi-users connecting for reading and writing in the same time? How the global coherence of the database is controlled when users are updating dimension and data all together?

    For reading, Essbase handles multiple requests concurrently. For metadata (outline) only one user at a time can make and save changes.For data, Essbase uses a block level locking mechanism, which implies that an update to a block can only be done by a single update request, but other blocks in the database are still updateable by other users.Hope that helps.Regards,Jade---------------------------------Jade ColeSenior Business Intelligence ConsultantClarity [email protected]

  • HT5621 I have moved permanently from the US to live in the UK. when I try to download a UK app I am often told that I cannot use a UK Apple sstore, only a US store. I need to access various UK stores how can I deal with this?

    I have moved permanently from the US to live in the UK. when I try to download a UK app I am often told that I cannot use a UK Apple sstore, only a US store. I need to access various UK stores how can I deal with this?

    Try here
    http://support.apple.com/kb/HT1311
    when you have UK Cards etc best to change as well

  • Adobe always quits unexpectedly in Mac when I read a bit fast. How can i deal with it, plz?

    Adobe always quits unexpectedly in Mac when I read a bit fast.
    It is the latest update.
    How can i deal with it, plz?

    You posted in the forum for iPad and iPhone (different app). I've moved your question to the Reader forum for desktop/laptop computers.

  • How can I deal with an apostrophy

    My simple questions is how can I deal with an apostrophy when I trying to save to the table, here is an example in how I am saving.
    'Sandr'as Casa' this gives me an error message. I have to do it like this
    Strings.replace("Sandr'as Casa"," ' "," ' ' "), a package function
    SQLDesFollow = "UPDATE [CRVMReq] " +
    "SET [SkillSet]='" + Strings.replace("Sandr'as Casa"," ' "," ' ' ")+ "'" WHERE [ReqId]='" + ReqValuesReqId[4] + "";
    dbs.execute(SQLDesFollow);
    SQLDesFollow = "UPDATE [CRVMReq] " +
    "SET [SkillSet]='Sandr'as Casa' WHERE [ReqId]='" + ReqValuesReqId[4] + "";
    dbs.execute(SQLDesFollow);
    any help will be appreciated.

    Here is the magic word: PreparedStatement.
    Start here:
    http://java.sun.com/docs/books/tutorial/jdbc/basics/pr
    epared.htmlSeconded, thirded and fourthed.
    And if later readers of this thread feel that they would like to provide another answer then they should think again because they would be wrong.
    There is only one correct answer to this question. PreparedStatement.

  • How do I deal with the"new itunes library" fiasco

    how do I deal with the "new itunes library" fiasco...?

    Recovering your iTunes library from your iPod or iOS device: Apple Support Communities

  • TS1436 I received this message twice on 2 new & separate attempts to burn a playlist to a NEW cd:  "The attempt to burn a disc failed.  The burn failed because of a medium write error."  What is a "medium write error" and how can I deal with this?

    I received this message twice on 2 new & separate attempts to burn a playlist to a NEW cd:  "The attempt to burn a disc failed.  The burn failed because of a medium write error."  What is a "medium write error" and how can I deal with this?

    Hello Pat,
    The following article provides troublehsooting steps and information that can help get iTunes burning discs again.
    Can't burn a CD in iTunes for Windows
    http://support.apple.com/kb/TS1436
    Cheers,
    Allen

Maybe you are looking for

  • Billing Doc not releasin for acccounting doc

    Hi After detail checking I have found that in customer master data>>Partner function tab, there is PY payer is required entry. When I am going to release billing doc in VF02 system is giving error message         Customer 730 has no bank details of t

  • Customer consignment price

    Hi, I would like to know from where system retrive the price during good issue for customer consignment using movement 633? Thank you

  • How can I invite someone to a calendar event after IOS8 update?

    Before the update I could select invitee and invite other icloud users to my events so it would show on their calendar as well. Now I do not see that option. Any advice?

  • Repository users in Designer 6

    Hello. I upgraded from Designer 1.3.2 to Designer 6. The database version is Oracle 8.0.5.0.1 running on Win NT. After the upgradation I am not able to access the application systems when connected as a repository user. The repository users have been

  • Is there any app that supports uploading word documents from iPad?

    Not being able to upload my cv from iPad. Is there any app that will help me do it? Please help!