views:

129

answers:

4

Hi,

I want to call a validation method inside a shared gwt class that i have created to store the validation logic (for user entered text fields)

 suggestBox.addKeyUpHandler( new KeyUpHandler() {
            public void onKeyUp(KeyUpEvent event) {
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { 
                    String boxText = suggestBox.getText();
                    if (new FieldVerifier().validUserName(boxText)) { //inner class used to instanciate the FieldVerifier class where validUserName(String ..) lives

now i could do this with a properly instanciated FieldVerifier class (rather than a inner class as above) - or indeed, perhaps make it abstract. but i have the suspicion i am missing something (ie. must be an elegant way of doing it).

looked on google code search, but didnt come across anything particularly helpful..

+1  A: 

I'm not sure I got it, but try:

FieldVerifier.this.validUserName(boxText);
Bozho
A: 

i could do this with a properly instanciated FieldVerifier class (rather than a inner class as above)

Your use of FieldVerifier is not an inner class. It is indeed 'properly instanciated'. KeyUpHandler is an example of an anonymous inned class.

mR_fr0g
A: 

If you made the validUserName() method of FieldVerifier static then you could just call FieldVerifier.validUerName() directly, without having to instantiate a FieldVerifier object. If it's a fairly small class, though, the overhead of creating a new object is likely to be minimal.

jackbot
I did start with making it static - but eclipse seemed to suggest i should only 'call it in a static context' so i wasnt sure if this was a wonky practice.it seems though (from the comments above) that instantiating objects for uses such as this seems to be OK in java?
flyingcrab
If the FieldVerifier class isn't consuming a bunch of resources in its constructor (say if it's just initialising a few variables or something) then you're not going to notice anything by instantiating a new object just to call `validUserName()` so it's fine to do that.
jackbot
A: 

If I understand what you're trying to do, I would make validUserName() a static method. It doesn't appear to require or change any state; you just pass in something, run some verification logic on it, then return a boolean. This case is when you want to start looking at using statics.

MattGrommes