Java coding style - calling a method inside a class - java

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..

I'm not sure I got it, but try:
FieldVerifier.this.validUserName(boxText);

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.

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.

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.

Related

How to get access to functions from within more than one class

I have one main class that executes functions written in another class, let's call it "code" class. Now I have created one more "code" class and I want to call the functions there as well. I don't want to create more than one object in my main class, as I have constructors in both code classes and creating multiple objects will screw with my tests. I can't extend more than one class as I know. Is there any other solution for me to call the functions in the second code class without creating an object of that class?
ReqOrderImpMain d = new ReqOrderImpMain();
//Request Order Import - First page function calling
d.page();
d.checkLoginAndProceed();
/*d.output();
d.correctORNumber();
d.createNewOrder();
d.checkOrder();
d.checkSend();
d.quantityCheck();
d.restMatWithQuantity();
d.submit();
d.quit();*/
//Request Order Import - Rest of the pages function calling ??.output(); ??.select();
}
Functions with d. are called from the first code class. I want to be able to call the ??.function() ones.
If you want to call functions (methods) in a class without creating an instance of that class, you need to create static methods.
public class ClassWithStaticMethod {
public static void staticMethod() {
...
}
}
You can call the method like this (no instance required):
ClassWithStaticMethod.staticMethod();
It sounds like you may have backed yourself into a corner with your tests though, and may want to consider redesigning your code / tests. I don't think test code should ever decide how your actual code looks or works.
Since you want only one object, but use the results of the functions of your second class, you have to either assign them to your first object (1) (via some attributes) or just let them run on some input (2)(in case they are void).
1) firstCodeClassObject.someAttribute = SecondCodeclass.doSomeMethod(inputType input);
2) SecondCodeclass.doSomeMethod(inputType input);
Ok, found the answer. I just have to initialize driver in main class, then create a constructor and pass the driver reference to the other two classes.

How should i implement an interface in Java? [Code-Correctness]

First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.

possible to Java override functions at an instance level?

I'm reviewing some Java code written long ago and not being a Java developer, I have a question. I found the following lines in the body of a class. Someone is creating an instance of SearchQueryParameter however there are curly braces following "new SearchQueryParameter" and it appears that someone overrode some functions here.
My questions are the following.
1) Are these functions overwritten at an instance level?
2) Does this language feature have a name?
public static final SearchQueryParameter X_POSTDOC_WORKFLOW_STEP = new SearchQueryParameter(128,"XPOSTDOCWorkflowStep",AdvancedFields.X_EVENT_POSTDOC_WFSTEP,SearchTypes.XEVENT_DOCUMENTS) {
#Override
protected int getFilterType() {
return SEARCH_FILTER;
}
<<snip>>
};
Thanks, mj
Background:
This is called anonymous class. It is a class that extends a non final class or implements a single interface and you're creating a single instance of this class.
Now, to your questions:
1) Are these functions overwritten at an instance level?
No, they are at level class. You have a new subclass of the desired class and this subclass overrides the method. Then, you create a new instance of the subclass.
2) Does this language feature have a name?
Yes, it is anonymous class.
You probably should have done some research on your own first, but that is called an anonymous inner class.
The code creates an instance of an anonymous class (SearchQueryParameter) and then overrides one method in it.
Essentially, it creates something that extends the SearchQueryParameter class and which overrides the getFilterType() method.
Since only one instance of this particular class definition can ever be created (without reflection), the function may appear like it's being overridden at an instance level but is actually getting overridden at the class level (since it may replace the existing definition).
It's called an anonymous class.

Java member object inside class of same type

I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".

Is it possible to see via which child class was a parent's static method called in Java?

A little background first. I am looking into the possibility of implementing Ruby's ActiveRecord in Java as cleanly and succinctly as possible. To do this I would need to allow for the following type of method call:
Person person = Person.find("name", "Mike");
Which would resolve to something like:
ActiveRecord.find(Person.class, "name", "Mike");
The plan is to have Person extend ActiveRecord, which would have a static find method with two parameters (column, value). This method would need to know it was called via Person.find and not another domain class like Car.find and call the find(Class, String, Object) method to perform the actual operation.
The problem I am running into is the finding out via which child class of ActiveRecord the static find method (two param) was called. The following is a simple test case:
public class A {
public static void testMethod() {
// need to know whether A.testMethod(), B.testMethod(), or C.testMethod() was called
}
}
public class B extends A { }
public class C extends A { }
public class Runner {
public static void main(String[] args) {
A.testMethod();
B.testMethod();
C.testMethod();
}
}
Solutions found so far are load-time or compile time weaving using aspectJ. This would involve placing a call interceptor on the testMethod() in A and finding out what signature was used to call it. I am all for load time weaving but the set up of setting this up (via VM args) is a bit complex.
Is there a simpler solution?
Is this at all possible in java or would need to be done in something like groovy/ruby/python?
Would the approach of using something like ActiveRecord.find for static loads and Person.save for instances be better overall?
You cannot override static methods in Java, so any calls to the static method via a subclass will be bound to the base class at compile time. Thus a call to B.testMethod() will be bound to A.testMethod before the application is ever run.
Since you are looking for the information at runtime, it will not be available through normal Java operations.
As others have noted, I don't think the problem is solvable in Java as you pose it. A static method is not really inherited in the same way that a non-static method is. (Excuse me if I'm not using the terminology quite right.)
Nevertheless, it seems to me there are many ways you could accomplish the desired result if you're willing to modify your interface a little.
The most obvious would be to just make the call using the parent class. What's wrong with writing
Person person=(Person)ActiveRecord.find(Person.class, "name", "Mike");
?
Alternatively, you could create an instance of the record type first and then do a find to fill it in. Like
Person person=new Person();
person.find("name", "Mike");
At that point you have a Person object and if you need to know it's class from within a function in the supertype, you just do "this.getClass()".
Alternatively, you could create a dummy Person object to make the calls against, just to let you do the getClass() when necessary. Then your find would look something like:
Person dummyPerson=new Person();
Person realPerson=dummyPerson.find("name", "Mike");
By the way, seems to me that any attempt to have a generic ActiveRecord class is going to mean that the return type of find must be ActiveRecord and not the particular record type, so you'll probably have to cast it to the correct type upon return from the call. The only way to beat that is to have an explicit override of the find in each record object.
I've had plenty of times that I've written some generic record-processing code, but I always avoid creating Java objects for each record type, because that invariably turns into writing a whole bunch of code. I prefer to just keep the Record object completely generic and have field names, indexes, whatever all be internal data and names. If I want to retrieve the "foo" field from the "bar" record, my interface will look something like this:
Record bar=Record.get(key);
String foo=bar.get("foo");
Rather than:
BarRecord bar=BarRecord.get(key);
String foo=bar.getFoo();
Not as pretty and it limits compile-time error-checking, but it's way less code to implement.
You would not do this in Java. You would probably do something more like:
public interface Finder<T, RT, CT>
{
T find(RT colName, CT value);
}
public class PersonFinder
implements Finder<Person, String, String>
{
public Person find(String nameCol, String name)
{
// code to find a person
}
}
public class CarFinder
implements Finder<Car, String, int>
{
public Person find(String yearCol, int year)
{
// code to find a car
}
}
It is possible but it is expensive.
If you can find a way to only call it once then you're set.
You can create a new exception and look at the first frame and then you'll know who call it. Again the problem is it is not performant.
For instance with this answer it is possible to create a logger like this:
class MyClass {
private static final SomeLogger logger = SomeLogger.getLogger();
....
}
And have that logger create a different instance depending on who called it.
So, in the same fashion, you could have something like:
class A {
public static void myStatic() {
// find out who call it
String calledFrom = new RuntimeException()
.getStackTrace()[1].getClassName();
}
}
This is fine for a one time initialization. But not for 1,000 calls. Although I don't know if a good VM may inline this for you.
I would go for AspectJ path.
My theory on this, having built something similar, is to use a code generation strategy to create a delegate for each class which contains the method. You can't have quite as much hidden code in Java, it's probably not worth the effort as long as you generate something reasonable. If you really want to hide it, you could do something like...
public class Person extends PersonActiveRecord
{
}
//generated class, do not touch
public class PersonActiveRecord extends ActiveRecord
{
public Person find(Map params)
{
ActiveRecord.find(Person.class, params);
}
}
But it tends to mess up your inheritance hierarchy too much. I say just generate the classes and be done with it. Not worth it to hide the find method.
You can do it very manually by creating a hackish constructor.
A example = new B(B.class);
And have the superclass constructor store the class that's passed to it.
I don't think the thrown exception above would work, but if you'd want to ever do something like that without creating an exception...
Thread.currentThread().getStackTrace()
You may be able to do it much more smoothly with meta-programming and javassist.
I suppose you want to implement ActiveRecord in Java. When I decided to do the same, I hit the same problem. This is a hard one for Java, but I was able to overcome it.
I recently released entire framework called ActiveJDBC here:
http://code.google.com/p/activejdbc/
If interested, you can look at sources to see how this was implemented. Look at the Model.getClassName() method.
This is how I solved getting a class name from a static method. The second problem was to actually move all the static methods from a super class to subclasses (this is a cludgy form of inheritance after all!). I used Javassist for this. The two solutions allowed me to implement ActiveRecord in Java completely.
The byte code manipulation originally was done dynamically when classes loaded, but I ran into some class loading problems in Glassfish and Weblogic, and decided to implement static bytecode manipulation. This is done by a http: activejdbc.googlecode.com/svn/trunk/activejdbc-instrumentation/ Maven plugin.
I hope this provides an exhaustive answer to your question.
Enjoy,
Igor

Categories

Resources