Using assert or exception?

I have been struggling with the methodology of using assertions for some time
now and would like to have an objective viewpoint. It primarily has to
do with the use of assertions for pre-conditions.
Let's say we have some class, for demonstration purpose only, as this one:
public class MyClass {
    private final String str;
    public MyClass(String str)
        this.str = str;
    private int getLength(String x, String y)
        return x.length() + y.length();
    public int getTotalLength(String x)
        return  getLength(str, x);
}Let's say I want to make sure that the classes methods and constructor is not
called with any null parameter. Of course I will get a NullPointerException
eventually automatically anyway, but let's say I want to know as soon
as possible to something is wrong. Or maybe I am dealing with a complicated
class in which it is not so clear yet.
Anyway the Sun Java documentation says the following:
http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html#preconditions
"Do not use assertions to check the parameters of a public method."
Instead it should throw some particular exception. In this case a
NullPointerException in the MyClass constructor if the str parameter is
null. Conventation say that assertion can be used for private methods
however, such as the getLength method.
I always try to keep my classes relatively small. So often I feel no desire
to include assertions in private methods to check parameters if I can
already see that the parameters are checked in the public methods.
So in this case why add assertions in getLength if I can already clearly
see that the parameters have been checked in the MyClass constructor and
the getTotalLength method?
Maybe I am wrong, but I am afraid that using such rigurous parameter testing
in every public method might influence performance too much, because in
contrary of assertions these normal checks are done always. I cannot
remove these normal checks, because that would mean it could trigger
an assertion in one of the private methods, and I could as well move
the assertions from the private to the public methods.
What I don't feel comfortable about is this big distinction between
assertions and run-time exceptions. Why not use assertions in
public methods for parameter testing? They are just exceptions
too anyway. And they have the benefit of not impacting performance
for production environments.
There is an article about challenging the Sun Assert convention here.
http://www.javaworld.com/javaworld/jw-12-2001/jw-1214-assert-p2.html
I would like you to read it and give your objective opinion. Weighing
the positive and negative implications of it and tell me what you
think and why.

I don't have the time to read that article. IMO
assertions are to be used to validate the state of
your instance and its internal works.So you do not think that assertions should be used for any pre-conditions of parameters?
They are not
exceptions, by the way. Failure will result in an
AssertionError.Yes, I should have said errors or throwables.
It's quite overkill IMO to use those for the
validation of parameters provided by someone else.Why? Isn't it overkill to impact the performance by
using run-time exceptions instead of assertions?
If
your API declares the legit value range of an
argument, a NullPointerException for null and an
IllegalArgumentException for values outside bounds,
that gives me more flexibility to react and handle
error states (it could be user input - null would
mean there's a bug, out of bounds would mean I have
to ask the user again) than merely firing of a "big"
assertion error.But the whole idea of pre-conditions is that the method never must be called with invalid values. Your example might make sense for some class close to the front-end, but most classes are deep inside everything and have no idea what to do with a NullPointerException or IllegalArgumentException at that point. I would let a facade near the front-end deal with invalid user input and explicitly prevent the invalid input progress deeper inside my code.
The article I linked goed deeper in about why it is a good idea to give a "big" assertion error at that point.
There's probably no hard or objective rule when you
should use what anyway, otherwise, there wouldn't be
different opinions in this matter. If you're looking
for one, you'll most likely not find it.I have certain ideas about assertions and I would like to know if these ideas are reasonable. Especially because they go against the Sun convention and I usually am a follower of standards.

Similar Messages

  • Async tests and Assert throws exceptions

    Hi,
    In a regular non-async test, something like Assert.assertEquals( "apples", "oranges" ); gives a nice report that the strings didn't match.  The test fails and the suite continues and all is good.  If the test is asynchronous, though, you get an uncaught exception, and a timeout on the test rather than a nice report.  Worse, it will cause a command-line based test to freeze with a stack trace showing (if you have a debug version of Flash, of course), until you hit the dismiss button.
    Here's an example.  Without the Assert.assertEquals line, the test passes after two seconds as expected.  With the Assert.assertEquals in place, you get the behaviour I described.  So the question is, how do I use asserts in an asynchronous test?  I want the behaviour that you get with synchronous tests, i.e. a nice report and no pop-up dialog showing the stack.
            const TEST_COMPLETE:String = "testComplete";
            [Test(async)]
            public function myAsyncTest():void   
                Async.proceedOnEvent( this, this, TEST_COMPLETE, 5000 );
                var t:Timer = new Timer(2000, 1);
                t.addEventListener(TimerEvent.TIMER, timeout);
                t.start();
            private function timeout(e:Event):void
                Assert.assertEquals( "apples", "oranges" );
                dispatchEvent( new Event(TEST_COMPLETE) );
    Any help?
    Thanks!
    DB

    The code you have below doesn't do what you think it does.
    When you setup an async test in FlexUnit, it needs to know what code is related to a given test. When you use items like the asyncHandler() methods, it basically calls that code in a way that watches for assertions and can manage to track them when they occur.
    In your code, you are setting up a timer and that timer is calling another method which does an assertion. The timer calls that code directly from the top of the call stack... in other words, completely outside of FlexUnit. FlexUnit doesn't know your method is being called and cannot wrap the call in order to catch any information thrown from your assertion.
    Can you describe what you want to do and I can advise you on the right syntax? It isn't that assertions work differently in async tests, it is that FlexUnit has no idea that the timeout() method is being called, Flash Player is calling it directly, and hence there is no way for it to watch the assertion.
    I am guessing you want something more alogn the lines of this, but I am not sure:
    Test(async)] 
    public function myAsyncTest():void{
    var t:Timer = new Timer(2000, 1); 
    var handler:Function = Async.asyncHandler( this, timeout );t.addEventListener(TimerEvent.TIMER, handler );
    t.start();
    private function timeout(e:Event, passThroughData:Object ):void
    Assert.assertEquals(
    "apples", "oranges" );}

  • I have all of my music on my dad's apple ID (on my Macbook pro and iphone). I want to start using my own apple ID (the one that my iPhone uses for everything except iTunes store) as my iTunes apple ID - how do I do this without losing my old music?

    I have all of my music on my dad's apple ID (on my Macbook pro and iphone). I want to start using my own apple ID (the one that my iPhone uses for everything except iTunes store) as my iTunes apple ID - how do I do this without losing my old music?

    Authorize your computer with your Dad's AppleID.

  • I've a problem which is: Ibelieve there's someone who knows my password in some games like "Happy Day" so, could you please help me by not letting anybody to use this game except for this IMEI 01 336000 521261 1 even if they have the correct password.

    I've a problem which is: Ibelieve there's someone who knows my password in some games like "Happy Day" so, could you please help me by not letting anybody to use this game except for this IMEI 01 336000 521261 1 even if they have the correct password. Thanks alot for your help.

    Change your password.
    These are user forums. We can't do what you ask, in fact no one can.

  • How to use assert with wireless toolkit?

    Hi,
    I am trying to find out how to use assert with wireless toolkit. I have found that I need to pass "-source 1.4" to the java compiler. But I can't find any documentation on how to do it.
    I'm using J2ME Wireless Toolkit 2.2.
    thanks
    Ludde

    Here's a quote from an article on Java World at http://www.javaworld.com/javaworld/jw-11-2001/jw-1109-assert.html
    "To support the new assertion facility in J2SE 1.4, the Java platform adds the keyword assert to the language, an AssertionError class, and a few additional methods to java.lang.ClassLoader."
    So I really think it's part of 1.4.

  • How to Use " ASSERT ID " , in the programm and what is the use of it?

    Hi,
    friends,
    I wanted to write a program (TEST CASE) by using ASSERT ID . But i got the description (Hint) like what iam mentioning below:
    *" Detects uses of ASSERT ID and flags cases where there is code to be executed after the command. In production environments ASSERTS are disabled, as a rule, therefore this code gets to be executed. "
    So, let me know the Use of this key word with some example .
    Thanks & Regards,
    P.N.Kumar

    Hi,
         Please look for F1 on this keyword. Also look at "Checkpoints".
         Check this link.
         http://help.sap.com/erp2005_ehp_02/helpdata/EN/9b/b1b64104e52f31e10000000a155106/frameset.htm
    Regards,
    Srini.

  • Why use customized / particular exceptions instead java.lang.Exception

    Hi,
    Do any of you guys know where can I find a theorical statement / explanation about why use particular / customized exceptions instead java.lang.Exception? I am aware that it consumes more resources and becomes a heavier object, as well as the clearness when coding and all that stuff; however, my boss wants to see a tech document where all this is clearly stated. Any resource over there?
    Regards

    It is better to throw specific--or at least module- or
    package-specific--excpetions, rather than Exception,
    because then the caller knows what to expect. However,
    if you declare "throws Exception", the caller can
    still catch IOException, SQLException, etc.,
    separately. He'll just have to be a really good
    guesser as to which ones he should catch.True.
    Also, there's no point in declaring "throws
    NullPointerException." Any method can throw it without
    declaring it. If you generate your own NPE (or other
    unchecked exception) inside the method, then you
    should document it in the javadoc comments, but you
    don't need to put it in the throws clause. It doesn't
    do any harm, but it's redundant and cluttersome.It was an example and I wasn't feeling too creative....excuse me. ;-) But yeah, I've never thrown NPE ever.
    I'm assuming overhead caused by extending classes.At
    the worst, it would be miniscule, or so I wouldthink.
    What overhead is created by extending classes?Hmm, I was under the impression that a class the extended another class, inherited all of the other classes data (variables, etc.). Hence, you get something like this:
    SuperClass1 + SubClass1 + SubClassOfSubcCass1 = Memory usuage for SubClassOfSubClass1.
    Since adding postivie number will always end up increasing data, SubClassOfSubClass1 will use more dtat than SuperClass1.
    Am I wrong?

  • If I do NOT use any event, except AT SELECTION SCREEN, Do I get any issues?

    Hi Experts,
    Pls. let me know that, If I do NOT use any event, except AT SELECTION SCREEN, Do I/prog. get any issues? (am also using AT SELECTION SCREEN OUTPUT for list box preperation).
    For some reason(execution of the report prog. with ENTER button), am using ONLY these 2 events.
    For full detials, pls. see my other thread with title,
    Is it possible to execute a REPORT prog. with pressing of ENTER button?
    thanq

    Hi
    srinivas see this program
    i am executing this program with out any event it is not showing any error but not giving output
    when i put start-of-selection then it is showing output
    *& Report  ZNNR_REPORT33
    REPORT  ZNNR_REPORT33 NO STANDARD PAGE HEADING MESSAGE-ID ZNNR LINE-SIZE 100 LINE-COUNT 65(4).
    ******DATA DECLARATIONS**********
    DATA : BEGIN OF IT_PLANT OCCURS 0,
            MATNR LIKE MARA-MATNR,
            WERKS LIKE MARC-WERKS,
            PSTAT LIKE MARC-PSTAT,
            EKGRP LIKE MARC-EKGRP,
           END OF IT_PLANT.
    DATA : BEGIN OF IT_PONO OCCURS 0,
            EBELN LIKE EKKO-EBELN,
            EBELP LIKE EKPO-EBELP,
            MATNR LIKE EKPO-MATNR,
            WERKS LIKE EKPO-WERKS,
            LGORT LIKE EKPO-LGORT,
           END OF IT_PONO.
    TABLES EKKO.
    ********END OF DATA DECLARATIONS*********
    ********SELECTION SCREEN DESIGN ***********
    SELECTION-SCREEN BEGIN OF BLOCK B1 WITH FRAME TITLE TEXT-001.
    PARAMETER : P_WERKS LIKE MARC-WERKS MODIF ID S1.
    SELECT-OPTIONS : S_EBELN FOR EKKO-EBELN NO INTERVALS MODIF ID S2.
    SELECTION-SCREEN END OF BLOCK B1.
    SELECTION-SCREEN BEGIN OF BLOCK B2 WITH FRAME TITLE TEXT-004.
    SELECTION-SCREEN BEGIN OF LINE.
    PARAMETERS : R1 RADIOBUTTON GROUP G1 DEFAULT 'X' user-command uc1.
    SELECTION-SCREEN COMMENT 5(20) TEXT-002 FOR FIELD R1.
    SELECTION-SCREEN END OF LINE.
    SELECTION-SCREEN BEGIN OF LINE.
    PARAMETERS : R2 RADIOBUTTON GROUP G1.
    SELECTION-SCREEN COMMENT 5(20) TEXT-003 FOR FIELD R2.
    SELECTION-SCREEN END OF LINE.
    SELECTION-SCREEN END OF BLOCK B2.
    ******END OF SELECTION SCREEN DESIGN****************
    ***********SCREEN MODIFICATIONS*******************
    AT SELECTION-SCREEN OUTPUT.
      LOOP AT SCREEN.
        IF R1 EQ 'X' AND SCREEN-GROUP1 EQ 'S2'.
          SCREEN-INPUT = 0.
          MODIFY SCREEN.
        ENDIF.
        IF R2 EQ 'X' AND SCREEN-GROUP1 EQ 'S1'.
          SCREEN-INPUT = 0.
          MODIFY SCREEN.
        ENDIF.
      ENDLOOP.
    ********END OF SCREEN MODIFICATIONS*****************
    ***************SCREEN VALIDATIONS *****************
    at selection-screen.
      SELECT SINGLE *
               FROM EKKO
               INTO EKKO
               WHERE EBELN IN S_EBELN.
      IF SY-SUBRC <> 0.
        SET CURSOR FIELD 'S_EBELN-LOW'.
        MESSAGE E999 WITH TEXT-005.
        clear S_ebeln-low.
      ENDIF.
    ********end of screen validation*****************
      IF R1 EQ 'X'.
    *ULINE AT /1(48).
        WRITE : SY-VLINE ,2 'MATERIAL NUMBER',
                21 SY-VLINE , 22 'PLANT',
                27 SY-VLINE , 28 'STATUS',
                43 SY-VLINE , 44 'GRUP', 48 SY-VLINE.
        ULINE AT /1(48).
      ENDIF.
      IF R2 EQ 'X'.
        WRITE : SY-VLINE , 2 'PO NUMBER',
               12 SY-VLINE, 13 'ITEM',
               18 SY-VLINE,19 'MATERIAL NUMBER',
               37 SY-VLINE, 38 'PLANT',
               44 SY-VLINE, 45 'GRUP',
               49 SY-VLINE.
        ULINE AT /1(50).
      ENDIF.
    start-of-selection.
    *set pf-status '100'.
      IF R1 EQ 'X'.
        SELECT MATNR
               WERKS
               PSTAT
               EKGRP
           FROM MARC
           INTO TABLE IT_PLANT
           WHERE WERKS = P_WERKS.
        LOOP AT IT_PLANT.
          WRITE : SY-VLINE , 2 IT_PLANT-MATNR COLOR COL_KEY,
                 21 SY-VLINE , 22  IT_PLANT-WERKS COLOR COL_KEY,
                 27 SY-VLINE ,28 IT_PLANT-PSTAT COLOR COL_NORMAL,
                 43 SY-VLINE ,44 IT_PLANT-EKGRP COLOR COL_NORMAL.
        ENDLOOP.
      ENDIF.
      IF R2 EQ 'X'.
        SELECT EBELN EBELP MATNR WERKS LGORT
               FROM EKPO
               INTO TABLE IT_PONO
               WHERE EBELN IN S_EBELN.
        LOOP AT IT_PONO.
          WRITE : SY-VLINE , 2 IT_PONO-EBELN COLOR COL_KEY,
                 12 SY-VLINE , 13 IT_PONO-EBELP COLOR COL_KEY,
                 18 SY-VLINE , 19 IT_PONO-MATNR COLOR COL_NORMAL,
                 37 SY-VLINE , 38 IT_PONO-WERKS COLOR COL_NORMAL,
                 44 SY-VLINE , 45 IT_PONO-LGORT COLOR COL_NORMAL, 49 SY-VLINE..
        ENDLOOP.
      ENDIF.
      ULINE AT /1(50).
      WRITE :/10 'PAGE NUMBER', SY-PAGNO, '/' ,SY-PAGNO.
      ULINE AT /1(50).
      WRITE :/10 'PAGE NUMBER', SY-PAGNO.

  • Using an unchecked exception to alter flow control inside a class

    Best-practice question:
    Is it wrong to use an unchecked exception in an if-like manner?
    For example, instead of using:
    if (condition) {
    -----------a lot of code-----------------
    } else {
    ----------some more code--------------
    Is it wrong to do it like this?
    try {
    if (!condition) throw new IllegalArgumentException();
    -------------a lot of code---------------
    } catch (IllegalArgumentException e) {
    --------------some more code-----------
    I'm asking because I used this kind of practice recently in a piece of code i wrote (actually i used it to validate an argument I received from a html-form and post an error message in the catch block) and a colleague told me it was bad practice.
    If it IS bad practice, when should you actually use unchecked exceptions like IllegalArgumentException?
    I already posted this question in the newbie forum, but didn't get any answers. Anybody here can explain this to me please?

    It is fine to use IllegalArgumentException, but typically it is used when the code generating the exception and the client who is using the code that generates the exception are two different pieces of code.
    If you were writing some kind of library for others to use. It would make sense to throw this exception out of your library if the user gave you wrong data.
    But you shouldn't use exceptions as normal program logic.

  • How to use CALC ALL EXCEPT...

    I have some statistics that I don't want aggregated by product. The DBAG says you can do a CALC ALL EXCEPT command but the syntax is not explained very well. I need something like:CALC ALL EXCEPT the member statistics for the dimension All_ProductsI have been doing a calc script to CALC ALL and then to clear out all the parents for ALL_Products for the affected accounts, but it takes a long time.Any suggestions?? Thanks! - Debbie

    Depending on your outline it is many times more efficient (time wise)to do a fix ont the members you want (or use a remove list for members you don't want) and do a calc dim of the dimensions that do not have dynamic calc upper level members. also exclude dimensions that don't roll up like scenario. The best use of the Except is when you want to exclude a complete dimensionlike clac all except dim(time);Glenn S.Narratus Solutions

  • Using assert()

    hello
    Where m i wrong in using assert()
    In both outputs it print out: True Number,True Number
    class assertion
    void take(int a)
          assert(a>5);
          System.out.println("True Number");
      public static void main(String[] args)
         assertion obj=new assertion();
          obj.take(1);
          obj.take(20);
    }

    Java-Manoj wrote:
    kajbj wrote:
    (Use the -ea vm argument)Ok, I got it, but the argument vm is not required.
    Sorry. That I caused confusion. -ea is the vm argument, there's a difference between vm arguments and application arguments.

  • I have the interactive student mathematics CD from Haese & Harris Publications that requires Adobe Reader and includes a 'Self-help Tutor". I can open all the features using Adobe Reader except the Self-Tutor. I get a pop-up message saying I require an ap

    I have the interactive student mathematics CD for the Cambridge IGCSE Mathematics (0607) Extended from Haese & Harris Publications that requires Adobe Reader and includes a 'Self-help Tutor". I can open all the features using Adobe Reader except the Self-Tutor. I get a pop-up message saying that: I require an app to open "26Unitary Method.app". I can find no mention of this app online so can someone please help me?
    Thank you.

    Thank you for the prompt reply.  The CD says that it needs Adobe Reader (and it does read the 'Text book'), but it is not opening the interactive elements. Great!
    I am doing as you suggest and contacting Haese directly. Again, many thanks.

  • Debugging using assertions

    hello,
    is there any java game developer here using assert function
    i had read the article and still don't know how to use it properly
    it said that assert is the best way for debugging
    until now i only use the conventional System.out.println for debugging
    (do not know how to use any debugger tool)
    i'll be very grateful if someone can explain how to use it,
    cos i have been through many difficulties using System.out.println to find bugs in my infinitive game loop
    thanxx a million

    Using assertions:
    - you put expressions in your code like
    assert(val > 0);
    or
    assert (val > 0):"variable val too low";
    - you must use java 1.4 or later and compile with javac -source 1.4
    - you must run with java -enableassertions
    - if the assertion condition is not true an AssertionError is thrown
    You should only use assertions to check conditions resulting from you code's execution, never conditions arising out of user input or parameters passed to public methods.
    When your code is run without the -enableassertions the assert statements become no-ops.
    Hope this helps.

  • My ios is upgrade to 7.0.2, but I forget my power-on password, so the iphone is disabled and I can't use it now except for emergrncy call. Please help me...

    My ios is upgrade to 7.0.2, but I forget my power-on password, so the iphone is disabled and I can't use it now except for emergrncy call. Please help me...

    I tried this way , but I forgot my e-mail address too !
    and I dont have any idea to re-active my iPhone5 ..
    sombody help me .

  • How to use an ABAP exception as a web service fault

    Hi experts,
    I have created a web service out of an ABAP function module, using the SAP standard wizard for web services. The ABAP function has some exceptions defined. Now the question is: How can I "translate" these ABAP function exceptions to web service faults?
    In the WSDL file I can see that the web service defines the faults, but they are not part of the web service operation (in the WSDL file). So when I load the definition into JDeveloper, the faults are not recognized.
    Any ideas what I am missing here?
    Thanks in advance!
    Kind regards, Matthias

    Exceptions from SAP function module are not translated as web service fault message, this is a standard behaviour due among other to the fact that exceptions are not "in line" with the definition a web service fault message.
    Usually when you want to use a standard SAP function module and expose it as web service, you need to "wrap-it" into a new Z function module.
    In that new function module you must capture the exceptions and convert them into a web service fault message structure (usually containing error type, text and number)
    Karim

Maybe you are looking for