What you call a robust method?

in my project X, i am writing a method whose parameter should not be null, like the following:
public class MyClass {
  public void myMethod(MyObject obj) {
    if (obj!=null) {
      // do something.
    return;
}In order to make my method robust, i have several choices, but i dont know which coding style is the best.
1, do not check obj, and if it is null, NullPointerException will be thrown out automatically when i use the null object.
2, check the obj and throw out a runtime exception (NullPointerException or IllegalArgumentException) myself, like this:
public void myMethod(MyObject obj) {
  if (obj==null) {
    throw new NullPointerException("MyObject cannot be null.");
  // do something...
  return;
}3, check the obj and throw out a self-defined exception, like this:
public void myMethod(MyObject obj)
throws MyException {
  if (obj==null) {
    throw new MyException("MyObject cannot be null.");
  // do something...
  return;
}At my point of view, the first one cares nothing about the legality of its parameter, and thus is not robust enough. The second one is silly because i have to add the same code at the beginning of all my methods. The third one is even sillier because i have not only to add the same code at the beginning of all my methods, but also to catch exception everytime i call them...
So...who can give me some advices?
thanks.

This is not a problem to do with robustness, this is a reliabilityproblem.
Reliability means that the operation behaves in a predictable manner regardless of the environment.
Robustness means being able to act in a predictable manner regardless of the circumstances without causing unexpected exceptional conditions.
If you leave out the null reference check your method will act reliably in that a NullPointerException will be thrown at the point where the instance is referenced.
To make your method robust you have to be active in what you do, in this case throwing a NullPointerException as a result of the check for null makes sense as you control the message in the exception rather than relying on the default one.
Throwning an IllegalArgumentException is not the correct thing to do. The problem here is that there is no argument passed here rather null (no value). If you do further checks in the method for legal values and then your method considers the value passed to be outside of constrainst then throwing IllegalArgumentException is the correct thing to do.
Creating your own class of Exception or RuntimeException for this purpose is a decision you have to make for yourself. If the argument checks are supposed to be rigorous then checked exceptions (subclasses of the Exception class) should be used to force callers of your method to handle the potentional exceptional condition. In this case it makes sense to create and use your own Exception class. If they are not rigorous then NullPointerException and IllegalArgumentException are probably sufficient.
You should look at the Tutorials here for help on how the JavaBeans framework for property change support works as well, it provides some helpful insights into this problem.

Similar Messages

  • Can you call a class method as an RFC function

    Hi
    I would like to know whether it is possible to instantiate a class in another system via RFC and then call a method eg. cl_abap_typedescr=>describe_by_name, of that class in the other system like you can with an RFC enabled function.
    Thanks
    Faaiez

    Its not possible to call a method like RFC.
    What you could do is write a RFC and within that instantiate the class and call desired method .
    And now you can call this RFC from the other system.
    Regards
    Raja

  • I was so excited about apple pay and now setting it up hoping to replace a wallet within next year or so and then boom 8 cards you are done! Come on Apple 8 cards is that what you call wallet replacement?

    I was so excited about apple pay and now setting it up and boom 8 cards and you are done is that the wallet replacement they thought they'll do? really? I mean most people have 10-15 cards at least and I am, well because of my side business I have lots so 8 is nothing to me!

    Not sure what you are saying.  I was able to very quickly set up my AmEx card - no problems at all.  For my PNC and Macy's cards, companies still working on being ApplePay-ready. 
    It will happen, just not as fast as we might like, but I think it is going to be fabulous. 

  • Can you call a public method in a custom skin?

    I made a custom skin for a button. In the skin there's a method to change some text. Can I call this method from my application?
    I get an error message when I try to call it like a normal object:
    uploadNewBtn.setNewPhotosLabel("test");
    Error 1061: Call to a possibly undefined method setNewPhotosLabel through a reference with static type spark.components:Button.

    You said it yourself, the method is inside skin not the HostComponent (button in your case). Obviously you cannot call it.
    There is a skin protperty inside SkinnableComponent, but it is typed as UIComponent so you still cannot cal it on the skin without casting. I don't know your use case, so in theory you either push the text/label from the host towards the skin, or you listen or bind from the skin on the hostcomponent.
    C

  • What you call this

    If i have 2 seprate classes in two different packages
    package in;
    public class Animal {
    public Animal() {
    //accessible only throw inhertance or throw the dot operator if the accessing class is in the same package
    protected void eat()
    System.out.println("animal");
    package out;
    public class Horse extends in.Animal {
    public Horse() {
    * Override the protected method eat
    protected void eat()
    System.out.println("horse");
    package in;
    import out.Horse;
    public class BarnHorse
    public BarnHorse()
    Animal a=new Horse();
    //calling polymorphiclly the eat method in the horse class
    a.eat();
    the code compiles fine and calles the Horse version of eat and outputs "horse" although the calling class shouldn't know anything about the Horse eat version.

    SunFred wrote:
    GONO wrote:
    the eat() in the horse class is protected this means that only classes inside the package or classes that inherits the horse class could access this methodWrong. protected means only the class itself and subclasses. "Classes inside the package" is the default access modifier.No, he was right.
    Protected is the declaring class, subclasses of the declaring class, and classes in the same package as the declaring class. Else the code woudn't have compiled.
    [JLS 6.6.1 Determining Accessibility|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]:
    Otherwise, if the member or constructor is declared protected, then access is permitted only when one of the following is true:
    Access to the member or constructor occurs from within the package containing the class in which the protected member or constructor is declared.
    Access is correct as described in �6.6.2.

  • But in ipad page there is no ipad 3 and ipad 4 ithink that ipad3 is that wahat you call the ipad 2 and the ipad 4 is the ipad 3 right

    but in ipad page there is no ipad 3 and ipad 4 ithink that ipad3 is that what you call the ipad 2 and the ipad 4 is the ipad 3 right

    iPad 3 vs iPad 4
    http://www.digitaltrends.com/mobile/ipad-3-vs-ipad-4/

  • How do you call a method from  another class without extending as a parent?

    How do you call a method from another class without extending it as a parent? Is this possible?

    Why don't you just create an instance of the class?
    Car c = new Car();
    c.drive("fast");The drive method is in the car class, but as long as the method is public, you can use it anywhere.
    Is that what you were asking or am I totally misunderstanding your question?
    Jen

  • What class called my method?

    I have tried using the StringWriter and the printStackTrace() methodology for finding out the name of the method that actually called my class and it works fine. But the problem is that the execution time is too high (abt 70msec). I need a better and more efficient way of finding this out.
    Does someone have an idea of how to do this?
    Regards,
    Manoj Rathod.

    Ok, this was my test code:
        public class MethodTrace {
            public static void main (String[] args) {
                method3(false);
            public static void method1 (boolean stop) {
                StackTraceElement e[] = (new Throwable()).getStackTrace();
                System.out.println("method1: called by " + e[1].getMethodName());
                if (!stop) method3(false);
            public static void method2 (boolean stop) {
                StackTraceElement e[] = (new Throwable()).getStackTrace();
                System.out.println("method2: called by " + e[1].getMethodName());
                if (!stop) method1(true);
            public static void method3 (boolean stop) {
                StackTraceElement e[] = (new Throwable()).getStackTrace();
                System.out.println("method3: called by " + e[1].getMethodName());
                if (!stop) method2(false);
        };And this was the output:
        method3: called by main
        method2: called by method3
        method1: called by method2As for the speed, I don't know. It's cleaner than using printStackTrace(), and I would think it would be faster. But I'm not sure.
    Why do you need to know the calling method, though? Perhaps there is some other, faster way to do what you want to do that doesn't have to use any stack tracing stuff at all.
    Or maybe you could just call the method, passing the name of the calling method as a String parameter:
        public void excellent (String caller) {
            System.out.println("Called by " + caller);
        public void superb () {
            excellent("superb");
        public void hard () {
            excellent("hard");
        };Lemme know if you find out anything interesting.
    Jason Cipriani
    [email protected]
    [email protected]

  • EL - How do you call a method that requires a parameter

    How do you call a method that requires a parameter
    In scriplet code here is what I am trying to do
    <%= car.getDefaultColor(car.getCarType()) %>
    How do I do this in EL
    Here is my guess (it generates the Exception described below)
    ${car.defaultColor(car.carType)}
    Here is the Exception I am getting:
    javax.servlet.ServletException: <h3>Validation error messages from tag library c</h3>tag = 'out' / attribute = 'value': An error occurred while parsing custom action attribute "value" with value "${car.defaultColor(car.carType)}": Encountered "(", expected one of ["}", ".", ">", "gt", "<", "lt", "==", "eq", "<=", "le", ">=", "ge", "!=", "ne", "[", "+", "-", "*", "/", "div", "%", "mod", "and", "&&", "or", "||"]
    Any Ideas?
    P.S. If it matters to you, I am using JSTL 1.0 and the code snippets above are actually within the value attribute of a <c:out value="" /> statement.

    How do you call a method that requires a parameter
    In scriplet code here is what I am trying to do
    <%= car.getDefaultColor(car.getCarType()) %>
    How do I do this in ELYou don't. EL is very strict in method signatures. All get methods must be public Type getProperty(void); And all set methods must be public void setProperty(Type t);
    So you will have to re-work your Bean so it does not need an argument to the get method (getDefaultColor()). Since you are calling another method out of car, you might re-write the getDefaultColor method as such:
      public Object getDefaultColor() {
        CarType ct = this.getCarType();
        //then do other stuff
      }If that isn't suitable, then provide a helper method that is used to set the current car type and then call the getDefaultColor:
      private CarType curCarType;
      public void setCurrentCarType(CarType ct) { curCarType = ct; }
      public Object getDefaultColor() {
        if (curCarType == null) throw new IllegalStateException("CarType must be set before getting color");
        //normal work using curCarType
    <c:set target="${car}" property="currentCarType" value="${car.carType}"/>
    <c:out value="${car.defaultColor}"/>It is better to do as little of the data manipulation (setting up the car type) in the JSP as possible, so the first option is better than the second. Also better then the second would be to set the current car type in a servlet or data access object (or wherever) from which your retreive the car to begin with. Manipulatig it in the JSP itself should be your last resort (to keep as much business logic out of the JSP as possible).
    Here is my guess (it generates the Exception
    described below)
    ${car.defaultColor(car.carType)}
    Here is the Exception I am getting:
    javax.servlet.ServletException: <h3>Validation error
    messages from tag library c</h3>tag = 'out' /
    attribute = 'value': An error occurred while parsing
    custom action attribute "value" with value
    "${car.defaultColor(car.carType)}": Encountered "(",
    expected one of ["}", ".", ">", "gt", "<", "lt",
    "==", "eq", "<=", "le", ">=", "ge", "!=", "ne", "[",
    "+", "-", "*", "/", "div", "%", "mod", "and", "&&",
    "or", "||"]
    Any Ideas?
    P.S. If it matters to you, I am using JSTL 1.0 and
    the code snippets above are actually within the value
    attribute of a <c:out value="" /> statement.

  • What do you call this basic technique?

    Request: Is there a name for the technique I'm using below, because I
    know I've seen it and done it before.
    Context: I'd like to allow the user to resize images, while preserving
    their width:height aspect ratio. My GUI has a pair of JSpinners, for width
    and height, and when one is adjusted, the other should change.
    Example: if the aspect ratio is 2:1, setting the width spinner to 201
    should cause the height spinner to change to 100 (I truncate), whilst setting
    the height spinner to 100 should cause the width spinner to change to 200.
    But: I don't want those reactions to cascade: from the example, if the
    user sets the width spinner to 201, the height spinner should change to 100,
    but that is where it should stop -- the width spinner shouldn't itself react
    and change to 200.
    My solution: I'm a fan of fixing it in the model, and here is my tweak for
    SpinnerNumberModel: public class SafeSpinnerNumberModel extends SpinnerNumberModel {
         public SafeSpinnerNumberModel(int value, int minimum, int maximum, int stepSize) {
             super(value, minimum, maximum, stepSize);
         public void setValue(Object value) {
             if (!inSetValue) {
                 inSetValue = true;
                 super.setValue(value);
                 inSetValue = false;
         private boolean inSetValue;
    In my code, there are two JSpinners (with SafeSpinnerNumberModels),
    and each model has a ChangeListener that reacts by adjusting the other model.
    The flag stops the potential feedback loop.
    So, again, what would you call this technique?
    Thanks,
    BDLH

    Me too. And they love all those visual little
    thingies so much: ooh, when
    the number is positive it's displayed in black,
    otherwise it's red. I'm a
    genius! No lemme put 90 percent profit in here, just
    for the "what-if"
    question part. Yay! It's black!You should see some of the spreadhseets we have here. Risk management, process compliance, earned value management... I have no idea what any of this is, but its all thousands of rows of red-green-yellow, telling who's not doing any work. And if you change one value all the colors change all over the place. I bet they have Tetris encoded in there.
    I attempted to finish my bookkeeping for Q3 last
    Sunday but I was
    distracted by myself attempting to do the Towers of
    Hanoi puzzle
    using Excel. I managed to make it work, but it was so
    awful (using
    additional cells etc) I deleted it all. I still have
    to finish up Q3 ...Hmm, I believe I'll start short-selling JosAH Industries ;-)

  • How do you call a java class from the main method in another class?

    Hi all,
    How do you call a java class from the main() method in another class? Assuming the two class are in the same package.
    Thanks
    SI
    Edited by: okun on May 16, 2010 8:40 PM
    Edited by: okun on May 16, 2010 8:41 PM
    Edited by: okun on May 16, 2010 8:47 PM

    georgemc wrote:
    To answer your impending question, either the method you're calling has to be static, or you need an instance of that other class to invoke it against. Prefer the latterAnd to your impending question after that: no, don't use the Singleton pattern.

  • What name do you call the Flash Professional CS IDE program application thing?

    Everybody continues to use different names to refer to the application from Adobe that Wikipedia calls
    "The Adobe Flash Professional multimedia authoring program". I find myself using different names every time in discussions with my colleagues, though, since the term "authoring tool" doesn't really resonate with anyone. And it's rarely used as an "IDE", amongst any of my programmer colleagues.
    What do you call it?

    "unfortunately, "flash" is used to describe many different thing even by those who well versed on all things adobe. "
    I wasn't answering for them.

  • What does it mean when you call someone and it goes straight to the 3 beeps to mean cancelled

    hi
    what does it mean when you call someone and it goes straight to the 3 beeps to mean cancelled? this phone doesnt even ring, it just goes straight to the BEEP-BEEP-BEEP, its an iphone 4 and on IOS7 and it was ringing eailier on in the day when i spoke to this person. it wouldn't mean i have been blocked would it?
    what does all this mean?
    thanks
    mrredrunner100

    i got my friend to message this person to see if they had the same problem, and the message went through and i think he got a reply, and all of a sudden this has started to work again (calls only) but apparently none of my messages went through that i have sent since the block activated. and they still havent even though there working again, and "apparently" a message was sent to me at 9pm today and it has never arrived. so imessage and text still isnt working, before i go asking this person about this, is this a genuine block or is there a phone problem?

  • What do you call those cool little icons?

    you know the ones... i cant figure out what there called or where to find a site that has a bunch of them for use.
    if you dont know what i mean theres an arch linux one and a firefox one at the bottom of dibbles page (first ones i found just now) http://dtw.jiwe.org/news.php

    cactus wrote:
    Penguin wrote:phrakture, what *in the hell* is that avatar?
    The "house keeping" robot from FLCL (fooly cooly).
    naw but he's red in the picture.... which means ass-kickage (... or the main character's brother / the man he will become ... depending on how deeply you'd like me to analyze it)

  • What's the chain of methods called for painting components?

    Hi, I'm trying to find out at what point components are painted within a container, as in what methods are being called for that component to be rendered to the graphics context.
    I've tried watching for calls going to paint, paintAll and paintComponents, but if a component has been added to a container it seems that even if I override all of those methods of the container the components that have been added still get displayed.
    So I suppose I have two questions:
    * - What is the chain of methods called when a container is told to paint/repaint itself?
    * - What are the purpose of paintAll & paintComponents, I can't find anything that actually uses these calls.
    Thanks in advance,
    L

    Well it seems that the paint method of the component is being called from sun.awt.RepaintArea.paint(...) which itself is being kicked off from handling an event that's been thrown.
    That's clearer now....but has anyone seen when paintAll, paintComponents or the printXXX counterparts have actually been called by a part Sun's code? I can see how they (Sun) would advocate a practice lke this, but it would seem kinda lame for them to suggest it and then for them not to use it themselves.....that's why I think there's probably something in the JRE that does call these methods at sometime....can anyone cast some light on this?

Maybe you are looking for

  • How to avoid the run time error  "java.lang.OutOfMemoryError"

    hi i have written a code to read a txt file ,i used FileReader to read a file . the code is working well for small txt files. but when i tried to read a large file(greater than 2MB), a run time error called "java.lang.OutofMemoryError" appeared . plz

  • Development Configuration import failed: class java.io.UTFDataFormatExc

    Hello, after importing the SAP ESS/MSS source I tried to import the development configuration as described in "JDI Cookbook for ESS Customers - Modification guide for ESS". But when I confirm the selection: ESSTrack -> 1.0 -> ESSTrack_dev with the 'N

  • Is there a way to move Bridge ratings to a different machine?

    I'm working from home next week and I need to sort through hundreds of photos for a project. I wanted to use Bridge's ratings system. But then I need to move all of this back to work the following week. Is there some kind of Bridge file I can copy an

  • PRICE ERROR IN SALES ORDER

    Hi Gurus, I want the system to lock the variation in price while creating sales order. Or can have some % variation. Say suppose mat price is 10 rs, it can vary betwn 7 to 12 or system should directly suggest me the price for material. Where can I ge

  • Best Ink Jet Printer

    What would be the best ink jet printer to hook to a airport extreme router with both Mac's and Pc's hooked to it. No need for high end printing mostly black & white word documents and a few colour pages for school projects.