Tony
Tony

Reputation: 1155

Catching an error at compile rather than run time in Java

I had a method (call it foo) like this: public void foo (String parm) I know have occasion to sometimes require an Integer which I will convert to a String (not just "" + x, it is more complicated than that and you cannot determine the String value just by looking at the int value. The int value will be used as an index.

So now I do this:

public void foo(Object obj) {
 if (obj instanceof String) {
     ...
 } else if (obj instanceof Integer) {
     ...
 } else // some sort of error
}

which will not catch an error at compile time if you do something like:

foo(new Date());

Is there a way I can catch this at compile time (other than making two separate methods public void foo(Integer x) and public void foo (String str)?

Upvotes: 2

Views: 108

Answers (3)

azahar
azahar

Reputation: 48

It will not catch an error because there isn't an error.
You are allowing an object to be passed as an argument, and like you know, all objects are based off the class Object, so new Date() is an instance of Object.
I would recommend creating the two methods, as this would keep the code cleaner.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

I would even go one step further; not only should you have two methods (one taking a string, one taking an Integer) ... you should give those methods two different names.

You want to follow SRP (single responsibility principle). Any element (classes, methods) in your code should be responsible for exactly "one thing".

And the names of your classes and methods should make it very clear what they are supposed to do. And in that sense, it would seem awkward that you have two methods with the same name and different parameters. Because, in essence, those two methods would be doing different things. So - give them names that say what they really do.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

Sure, build overloaded versions of foo:

foo(String obj)

foo(Integer obj)

and remove the general one. Have those call a general (private) _foo(Object obj) if you must.

Upvotes: 4

Related Questions