is this possible in java or any other programming language - java

public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
System.out.println ("Parameters for subclass method were: ....");
}
}
public class Owner extends Master {
public void printSomething () {
System.out.println ("This printed from Owner");
}
public int returnSomeCals ()
{
return 5+5;
}
}
Without messing with methods of subclass...is it possible to execute printForAllMethodsInSubClass() before the method of a subclass gets executed?
update:
Using AspectJ/Ruby/Python...etc
Would it also be possible to print the parameters? Above code formatted below:
public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
}
}
public class Owner extends Master {
public void printSomething (String something) {
System.out.println (something + " printed from Owner");
}
public int returnSomeCals (int x, int y)
{
return x+y;
}
}

AspectJ can provide this functionality for you, but it's a separate compilation step and some extra libraries involved.
public aspect ServerLogger {
pointcut printSomething ();
before(): printSomething()
{
(Master)(thisJoinPointStaticPart.getTarget()).printForAlMethodsInSubClass();
}
}
The Eclipse Project provides a great implementation of AspectJ that integrates nicely with Eclipse and Maven. There's a boatload of great documentation available for it, and a lot of really good material for it here on StackOverflow.
[update]
To access parameter info, you can use the
thisJoinPoint.getSignature();
method to access information about the function being called if the returned Object is an instance of MethodSignature, you can use Signature.getParameterNames() to access the parameters to the function being called. You'd have to use a bit of reflection to actually get at the values, I think - AspectJ doesn't seem to handle this for you. I'd have to actually do some experimentation to get some working code for you.

To answer the "any other programming language": It's easily possible in Ruby:
class Master
REDEFINED = []
def printForAllMethodsInSubClass
puts 'Printing before subclass method executes'
end
def self.method_added(meth)
if self < Master and not Master::REDEFINED.include? meth
new_name = "MASTER_OVERRIDE_#{meth}".intern
Master::REDEFINED.push meth, new_name
alias_method new_name, meth
define_method(meth) {|*args| printForAllMethodsInSubClass; send(new_name, *args)}
end
end
end
You could also make a proxy declaration method to use in subclasses:
class Master
def printForAllMethodsInSubClass
Printing before subclass method executes
end
def self.master_method(name)
define_method(name) {|*args| printForAllMethodsInSubClass; yield *args}
end
end
class Owner
master_method(:print_something) do
puts "This was printed from Owner"
end
end
(This approach would also translate very naturally to Python decorators.)

This is possible in aspect-oriented programming languages, such as AspectJ.

In Python you can accomplish this using meta classes, here's a small example. You can probably make it more elegantly but it is just to make the point
import types
class PrintMetaClass(type):
def __init__(cls, name, bases, attrs):
# for every member in the class
override = {}
for attr in attrs:
member = attrs[attr]
# if it's a function
if type(member) == types.FunctionType:
# we wrap it
def wrapped(*args, **kwargs):
print 'before any method'
return member(*args, **kwargs)
override[attr] = wrapped
super(PrintMetaClass, cls).__init__(name, bases, attrs)
for attr in override:
setattr(cls, attr, override[attr])
class Foo:
__metaclass__ = PrintMetaClass
def do_something(self):
print 2
class Bar(Foo):
def do_something_else(self):
print 3
In this example, the PrintMetaClass gets in the way of the creation of the Foo class and any of its subclasses redefining every method to be a wrapper of the original and printing a given message at the beginning. The Bar class receives this aspect-like behavior simply by inheriting from Foo which defines its __metaclass__ to be PrintMetaClass.
Metaclasess in OOP:
http://en.wikipedia.org/wiki/Metaclass
Metaclasses in python:
http://www.python.org/doc/essays/metaclasses/
http://www.ibm.com/developerworks/linux/library/l-pymeta.html

Besides aspect oriented programming have a look at Template Method Pattern, http://en.wikipedia.org/wiki/Template_method_pattern.
In short: the parent class have an abstract method, which subclasses have to implement, this abstract method is called by a method in the parent class where put your printouts or whatever necessary statements.

Related

How to verify whether a super class method was called in Spock?

Imagine I had the following class structure:
class Parent {
public void method() {
// Some calculations
}
}
class Child extends Parent {
#Override
public void method() {
super.method();
// Some additional logic
}
}
I am spock-testing the Child.method and want to verify if the Parent.method is called from the Child.method. I did some research and i haven't found any satisfying solution to solve my problem.
How can I verify in a Spock test that in the call of Child.method the superclass method (Parent.method) was called as well?
Known solution: In Child move the super.method() to a separate, package-private method.
I want to know whether there is a better solution.
tim_yates commented:
Why do you want to test this? Can't you tell as the super class calculations were performed?
I completely agree. I would not test this because as #Override implies, the contract is an override, delegation to the super class method is optional. Why would you force your users to call the super class method? But as Tim said, you can test for the side effects which are important to you. Here is a little example with one side effect being a field assignment and another being something written to System.out (maybe silly, but just in order to show something non-obvious with a mock):
package de.scrum_master.stackoverflow.q60167623;
public class Parent {
protected String name;
public void method() {
// Some calculations
System.out.println("parent method");
name = "John Doe";
}
}
package de.scrum_master.stackoverflow.q60167623;
class Child extends Parent {
#Override
public void method() {
super.method();
// Some additional logic
System.out.println("child method");
}
public static void main(String[] args) {
new Child().method();
}
}
package de.scrum_master.stackoverflow.q60167623
import spock.lang.Specification
class ChildTest extends Specification {
static final PrintStream originalSysOut = System.out
PrintStream mockSysOut = Mock()
def setup() {
System.out = mockSysOut
}
def cleanup() {
System.out = originalSysOut
}
def test() {
given:
def child = new Child()
when:
child.method()
then:
1 * mockSysOut.println({ it.contains("parent") })
child.name == "John Doe"
}
}
Update: What you want to do simply is not possible technically, and for a reason: It would break encapsulation, see here, here, indirectly also here. The method is overridden, the word says it all. Test for the (side) effect or the result of a method, not for its interaction (that it is actually called). Spock's interaction testing capabilities are over-used even though the Spock manual warns about over-specification in some places. It just makes your tests brittle. Interaction testing is okay for design patterns like publish/subscribe (Observer pattern) where it makes sense to test the interactions between objects as such.
If you need to enforce that some functionality in Parent is called, you should enforce it via design not tests.
abstract class Parent {
public final void method() {
// Some calculations
additionalLogic();
}
protected abstract void additionalLogic();
}
class Child extends Parent {
#Override
protected void additionalLogic() {
super.method();
// Some additional logic
}
}
You could of course not make it abstract and just add a no-op implementation for additionalLogic() instead.
tim_yates and kriegaex are the big beasts in the jungle when it comes to good and bad Spock, or TDD-style testing generally ... they have more than once (rightly) picked apart my questions in the way they do here, basically on the basis of testing the code rather than the implementation.
Sometimes it's difficult though. Maybe there can be cases in which you would want to test for the calling of super.doSomething(). I am just putting together, using TDD, having already done a "spike", in which I rushed ahead without testing, an editor for a TreeTableView. The "spike" can be seen here. In a constructive comment to my answer, kleopatra advised me to check (i.e. put an if in the app code) to make sure that super.startEdit() had indeed started the editing of the cell before going further, so in this case it is not sufficient to test the "side-effect" of super.startEdit() as being that isEditing() now returns true. You genuinely need to know that your class's startEdit() actually does nothing more nor less than call super.startEdit().
However, I don't believe it can be done, and tim_yates or kriegaex would almost certainly have said how you could do that if it were possible.
My suggested TDD solution would therefore be something like this:
def 'super start edit should be called if cell is not empty'(){
given:
// NB has to be GroovySpy because isEmpty() is final
DueDateEditor editor = GroovySpy( DueDateEditor ){
isEmpty() >> false
}
when:
editor.startEdit()
then:
1 * editor.callSuperStartEdit()
}
class DueDateEditor extends TreeTableCell {
#Override
void startEdit(){
if( ! isEmpty() ) {
// this is the line you have to add to make the test pass
callSuperStartEdit()
}
}
def callSuperStartEdit(){
super.startEdit()
}
}
I think you have to "spawn" an artificial single-purpose method since there is, precisely, no side effect at all!
PS I will in fact parameterise this test so that it returns true to isEmpty() in the second call, and require the method NOT to be called in that case.
I´ve never used the Spock framework, but i think you can check the type of the instance in the Parent.method with instance of operator or reflection.

Constructor invoke overridable method in Java [duplicate]

I have a Wicket page class that sets the page title depending on the result of an abstract method.
public abstract class BasicPage extends WebPage {
public BasicPage() {
add(new Label("title", getTitle()));
}
protected abstract String getTitle();
}
NetBeans warns me with the message "Overridable method call in constructor", but what should be wrong with it? The only alternative I can imagine is to pass the results of otherwise abstract methods to the super constructor in subclasses. But that could be hard to read with many parameters.
On invoking overridable method from constructors
Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the #Override is invoked, the state of the object may be inconsistent and/or incomplete.
A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
Here's an example to illustrate:
public class ConstructorCallsOverride {
public static void main(String[] args) {
abstract class Base {
Base() {
overrideMe();
}
abstract void overrideMe();
}
class Child extends Base {
final int x;
Child(int x) {
this.x = x;
}
#Override
void overrideMe() {
System.out.println(x);
}
}
new Child(42); // prints "0"
}
}
Here, when Base constructor calls overrideMe, Child has not finished initializing the final int x, and the method gets the wrong value. This will almost certainly lead to bugs and errors.
Related questions
Calling an Overridden Method from a Parent-Class Constructor
State of Derived class object when Base class constructor calls overridden method in Java
Using abstract init() function in abstract class’s constructor
See also
FindBugs - Uninitialized read of field method called from constructor of superclass
On object construction with many parameters
Constructors with many parameters can lead to poor readability, and better alternatives exist.
Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:
Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...
The telescoping constructor pattern is essentially something like this:
public class Telescope {
final String name;
final int levels;
final boolean isAdjustable;
public Telescope(String name) {
this(name, 5);
}
public Telescope(String name, int levels) {
this(name, levels, false);
}
public Telescope(String name, int levels, boolean isAdjustable) {
this.name = name;
this.levels = levels;
this.isAdjustable = isAdjustable;
}
}
And now you can do any of the following:
new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);
You can't, however, currently set only the name and isAdjustable, and leaving levels at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean and int arguments, which would really make a mess out of things.
As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).
Bloch recommends using a builder pattern, which would allow you to write something like this instead:
Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();
Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.
See also
Wikipedia/Builder pattern
Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters (excerpt online)
Related questions
When would you use the Builder Pattern?
Is this a well known design pattern? What is its name?
Here's an example which helps to understand this:
public class Main {
static abstract class A {
abstract void foo();
A() {
System.out.println("Constructing A");
foo();
}
}
static class C extends A {
C() {
System.out.println("Constructing C");
}
void foo() {
System.out.println("Using C");
}
}
public static void main(String[] args) {
C c = new C();
}
}
If you run this code, you get the following output:
Constructing A
Using C
Constructing C
You see? foo() makes use of C before C's constructor has been run. If foo() requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo() expects, you get a warning.
Invoking an overridable method in the constructor allows subclasses to subvert the code, so you can't guarantee that it works anymore. That's why you get a warning.
In your example, what happens if a subclass overrides getTitle() and returns null ?
To "fix" this, you can use a factory method instead of a constructor, it's a common pattern of objects instanciation.
Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.
class A {
protected int minWeeklySalary;
protected int maxWeeklySalary;
protected static final int MIN = 1000;
protected static final int MAX = 2000;
public A() {
setSalaryRange();
}
protected void setSalaryRange() {
throw new RuntimeException("not implemented");
}
public void pr() {
System.out.println("minWeeklySalary: " + minWeeklySalary);
System.out.println("maxWeeklySalary: " + maxWeeklySalary);
}
}
class B extends A {
private int factor = 1;
public B(int _factor) {
this.factor = _factor;
}
#Override
protected void setSalaryRange() {
this.minWeeklySalary = MIN * this.factor;
this.maxWeeklySalary = MAX * this.factor;
}
}
public static void main(String[] args) {
B b = new B(2);
b.pr();
}
The result would actually be:
minWeeklySalary: 0
maxWeeklySalary: 0
This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.
I hope that would help someone.
If you call methods in your constructor that subclasses override, it means you are less likely to be referencing variables that don’t exist yet if you divide your initialization logically between the constructor and the method.
Have a look on this sample link http://www.javapractices.com/topic/TopicAction.do?Id=215
I certainly agree that there are cases where it is better not to call some methods from a constructor.
Making them private takes away all doubt: "You shall not pass".
However, what if you DO want to keep things open.
It's not just the access modifier that is the real problem, as I tried to explain here. To be completely honest, private is a clear showstopper where protected usually will still allow a (harmful) workaround.
A more general advice:
don't start threads from your constructor
don't read files from your constructor
don't call APIs or services from your constructor
don't load data from a database from your constructor
don't parse json or xml documents from your constructor
Don't do so (in)directly from your constructor. That includes doing any of these actions from a private/protected function which is called by the constructor.
Calling an start() method from your constructor could certainly be a red flag.
Instead, you should provide a public init(), start() or connect() method. And leave the responsibility to the consumer.
Simply put, you want to separate the moment of "preparation" from the "ignition".
if a constructor can be extended then it shouldn't self-ignite.
If it self-ignites then it risks being launched before being fully constructed.
After all, some day more preparation could be added in the constructor of a subclass. And you don't have any control over the order of execution of the constructor of a super class.
PS: consider implementing the Closeable interface along with it.
In the specific case of Wicket: This is the very reason why I asked the Wicket
devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.
Construction - via constructor
Initialization - via onInitilize (after construction when virtual methods work!)
There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)
The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.
I guess for Wicket it's better to call add method in the onInitialize() (see components lifecycle) :
public abstract class BasicPage extends WebPage {
public BasicPage() {
}
#Override
public void onInitialize() {
add(new Label("title", getTitle()));
}
protected abstract String getTitle();
}

Can a subclass override a method and have different parameters?

I want to have a method in multiple subclasses which essentially get a certain thing done (like getting user info), but is declared in (and has different parameters and definitions than) the main class. Is this possible?
I know this is not really overriding, but can this be done or is it not a suitable way to structure methods?
What you want to do is called overloading a method. It is doable and occurs often. Play with the fiddle here. Java is similar.
public class Parent
{
public virtual string HelloWorld()
{
return "Hello world";
}
public string GoodbyeWorld()
{
return "Goodbye world";
}
}
public class Child : Parent
{
// override: exact same signature, parent method must be virtual
public override string HelloWorld()
{
return "Hello World from Child";
}
// overload: same name, different order of parameter types
public string GoodbyeWorld(string name)
{
return GoodbyeWorld() + " from " + name;
}
}
public class Program
{
public static void Main()
{
var parent = new Parent();
var child = new Child();
Console.WriteLine(parent.HelloWorld());
Console.WriteLine(child.HelloWorld());
Console.WriteLine(child.GoodbyeWorld());
Console.WriteLine(child.GoodbyeWorld("Shaun"));
}
}
You can have multiple versions of a method with the same name having different number of parameters. You can have all these in the main/parent class or you can add the newer versions in the subclasses only. There is no restriction on doing this.
As stated in the comments and the other answer, you can define a method in a subclass with the same name as a method in its superclass, but you can't override it, exactly. Both methods will still exist, so it's called overloading. In Java and in C Sharp it works pretty much the same; you just define a new method with different parameters. You cannot just change the return type, though. The parameters to the methods must be different in order to overload one. Here is an article about overloading vs. overriding in Java.

Can we write a function in Java that takes another function signature as a parameter and executes it? [duplicate]

This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.
Java provides a set of common functional interfaces. whereas you could do the following:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}
There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.
Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.
Example:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();

Shared functionality in an abstract method

I have an abstract method which sets a graphical item's label. There are different types of items, all of which inherit from an abstract base class which has a "setLabel()" method.
The different items do different things when they set a label, but at the end they should all do the same thing, which is a series of housekeeping activities. I know I can create a method in the base class to do these chores and then call that in each of the implementations, but that is bad because among other things if I forget to call it from one of the implementations, it will create a bug.
What is a good way to structure this?
Here is example code (how I am doing it now in Java):
final public void _setLabel( String s ){
if( s.trim().equals( "null" ) ) return;
StringBuffer sbError = new StringBuffer();
if( ! _setConstantValue( s, sbError ) ){
Error.vShowError( "failed to set value: " + sbError );
return;
}
sLabel = s;
_update();
_updateProperties();
if( _isGroupMember() ) this.nodeGroup._update();
}
There is an abstract method "_setLabel" in the base class, so all my subclasses MUST implement this method. The last three lines in the method are always the same:
_update();
_updateProperties();
if( _isGroupMember() ) this.nodeGroup._update();
Right now, I just copy and paste these lines into each implementation, but I would rather they get done in the base class somehow, so I can guarantee that they always occur. These must be called after everything else.
SOLUTION:
Based on the marked answer below (thanks to user3736255), the solution is to use a non-virtual interface in C++ or a template method in Java (which is equivalent). So the new base class code is:
final public void _setLabel( String s ){
__setLabel( s );
_update();
_updateProperties();
if( _isGroupMember() ) this.nodeGroup._update();
}
abstract protected void __setLabel( String s );
Each subclass implements the __setLabel method which is called by the template method _setLabel in the base class.
Sounds like you are looking for the Non-virtual interface pattern: http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface
Maybe:
class Base() {
public:
void setLabel();
protected:
virtual void doSetLabel();
private:
houseKeepingBefore();
houseKeepingAfter();
}
void Base::setLabel() {
houseKeepingBefore();
doSetLabel();
houseKeepingAfter();
}
But, this will not solve your problem, if you have a houseKeepingInbetween.
Do you want to create a decorator that extends the base and is created with an appropriate instance of the graphical item. It is the responsibility of the decorator to invoke the housekeeping activities. All clients invoke the decorator instead of the actual graphical item. Note: I am assuming that all invocations to the graphical item are through defined/declared methods in the base.
You could perhaps also utilize aspects: http://en.wikipedia.org/wiki/Aspect-oriented_programming

Categories