OOP design pattern - calling super methods implicitly or some other solution - java

Is there a design pattern (probably but not necessarily OOP) whereby you can implicitly (not explicitly) call one function/method A form all the other methods in an object each time those other methods are called?
for example:
//pseudocode
class Foo {
int count = 0;
void synchronized countUp(){
count++;
}
void doSomethingFirst(){
//call countUp() implicitly here
}
void doSomethingSecond(){
//call countUp() implicitly here
}
}
Would there be a way to use annotations in Java for instance? I could mark methods that need to call super methods or something. So it would be like an implicit call to super. I am not saying this is a great idea I am just wondering if it can be done somehow with a design pattern.

You could probably copy the system (I don't think it is a design pattern) used by the Spring MVC framework. It relies on making the inherited method final, and providing an overloadable method for descendants.
Using part of your example code (in Java):
final void doSomethingFirst(){
countUp();
doSomethingFirstInternal();
}
protected void doSomethingFirstInternal() {
// Empty implementation that descendants can override when necessary.
}
I'm not saying this is a great idea - you need to be 100% sure that your code should execute first. But is an option and careless programmers cannot introduce bugs because they forgot to call super().

You could extend the class and overwrite the countUp() method, after. Make all methods protected and call the superclass methods that you need from the child class.
class Boo extends Foo {
#Override
void countUp() {
setUp();
super.countUp();
tearDown();
}
}
To make this more generic, you could use the observer pattern:
make Foo class observable
get all its methods at init via reflection
Foo.class.getMethods()
wrap all methods in a class and register as observers

Related

How to declare a method that can be used only inside another method in a java interface?

How to declare a method that can be used only inside another method in a java interface?
public interface VendingMachine_ADT {
public void selectDrink(Drink d);
public void MoneyEntered(Coin c);
public void DrinkSelectedandMoneyEntered();
public void cancel();//i want this method inside selectDrink();
}
Although you can, with come coercion, achieve this in C++ (which somewhat legitimises this question), you cannot do this in Java.
All methods in a Java interface are necessarily public. Really the concept of a private method localised to a particular function is more to do with the implementation of that interface rather than the interface itself.
So you'd need to enforce your restriction in an implementation of selectDrink().
You cannot do that. All methods in an interface are meant to be public.
Apparently, you have several classes that implement VendingMachine_ADT, and they use a method named cancel that is the same for them - or at least similar.
In this case, you can make a base class for VendingMachine_ADT, and make cancel a protected method of the base class. Your cancel method will be available to descendant classes.
Depending on your needs, you could even have cancel as an abstract method, to be implemented by subclasses. That is as close to an interface as you can get.

Invoke a method on all subclasses from superclass?

I have recently stubled upon something that has always annoyed me.
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions, I would like to have a keyword that does the opposite of the keyword super. Basically, I want the invocation to be passed down (if a class inherits a method, and the method in the superclass is called, it will be called in the subclass as well). Is there anything that resembles what I am asking for?
EDIT:
The contemporary methods I am using are efficient, but not as efficient as I would like them to be. I am only wondering if there is a way of invoking a method, that has been inherited, from its superclass/superinterface. The last time I was looking for this, I did not find it either.
NOTE: All of the subclasses are unknown, hence impossible to utilize. The only known class is the superclass, which is why I can't invoke it. This can be solved using the Reflections API, which I am currently using. However, it does not always comply with what I am searching for.
Every method in Java is virtual with the exception of static methods, final methods and constructors meaning that if a subclass implements the method being invoked, the subclass's implementation will be called. If the subclass wishes to also invoke the immediate superclass method, that is accomplished via a call to super.
This is very common with abstract classes where some base class is utilized by a framework, but clients are expected to override. For instance:
public abstract class Drawer{
public void draw(){
//setup code, etc common to all subclass implementations
doDraw();
}
protected abstract void doDraw();
}
public class CircleDrawer extends Drawer{
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Now, when you have an instance of CircleDrawer and you call draw(), the superclass Drawer.draw() method will be invoked that is, in turn, able to call CicleDrawer.doDraw().
Edit Now, if CircleDrawer was this:
public class CircleDrawer extends Drawer{
public void draw(){
//do stuff
}
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Any invocation of Drawer.draw() on an instance of CircleDrawer will always invoke the CircleDrawer.draw() method.
If you mean something like this:
class A {
public void func1(){
//do stuff
subclass.func1();
}
}
class B extends A{
public void func1(){
//do more stuff
}
}
class C extends A{
}
What happens when I call new C().func1()? Remember, func1 is not abstract and therefore, you cannot require classes to define it.
A better solution is to do the following:
abstract class A {
public void func1(){
//do stuff
func2();
}
public abstract func2();
}
class B extends A{
public void func2(){
//do more stuff
}
}
Hence, you require your subclasses to define a function that you can call from the super class.
The is no such a thing. When calling an overriden method in Java, the child-most class's method will be always called. If you want to call parent methods as well, you need to use super.methodCall() in every class's method of your hirearchy.
Unfortunately, I don't believe the thing you are trying to do is as possible as you may think. It's not quite that easy to invoke your subclasses from the super class, because not all subclasses may behave in the same way so a generic keyword for that functionality would wreak havoc! Although, by the phrasing of "Basically, I want the invocation to be passed down." it sounds like what you want is normal inheritance.
Just define the most generic similarities that all subclasses have in common in the superclass, then simply start each subclass definition of the method with super()
I don't mean to point out the obvious, but OO was designed for that and not for what you are asking. I doubt you'll be unable to find a way to do what you want within the typical arsenal of OO concepts
I think you got confused describing what you need, I don't think this:
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions
Is the same as this:
I would like to have a keyword that does the opposite of the keyword super
From what I understand, in the first one, you are referring to calling a method for all instances of a base class and its subclasses. For the second one, calling a subclass' method is exactly calling that method on a subclass which has probably overriden it.
I'm not sure what you are trying to do, maybe you should clarify with an example. Most likely, yours is a design problem which is solved in a different way than the one you are proposing. However, a "solution" came to mind when reading your question.
I'm a little more experienced with C# and python than with Java (and not even that much), but I'm sure more experienced programmers won't hesitate to correct me if I said stupid things.
You should have some kind of collection of objects of type of the base class and call that method, on each object, which each subclass must have overriden.
Maybe using the observer pattern, which is commonly used to reproduce event triggering, you can make all instances of a base class and its subclasses execute a "callback" whenever you want.

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

Can I rename an implemented method in Java?

I have a class which is implementing an interface, and one of the methods is called onClick. Is there a way to implement the onClick that the interface wants but name it something else? Something like (and I'm making this up):
public void AnyMethodNameIWant() implements Interface1.onClick
Three reasons I'm asking are:
It would be nice to look at an method signature and know that it's
coming from an interface
To avoid 'generic' names like onClick that an interface may require me to have
To distinguish between the same method names in many interfaces
Apologies if this is a fundamentally 'bad' question as I am new to Java.
No, you can't. Interfaces have to be implemented by a method of the same name in Java.
You can use the #Override annotation with interface implementations (as of Java 6) though, which helps to clarify that this is a method which can't just be renamed arbitrarily.
One option for your second issue might be to create an implementation class just for the purpose of forwarding on the call to a more specific method. You might want to do this as a nested or even anonymous class. I'm not sure I'd usually do this though.
EDIT: Having seen the third question - no, if you have two interfaces with the same method signature in Java, you can only provide one implementation :( Oh, and if you've got two interfaces with the same signature but different return types, it's even worse. You could always write a method of Interface1 getInterface1() which returns an instance of an anonymous inner class proxying the Interface1 methods onto the "main" class.
Nope.
The only thing you could do is add a shadow method that implements the interface and calls your method.
public class MyClass implements Interface1 {
public void AnyMethodNameIWant() { ...; }
public void onClick() { AnyMethodNameIWant(); }
}
Those two points
To avoid 'generic' names like onClick that an interface may require me to have
To distinguish between the same method names in many interfaces
are usually solved by using the Adapter Pattern.
interface IFoo {
void onClick();
void onChange();
}
class MyImpl {
void doSomething(){
// real code for onClick
}
void doSomethingElse(){
// real code for onChange
}
IFoo getFooAdapter(){
return new IFoo() {
#Override
public void onClick() {
doSomething();
}
#Override
public void onChange() {
doSomethingElse();
}
};
}
}
Basically you create an intermediate step which forwards all calls to any interface method to the real implementation.
Naming and signatures can vary. You can also offer different adapters for different interfaces if you want (or must if both interfaces have competing method with different behaviour).
There are quite some possibilities how to hand out the adapter instance - creating a new one every time might not be wise in certain circumstances.
Of course this pattern is nothing you implement just for fun or just for minimal and clean code. But it can solve real problems.
You can't rename the method, but you could define both methods (onClick and anyMethodNameIWant) and have onClick just simply call your other method.
#Override
public void onClick() {
anyOtherMethodNameIWant();
}
You of course can have additional methods with different names that point to the same implementation to get the naming you desire.
public void interfaceMethodA(){
// some implementation here
}
public void AnyMethodNameIWant(){
interfaceMethodA();
}

Is there a 'new' modifier for methods in Java?

Is there an equivalent to C#'s new modifier in Java?
I'd like to use it for unit tests - every init() method should be marked final and annotated with #Before. Then, jUnit executes all of these init() methods.
I don't want to bother coming up with new names for each of these init() methods, and I definitely wants to mark them as final to make sure they don't override eachother (an alternative pattern is to override and call super.init() from every init() method).
A common pattern is to make your own 'before' methods final and create protected (abstract) methods for the subclasses.
In the superclass
#Before
public final void before() {
onBefore();
}
protected void onBefore() {
}
In the subclass
protected void onBefore() {
// prepare the test fixture
}
This gives you the best of both worlds:
a well-known method to override in sub-classes;
overriding is optional;
the superclass method is never overriden;
the client method is invoked when the super-class decides, i.e. either before or after the super-class decides.
It does have a single downside - it ties you to a single super-class. Still, that may not be an issue to your environment.
Unfortunately not. Heck, before #Override there wasn't even any way of protecting against typos when overriding.
You can't create a method with the same signature as a superclass method without it overriding that method. Admittedly I try not to do this even in C#...
Have you considered using initFoo and initBar for classes Foo and Bar respectively (etc)? It's a simple enough pattern to follow, and would avoid the name collisions. A bit ugly, admittedly.
Java does not have an equivalent to the C# new operator which is
Used to hide an inherited member from a base class member.
For what you'd like to do, why not create a base class that your other tests can extend, and create an abstract method named init() (marked with #Before) in the base class? This forces all subclasses to supply an init() method.

Categories