tags:

views:

61

answers:

2

I have build a generic datacontainer and now I want to manipulate data depending on their type. However, I get an incompatable types warning. What am I doing wrong?

Type _Value;
public void set(Type t) throws Exception {
   if (_Value instanceof Integer
     && t instanceof Integer) {
       _Value = (((Integer) t
         - _MinValue + getRange())
            % getRange()) + _MinValue;
         }
       else if (_Value instanceof Boolean
         && t instanceof Boolean) {
 _Value = t;
            }
       else throw new Exception("Invalid type");
  }
+2  A: 

You aren't following the Sun Java coding standards, for one. Variable names should begin with a lower case letter. My personal taste would say lose that leading underscore as well. If you must spell out that a variable is a class member, use "this.". IDEs are smart enough to display them. That ancient C++ convention of denoting class member variables with a leading underscore might be a good idea when all you have is a text editor that can't do text highlighting, but that's not the case today.

As for your "instanceof" constructs, that goes against every object-oriented principle there is.

You can't embed operations that are type dependent inside the container itself. My advice would be to write the container and externalize the operations on the items it contains into an Iterator, Functor, or Visitor of some kind. You can use the generic type to specify the type without having to resort to "instanceof".

It's a much cleaner design: no "instanceof" and proper separation of concerns.

duffymo
A: 

If Type is java.reflect.Type then it can never be an Integer or a Boolean. It's just an interface for objects that hold information about types, classes, interfaces, they are not actually objects of that type, class, interface. And you should be getting errors, not warnings. Maybe you should be using Object instead of Type, or are you trying to do something reflectively?

Andrei Fierbinteanu