Setter error checking

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
6
down vote

favorite












I have a class called Duration which has the attributes hours, mins, and secs. These attributes have to stay within acceptable ranges, so I implemented the following in their setters:



public void setHours(int newHours)
if (newHours >= 0)
hours = newHours;

else
throw new RuntimeException("Invalid argument values");




and so on for the other attributes.



Is there a better design pattern I could be using here? Is this an appropriate use of the RuntineException?







share|improve this question





















  • If newHours must be >= 0, why not use an unsigned int? Granted, this may lead to problems if negative numbers are provided -- but that would (in theory) move the error checking out of the setter and into the code that uses the setter.
    – tonysdg
    Jan 15 at 19:38







  • 1




    This is a private method — could you also show the code that calls it? I suspect that this class is improperly designed.
    – 200_success
    Jan 15 at 20:50










  • @tonysdg java doesn't have those.
    – njzk2
    Jan 16 at 2:32










  • @njzk2: Seriously? Never knew that (I'm mainly a C/Python guy). Huh -- I wonder what was behind that (awful, IMO) design choice.
    – tonysdg
    Jan 16 at 13:42










  • @200_success Whoopsies, this is supposed to be public, will edit.
    – Brett Warren
    Jan 16 at 16:05
















up vote
6
down vote

favorite












I have a class called Duration which has the attributes hours, mins, and secs. These attributes have to stay within acceptable ranges, so I implemented the following in their setters:



public void setHours(int newHours)
if (newHours >= 0)
hours = newHours;

else
throw new RuntimeException("Invalid argument values");




and so on for the other attributes.



Is there a better design pattern I could be using here? Is this an appropriate use of the RuntineException?







share|improve this question





















  • If newHours must be >= 0, why not use an unsigned int? Granted, this may lead to problems if negative numbers are provided -- but that would (in theory) move the error checking out of the setter and into the code that uses the setter.
    – tonysdg
    Jan 15 at 19:38







  • 1




    This is a private method — could you also show the code that calls it? I suspect that this class is improperly designed.
    – 200_success
    Jan 15 at 20:50










  • @tonysdg java doesn't have those.
    – njzk2
    Jan 16 at 2:32










  • @njzk2: Seriously? Never knew that (I'm mainly a C/Python guy). Huh -- I wonder what was behind that (awful, IMO) design choice.
    – tonysdg
    Jan 16 at 13:42










  • @200_success Whoopsies, this is supposed to be public, will edit.
    – Brett Warren
    Jan 16 at 16:05












up vote
6
down vote

favorite









up vote
6
down vote

favorite











I have a class called Duration which has the attributes hours, mins, and secs. These attributes have to stay within acceptable ranges, so I implemented the following in their setters:



public void setHours(int newHours)
if (newHours >= 0)
hours = newHours;

else
throw new RuntimeException("Invalid argument values");




and so on for the other attributes.



Is there a better design pattern I could be using here? Is this an appropriate use of the RuntineException?







share|improve this question













I have a class called Duration which has the attributes hours, mins, and secs. These attributes have to stay within acceptable ranges, so I implemented the following in their setters:



public void setHours(int newHours)
if (newHours >= 0)
hours = newHours;

else
throw new RuntimeException("Invalid argument values");




and so on for the other attributes.



Is there a better design pattern I could be using here? Is this an appropriate use of the RuntineException?









share|improve this question












share|improve this question




share|improve this question








edited Jan 16 at 16:05
























asked Jan 15 at 15:31









Brett Warren

884




884











  • If newHours must be >= 0, why not use an unsigned int? Granted, this may lead to problems if negative numbers are provided -- but that would (in theory) move the error checking out of the setter and into the code that uses the setter.
    – tonysdg
    Jan 15 at 19:38







  • 1




    This is a private method — could you also show the code that calls it? I suspect that this class is improperly designed.
    – 200_success
    Jan 15 at 20:50










  • @tonysdg java doesn't have those.
    – njzk2
    Jan 16 at 2:32










  • @njzk2: Seriously? Never knew that (I'm mainly a C/Python guy). Huh -- I wonder what was behind that (awful, IMO) design choice.
    – tonysdg
    Jan 16 at 13:42










  • @200_success Whoopsies, this is supposed to be public, will edit.
    – Brett Warren
    Jan 16 at 16:05
















  • If newHours must be >= 0, why not use an unsigned int? Granted, this may lead to problems if negative numbers are provided -- but that would (in theory) move the error checking out of the setter and into the code that uses the setter.
    – tonysdg
    Jan 15 at 19:38







  • 1




    This is a private method — could you also show the code that calls it? I suspect that this class is improperly designed.
    – 200_success
    Jan 15 at 20:50










  • @tonysdg java doesn't have those.
    – njzk2
    Jan 16 at 2:32










  • @njzk2: Seriously? Never knew that (I'm mainly a C/Python guy). Huh -- I wonder what was behind that (awful, IMO) design choice.
    – tonysdg
    Jan 16 at 13:42










  • @200_success Whoopsies, this is supposed to be public, will edit.
    – Brett Warren
    Jan 16 at 16:05















If newHours must be >= 0, why not use an unsigned int? Granted, this may lead to problems if negative numbers are provided -- but that would (in theory) move the error checking out of the setter and into the code that uses the setter.
– tonysdg
Jan 15 at 19:38





If newHours must be >= 0, why not use an unsigned int? Granted, this may lead to problems if negative numbers are provided -- but that would (in theory) move the error checking out of the setter and into the code that uses the setter.
– tonysdg
Jan 15 at 19:38





1




1




This is a private method — could you also show the code that calls it? I suspect that this class is improperly designed.
– 200_success
Jan 15 at 20:50




This is a private method — could you also show the code that calls it? I suspect that this class is improperly designed.
– 200_success
Jan 15 at 20:50












@tonysdg java doesn't have those.
– njzk2
Jan 16 at 2:32




@tonysdg java doesn't have those.
– njzk2
Jan 16 at 2:32












@njzk2: Seriously? Never knew that (I'm mainly a C/Python guy). Huh -- I wonder what was behind that (awful, IMO) design choice.
– tonysdg
Jan 16 at 13:42




@njzk2: Seriously? Never knew that (I'm mainly a C/Python guy). Huh -- I wonder what was behind that (awful, IMO) design choice.
– tonysdg
Jan 16 at 13:42












@200_success Whoopsies, this is supposed to be public, will edit.
– Brett Warren
Jan 16 at 16:05




@200_success Whoopsies, this is supposed to be public, will edit.
– Brett Warren
Jan 16 at 16:05










2 Answers
2






active

oldest

votes

















up vote
9
down vote



accepted










Input validation is a critical aspect of any reliable program. Your code is functional, but there are a few things to note.



First up, the RuntimeException is not a good error type to return, use an IllegalArgumentException instead (because it is an illegal argument). Note that IllegalArgumentException extends RuntimeException so it does not need to be explicitly checked/thrown.



Next, you should validate inputs before using the values - using a "Guard Clause". While your code technically does that, the logic looks like the validation is done after the hours are updated.



Finally, error messages should give the user/programmer an indication of what's needed to fix the problem. Your message should be more useful.



So, all things considered, I would do the code as:



private void setHours(int newHours) 
if (newHours < 0)
throw new IllegalArgumentException("Input hours must be positive value: " + newHours);

hours = newHours;






share|improve this answer























  • "Invalid positive hours value" for a negative value?
    – Sharon Ben Asher
    Jan 15 at 15:39










  • @SharonBenAsher - Yeah, maybe it's not expressed well, but I try to have error messages that express what the value should be, and then what the value is. The hours is expected to be positive, but the value supplied is negative. I'm part of a team/community where the above message would make sense because it's a "common practice", but I can see the confusion.
    – rolfl♦
    Jan 15 at 15:41










  • why not "value must be positive"?
    – Sharon Ben Asher
    Jan 15 at 15:44










  • Sure, changed ;-)
    – rolfl♦
    Jan 15 at 15:54






  • 2




    Aren't these also called guard clauses? Perhaps you could mention that :D
    – Koekje
    Jan 15 at 19:31

















up vote
2
down vote













Adding to the great answer of rolfl, should you do input validation and use exceptions to guard against invalid arguments, I'd say it is really important to document those. RuntimeExceptions are generally not visible from the method declaration. So for example:



/**
* Sets the hours to the given value.
*
* @param newHours the new value for the hours
* @throws IllegalArgumentException when @code newHours is negative
*/
public void setHours(int newHours)
....






share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f185145%2fsetter-error-checking%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    9
    down vote



    accepted










    Input validation is a critical aspect of any reliable program. Your code is functional, but there are a few things to note.



    First up, the RuntimeException is not a good error type to return, use an IllegalArgumentException instead (because it is an illegal argument). Note that IllegalArgumentException extends RuntimeException so it does not need to be explicitly checked/thrown.



    Next, you should validate inputs before using the values - using a "Guard Clause". While your code technically does that, the logic looks like the validation is done after the hours are updated.



    Finally, error messages should give the user/programmer an indication of what's needed to fix the problem. Your message should be more useful.



    So, all things considered, I would do the code as:



    private void setHours(int newHours) 
    if (newHours < 0)
    throw new IllegalArgumentException("Input hours must be positive value: " + newHours);

    hours = newHours;






    share|improve this answer























    • "Invalid positive hours value" for a negative value?
      – Sharon Ben Asher
      Jan 15 at 15:39










    • @SharonBenAsher - Yeah, maybe it's not expressed well, but I try to have error messages that express what the value should be, and then what the value is. The hours is expected to be positive, but the value supplied is negative. I'm part of a team/community where the above message would make sense because it's a "common practice", but I can see the confusion.
      – rolfl♦
      Jan 15 at 15:41










    • why not "value must be positive"?
      – Sharon Ben Asher
      Jan 15 at 15:44










    • Sure, changed ;-)
      – rolfl♦
      Jan 15 at 15:54






    • 2




      Aren't these also called guard clauses? Perhaps you could mention that :D
      – Koekje
      Jan 15 at 19:31














    up vote
    9
    down vote



    accepted










    Input validation is a critical aspect of any reliable program. Your code is functional, but there are a few things to note.



    First up, the RuntimeException is not a good error type to return, use an IllegalArgumentException instead (because it is an illegal argument). Note that IllegalArgumentException extends RuntimeException so it does not need to be explicitly checked/thrown.



    Next, you should validate inputs before using the values - using a "Guard Clause". While your code technically does that, the logic looks like the validation is done after the hours are updated.



    Finally, error messages should give the user/programmer an indication of what's needed to fix the problem. Your message should be more useful.



    So, all things considered, I would do the code as:



    private void setHours(int newHours) 
    if (newHours < 0)
    throw new IllegalArgumentException("Input hours must be positive value: " + newHours);

    hours = newHours;






    share|improve this answer























    • "Invalid positive hours value" for a negative value?
      – Sharon Ben Asher
      Jan 15 at 15:39










    • @SharonBenAsher - Yeah, maybe it's not expressed well, but I try to have error messages that express what the value should be, and then what the value is. The hours is expected to be positive, but the value supplied is negative. I'm part of a team/community where the above message would make sense because it's a "common practice", but I can see the confusion.
      – rolfl♦
      Jan 15 at 15:41










    • why not "value must be positive"?
      – Sharon Ben Asher
      Jan 15 at 15:44










    • Sure, changed ;-)
      – rolfl♦
      Jan 15 at 15:54






    • 2




      Aren't these also called guard clauses? Perhaps you could mention that :D
      – Koekje
      Jan 15 at 19:31












    up vote
    9
    down vote



    accepted







    up vote
    9
    down vote



    accepted






    Input validation is a critical aspect of any reliable program. Your code is functional, but there are a few things to note.



    First up, the RuntimeException is not a good error type to return, use an IllegalArgumentException instead (because it is an illegal argument). Note that IllegalArgumentException extends RuntimeException so it does not need to be explicitly checked/thrown.



    Next, you should validate inputs before using the values - using a "Guard Clause". While your code technically does that, the logic looks like the validation is done after the hours are updated.



    Finally, error messages should give the user/programmer an indication of what's needed to fix the problem. Your message should be more useful.



    So, all things considered, I would do the code as:



    private void setHours(int newHours) 
    if (newHours < 0)
    throw new IllegalArgumentException("Input hours must be positive value: " + newHours);

    hours = newHours;






    share|improve this answer















    Input validation is a critical aspect of any reliable program. Your code is functional, but there are a few things to note.



    First up, the RuntimeException is not a good error type to return, use an IllegalArgumentException instead (because it is an illegal argument). Note that IllegalArgumentException extends RuntimeException so it does not need to be explicitly checked/thrown.



    Next, you should validate inputs before using the values - using a "Guard Clause". While your code technically does that, the logic looks like the validation is done after the hours are updated.



    Finally, error messages should give the user/programmer an indication of what's needed to fix the problem. Your message should be more useful.



    So, all things considered, I would do the code as:



    private void setHours(int newHours) 
    if (newHours < 0)
    throw new IllegalArgumentException("Input hours must be positive value: " + newHours);

    hours = newHours;







    share|improve this answer















    share|improve this answer



    share|improve this answer








    edited Jan 15 at 20:21


























    answered Jan 15 at 15:37









    rolfl♦

    90.2k13186390




    90.2k13186390











    • "Invalid positive hours value" for a negative value?
      – Sharon Ben Asher
      Jan 15 at 15:39










    • @SharonBenAsher - Yeah, maybe it's not expressed well, but I try to have error messages that express what the value should be, and then what the value is. The hours is expected to be positive, but the value supplied is negative. I'm part of a team/community where the above message would make sense because it's a "common practice", but I can see the confusion.
      – rolfl♦
      Jan 15 at 15:41










    • why not "value must be positive"?
      – Sharon Ben Asher
      Jan 15 at 15:44










    • Sure, changed ;-)
      – rolfl♦
      Jan 15 at 15:54






    • 2




      Aren't these also called guard clauses? Perhaps you could mention that :D
      – Koekje
      Jan 15 at 19:31
















    • "Invalid positive hours value" for a negative value?
      – Sharon Ben Asher
      Jan 15 at 15:39










    • @SharonBenAsher - Yeah, maybe it's not expressed well, but I try to have error messages that express what the value should be, and then what the value is. The hours is expected to be positive, but the value supplied is negative. I'm part of a team/community where the above message would make sense because it's a "common practice", but I can see the confusion.
      – rolfl♦
      Jan 15 at 15:41










    • why not "value must be positive"?
      – Sharon Ben Asher
      Jan 15 at 15:44










    • Sure, changed ;-)
      – rolfl♦
      Jan 15 at 15:54






    • 2




      Aren't these also called guard clauses? Perhaps you could mention that :D
      – Koekje
      Jan 15 at 19:31















    "Invalid positive hours value" for a negative value?
    – Sharon Ben Asher
    Jan 15 at 15:39




    "Invalid positive hours value" for a negative value?
    – Sharon Ben Asher
    Jan 15 at 15:39












    @SharonBenAsher - Yeah, maybe it's not expressed well, but I try to have error messages that express what the value should be, and then what the value is. The hours is expected to be positive, but the value supplied is negative. I'm part of a team/community where the above message would make sense because it's a "common practice", but I can see the confusion.
    – rolfl♦
    Jan 15 at 15:41




    @SharonBenAsher - Yeah, maybe it's not expressed well, but I try to have error messages that express what the value should be, and then what the value is. The hours is expected to be positive, but the value supplied is negative. I'm part of a team/community where the above message would make sense because it's a "common practice", but I can see the confusion.
    – rolfl♦
    Jan 15 at 15:41












    why not "value must be positive"?
    – Sharon Ben Asher
    Jan 15 at 15:44




    why not "value must be positive"?
    – Sharon Ben Asher
    Jan 15 at 15:44












    Sure, changed ;-)
    – rolfl♦
    Jan 15 at 15:54




    Sure, changed ;-)
    – rolfl♦
    Jan 15 at 15:54




    2




    2




    Aren't these also called guard clauses? Perhaps you could mention that :D
    – Koekje
    Jan 15 at 19:31




    Aren't these also called guard clauses? Perhaps you could mention that :D
    – Koekje
    Jan 15 at 19:31












    up vote
    2
    down vote













    Adding to the great answer of rolfl, should you do input validation and use exceptions to guard against invalid arguments, I'd say it is really important to document those. RuntimeExceptions are generally not visible from the method declaration. So for example:



    /**
    * Sets the hours to the given value.
    *
    * @param newHours the new value for the hours
    * @throws IllegalArgumentException when @code newHours is negative
    */
    public void setHours(int newHours)
    ....






    share|improve this answer

























      up vote
      2
      down vote













      Adding to the great answer of rolfl, should you do input validation and use exceptions to guard against invalid arguments, I'd say it is really important to document those. RuntimeExceptions are generally not visible from the method declaration. So for example:



      /**
      * Sets the hours to the given value.
      *
      * @param newHours the new value for the hours
      * @throws IllegalArgumentException when @code newHours is negative
      */
      public void setHours(int newHours)
      ....






      share|improve this answer























        up vote
        2
        down vote










        up vote
        2
        down vote









        Adding to the great answer of rolfl, should you do input validation and use exceptions to guard against invalid arguments, I'd say it is really important to document those. RuntimeExceptions are generally not visible from the method declaration. So for example:



        /**
        * Sets the hours to the given value.
        *
        * @param newHours the new value for the hours
        * @throws IllegalArgumentException when @code newHours is negative
        */
        public void setHours(int newHours)
        ....






        share|improve this answer













        Adding to the great answer of rolfl, should you do input validation and use exceptions to guard against invalid arguments, I'd say it is really important to document those. RuntimeExceptions are generally not visible from the method declaration. So for example:



        /**
        * Sets the hours to the given value.
        *
        * @param newHours the new value for the hours
        * @throws IllegalArgumentException when @code newHours is negative
        */
        public void setHours(int newHours)
        ....







        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Jan 15 at 19:39









        Koekje

        1,017211




        1,017211






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f185145%2fsetter-error-checking%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Chat program with C++ and SFML

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            Will my employers contract hold up in court?