How much logic is it "right" to put in a Callable? - java

I'm using callables quite often , and I've stubled upon a question that irritates me:
Lets say that to run function foo() , one needs to do a couple of checks first.
Should you
1. Insert the checks as part of the Callable :
class A implements Callable<Long> {
...
public Long call() {
check1();
check2();
return (run());
}
OR , insert all this logic into another class (ALogic) and use the Callable a mere shell for the executor?
class A implements Callable {
...
public Long call() {
ALogic aLogic = new ALogic();
return (aLogic.run());
}
What do you think are the pro's and con's? What do you usually prefer?

My general advice when implementing callback [Java keyword] interfaces is concentrate on making the [non-Java keyword] interface appropriate for the called type. There generally shouldn't be that much in the anonymous inner class (or whatever), but more than just forwarding call.
Also, it's generally not good to have an object that is constructed and then only has a single method called on it. Make it a static method (which may, perhaps, in turn create an object through a private constructor and run that).

Which do you feel is simpler or clearer?
I suggest you do that.

I usually prefer to simply forward the callback to a private method on the enclosing class. This eliminates the "this" reference that simply points to the anonymous inner class, which is pretty useless.

Related

Am I using instanceof "wrong"?

So in a simple game engine of mine I use an interface "UpdatedGameElement" to signal that an object having that interface has to be updated every frame through an implementation of an update() method.
Now in my "main"(not THE main) class I iterate through a list of GameElement 's and check if these are an instanceof UpdatedGameElement. If this is the case I cast them, and then call .update().
Now the thing is, I just read that using instanceof is usually a sign of bad coding; and in cases where classes are used as markers when they could be easily replaced with a variable, I agree. But I'm not so sure about my case.
I guess I could let the GameElement class implement UpdatedGameElement, and define a standard empty update() method that needs to be overridden to actually do something, but I'm not sure if and why that would be better than what I have now.
What would you say?
Edit: some code from my main class:
public void process()
{
if (active)
{
for (GameElement GE: elements)
{
if (!GE.isToBeRemoved())
{
//Relevant part
if (GE instanceof UpdatedGameElement)
{
((UpdatedGameElement) GE).update();
}
}
else
{
prepareRemoval(GE);
}
}
processRemovals();
}
}
Following the invitation if the OP:
If use of the interface has no other reason than to add a marker plus the update method to GEs, and if the type UGE isn't used except after this single instanceof, then it is a weak reason for having these extra types. ESpecially when the capability of being updated can be extended to all other GEs, where it is just a NOOP.
An abstract method in the base class forces the programmer to decide whether update needs to be coded for a particular subclass. This approach is rather "safe" from a "defensive design" point of view. But, of course, you write more code.
In contrast to the previous technique: If you forget the interface there's no alarm.
Also, if you code a NOOP update method in the base class and rely on programmers' alacrity to override where necessary: convenient, but risky when you forget to do it.
Summarizing: There are a few subtle pro's and con's - not just the instanceof "smell".
Based on your comments you mentioned that GameElement implements UpdatedGameElement, for now GameElement is the only class which is implementing UpdatedGameElement but it could be more in future. Also I hope you are aware that an interface cannot be instantiated thus you cannot create an instance of UpdatedGameElement thus in real the instances are created of the implementing classes of an interface. Thus during runtime when you create an instance of GameElement and assign it to UpdatedGameElement variable, that doesn't mean the instance is of type UpdatedGameElement now, its actually of type GameElement, now suppose that you have one more class implementing XYZElement implements UpdatedGameElement and create instance as below:
UpdatedGameElement ge = new GameElement();
UpdatedGameElement xyze = new XYZElement();
Do you think it good to use instance of check as below, as in either case it will be true and you never know which kind of instance ge and xyze are of.
if(ge instance of UpdatedGameElement)
instead one should always check for if(ge instance of GameElement)
Similarly for if(xyze instance of UpdatedGameElement)
instead one should always check for if(ge instance of XYZElement)
Hope this helps.
I guess I could let the GameElement class implement
UpdatedGameElement, and define a standard empty update() method that
needs to be overridden to actually do something
Yes, you should definitely do it!
Reason: suppose in the future you'll need to implement another "updateable" class that extends UpdatedGameElement - consider the code changes you'll have to do in every place you've used instanceof...

When to use Single method Interfaces in Java

I have seen in many libraries like Spring which use a lot of interfaces with single methods in them like BeanNameAware, etc.
And the implementer class will implement many interfaces with single methods.
In what scenarios does it make sense to keep single method interfaces? Is it done to avoid making one single interface bulky for example ResultSet? Or is there some design standard which advocates the use of these type of interfaces?
With Java 8, keeping the single method interface is quite useful, since single method interfaces will allow the usage of closures and "function pointers". So, whenever your code is written against a single method interface, the client code may hand in a closure or a method (which must have a compatible signature to the method declared in the single method interface) instead of having to create an anonymous class. In contrast, if you make one interface with more than one method, the client code will not have that possibility. It must always use a class that implements all methods of the interface.
So as a common guideline, one can say: If a class that only exposes a single method to the client code might be useful to some client, then using a single method interface for that method is a good idea. A counter example to this is the Iterator interface: Here, it would not be useful having only a next() method without a hasNext() method. Since having a class that only implements one of these methods is no use, splitting this interface is not a good idea here.
Example:
interface SingleMethod{ //The single method interface
void foo(int i);
}
class X implements SingleMethod { //A class implementing it (and probably other ones)
void foo(int i){...}
}
class Y { //An unrelated class that has methods with matching signature
void bar(int i){...}
static void bar2(int i){...}
}
class Framework{ // A framework that uses the interface
//Takes a single method object and does something with it
//(probably invoking the method)
void consume(SingleMethod m){...}
}
class Client{ //Client code that uses the framework
Framework f = ...;
X x = new X();
Y y = new Y();
f.consume(x); //Fine, also in Java 7
//Java 8
//ALL these calls are only possible since SingleMethod has only ONE method!
f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly
f.consume(Y::bar2); //Static methods are fine, too
f.consume(i -> { System.out.println(i); }) //lambda expression. Super concise.
// the above could even be more concise
// presenting all the beauty of the recent Java changes
f.consume(System.out::println)
//This is the only way if the interface has MORE THAN ONE method:
//Calling Y.bar2 Without that closure stuff (super verbose)
f.consume(new SingleMethod(){
#Override void foo(int i){ Y.bar2(i); }
});
}
Interfaces with only one (or few) methods is the key to the highly useful Strategy pattern, which is "some design standard which advocates the use of these type of interfaces".
Another common scenario is when you want a callback. Foo calls Bar as an asynchronous task, and when Bar is finished with something, the result is sent back to Foo using a callback -- which can be an interface containing only one method. (An example of this is the many listeners in Android, Event Listeners in Swing...)
Also, if you have two classes that are tightly coupled with one another (let's call them Foo and Bar). Foo uses nearly all of Bar's methods, but Bar only needs some a few of those from Foo. Foo can implement FooInterface which is then sent to Bar. Now the coupling is looser, because Bar only knows about the FooInterface, but does not care about the other methods the implementing class contains.
In what scenarios does it make sense to keep single method interfaces?
In such a scenarios when you need an interface with only one method.
Interfaces are used to encapsulate a common behavior of several classes. So if you have several places in your code where you need to call only limited set of class methods, it's time to introduce an interface. The number of methods depends on what exactly do you need to call. Sometimes you need one method, sometimes two or more, sometimes you don't need methods at all. What matters is that you can separate behavior from implementation.
Favor Composition over Inheritance tutorial of Head First Design Pattern book recommends this approach to add functionality dynamically to a class. Let's take below case:
public interface Quackable {
public void quack();
}
public class Quacks implements Quackable {
public void quack(){
//quack behavior
}
}
public class DontQuack implements Quackable {
public void quack(){
//dont quack
}
}
public class QuackableDuck{
Quackable quack; //add behavior dynamicall
}
So QuackableDuck class can add feature dynamically.
quack = new Quacks();
//or
quack = new DontQuack();
So similarly you can add multiple behavior to the class dynamically.
You create interfaces not according to the number of methods in it but to define behaviour expected by components of your systems to deliver a single responsibility to their neighbors. If you follow this simple principle/rule, you might or might not end up with single method interfaces, depending on the responsibility you are defining. I like to keep tests stupid simple and the application very flexible so I usually have many of those

Java, what do you call this? and why )};

I am going through Hello Android (Android PDF/tutorial) and have now seen this syntax a couple of times. Can someone please explain to me what Java syntax is used when run Runnable is defined?
private class AndroidBridge {
public void callAndroid(final String arg) { // must be final
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "callAndroid(" + arg + ")" );
textView.setText(arg);
}
...
Is the code defining a Runnable object and overriding it's run method?
As Dave Newton indicated, this is an anonymous inner class implementing the Runnable interface.
As to why one would want to use this, it could be thought of as syntactic sugar of sorts. You'll notice that in your example, the code in run() has access to the same scope as where the anonymous inner class itself is defined.
This simplifies access to those members, as if you defined the class externally, you'd have to pass in a reference to any object whose members you wanted to invoke/use.
In fact, IIRC, this is actually what happens when Java compiles the anonymous inner class; if there are references to the outer containing class, the compiler will create a constructor that passes in a reference to the outer containing class.
The .post method expects a Runnable object, which in your code sample is declared anonymously and passed as the argument.
That will start a new thread for some long-running process.
The thread constructor needs a Runnable object, which has a run method that's called when the thread is ready.
When many Java apps start, all of the operations pile up on one thread, including the UI. I mainly use threads to avoid freezing up the UI if I'm doing something "heavy".
You've seen this happen when you click "execute" or something, and the UI suddenly is less than responsive. This is because the current thread doesn't have enough resources to build the UI and do whatever "execute" is asking.
So, sometimes that's done elsewhere, on a different thread, which needs a Runnable object.
It's worth noting that multithreading (where you make more than one thread on purpose) is notoriously difficult to work with, for debugging reasons mostly, IMO. But it is a useful tool, of course.
The code is defining an anonymous inner class that implements the Runnable interface, and implementing the run method to perform the appropriate actions.

Checking subclasses for relevance before instantiating them?

Java newbie here. Here's what I'd like to do:
Enumerate over a list of classes, each of which extends the same superclass.
Ask the class whether it's interested in an event.
If the class is interested, instantiate the class and call the object's event handler.
The idea is that steps 2 and 3 will prevent instantiation of classes that aren't interested. However, because I'm calling a method before instantiation, the check would have to be done statically. Java (rightly) doesn't allow the overriding of static methods, so it seems that I have to instantiate the class in step 2, making the sequence look like this:
Enumerate over a list of classes, each of which extends the same superclass.
Instantiate each class and ask the object whether it's interested in the event.
If the object is interested, call its event handler. If it's not interested, throw it away.
Am I missing a general way to accomplish the first set of steps?
Note that this question is mostly theoretical. Object creation overhead may be low enough to render it moot. I'm interested in the possibilities, though.
Since we're speaking about theory, I'm pointing at some facts and speaking in terms of design.
Static methods are not associated to a particular instance of a class, so overriding is not an option since it depends on having an instance. I'm talking about Java, because I recall some other languages that allow class method overriding.
The workaround to this is to define a static method in each subclass that returns the events it is interested in, so you can know this data before instantiation.
Another option is to put a specific class in charge of those objects instantiation and making that class keep a table associating an event with a list of interested classes (table that you can initialize and configure). This approach seems more maintainable because you won't have to change code if you want to unsuscribe a class from an event.
In the end, you just instantiate all the classes thata re associated to a certain event:
public class EventClassCreator {
private Map<String, List<String>> subscriptions;
public EventClassCreator() {
subscriptions = new HashMap<String,Set<String>>();
}
public void addSubscription(String event, String class) {
if(subscriptions.containsKey(event))
subscriptions.get(event).add(class);
else {
Set<String> subscriptionsForEvent = new HashSet<String>();
subscriptionsForEvent.add(class);
subscriptions.put(event, subscriptionsForEvent);
}
}
//You just need to make an event that loops over the list of classes,
//checks a subscription and instantiates a class if it is in the
//proper list.
}

OOP-Design: Interface-Methods with implementation-dependent parameters

The subject says it already:
I am thinking right now about following design-problem: I define an interface for a specific type of object that contains various methods.
Now i have the problem, that different implementations of this interface, need additional/different method-parameters (because the way they are implemented makes this necessary), which i cannot incorporate into the interface because they are not common to all interface-implementations.
Now i realize that interface implementations could come with their own property-files, loading their additional parameters from there, but what if these parameters need to be passed in at runtime?
Currently i can only think of passing in a Map<String, Object> parameters to overcome this problem - since JDK-Classes like DocumentBuilderFactory are doing something very similar by providing methods like setAttribute(String attName, Object attValue) this
seems like a feasible approach to solve this problem.
Nevertheless i would be interested in how others solve issues like this, alternative ideas?
I dont want to derive from the interface and add additional methods, since in my case i would then have to throw NotImplementException from the methods of the base interface.
UPDATE:
What could be eventual problems of the Map-approach? Implementing classes are free to ignore it completely if they cant make use of additional parameters.
Others might check if the Map contains the desired parameter-names, check the type of their values and use them if valid, throw an exception if not.
I have also seen this being used for the abstract class JAXBContext, so it seems to be a common approach..
UPDATE:
I decided to go for the map-approach, since i dont see any obvious disadvantages and it is being used in the JDK as well (yes, i know this does not necessarily mean much :)
Since i cannot accept an answer on this question, i will just upvote. Thanks for your input!
regards,
--qu
You should just initialize each inheritor with its own specific required parameters and let the interface method remain parameter-less, as in:
Interface Runnable:
public interface Runnable {
public abstract void run();
}
Implementation:
public class MyRunnable {
private final String myConcreteString;
public MyRunnable(String myConcreteString) {
this.myConcreteString = myConcreteString;
}
public void run() {
// do something with myConcreteString
}
}
The point of the interfaces is to have something that is common to all implementations. By trying to do this you destroy the whole reason why interfaces exists.
If you absolutely must do that there is a simple enough way that I have used before.
My answer is in C++ because I'm just not that fluent in other languages. I'm sure there are ways to implement this in java as well.
SomeMethod(void* parameterData);
void* parameterData is a pointer to a struct containing your data. In each implementation you know what you are receiving. You can even have a enum to tell you what kind of data you are receiving.
SSomeData* data = (SSomeData)parameterData
EDIT:
Another approach would be to create a new interface for the parameters: IParameterData.
Inside that interface you have 2 methods: GetParameter(name) and SetParameter(name).
For each implementation of your primary interface you create a implementation of IParameterData.
I hope it helps
couldn't you design subinterfaces that extend your (super)interface?
anyhow I see a design problem if you need a method with different parameters depending on the implementation!
edit: code to clarify
interface CommonBehaviour
{
void methodA(int aParam);
}
interface SpecificBehaviour extends CommonBehaviour
{
void methodB(int aParam, int anotherParam);
}
class SpecificBehaviourImpl implements SpecificBehaviour
{
void methodA(int aParam)
{
//do something common
}
void methodB(int aParam, int anotherParam)
{
//do something specific
}
}
CommonBehaviour myObj = new SpecificBehaviourImpl();
EDIT: You may benefit from the Command pattern:
"Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters."
(source: wikipedia)
I don't think the Map approach to be any good, I may accept it as a fix of existing code that would allow you to have any parameter number and type, but without formal checks! You're trying to define a common behavior (interface methods) given a variable, runtime, state.
You should introduce parameter object representing a super-set of possible arguments.
In your place, I would consider finding appropriate design pattern to your problem, rather then try to bend the interface methods to suit your needs. Look into Strategy Pattern for starters.
Can you invert the problem, and implement an interface on the user of these objects which they can query for the additional parameters?
So, when you instantiate these objects implementing the common interface, you also pass in (e.g. to their constructor) an object which provides a way of accessing the additional parameters they might require.
Say your interface has a method 'doSomething' taking parameter 'a', but you have an implementation that needs to know what 'b' is inside this 'doSomething' method. It would call 'getB' on the object you provided to it's constructor to get this information.

Categories