Interface Bloated with Callbacks - oop

Imagine the following class hierarchy:
interface IRules
{
void NotifyPickup(object pickedUp);
void NotifyDeath();
void NotifyDamage();
}
class CaptureTheFlag : IRules
{
public void NotifyPickup(Pickup pickedUp)
{
if(pickedUp is Flag)
GameOver();
}
public void NotifyDeath()
{
}
public void NotifyDamage()
{
}
}
class DeathMatch : IRules
{
public void NotifyPickup(Pickup pickedUp)
{
points++;
}
public void NotifyDeath()
{
lives--;
}
public void NotifyDamage()
{
}
}
class GameWorld
{
IRules gameMode;
public Main(IRules gameMode)
{
this.gameMode = gameMode;
}
object[] worldObjects;
public void GameLoop()
{
foreach(object obj in worldObjects)
{
// This call may have a bunch of sideeffects, like getting a pickup
// Or a player dying
// Or damage being taken
// Different game modes are interested in different events / statistics.
obj.Update();
// Stuff happens...
gameMode.NotifyDamage();
// Stuff happens...
gameMode.NotifyDeath();
}
}
}
So here I've got an interface which contains Notify* functions. These are callbacks. Different game modes are interested in different events of the game. It's not really possible to access the concrete objects creating these events because they're buried in the worldObjects array. Imagine we are adding new game modes to our game. The IRules interface will get hugely bloated, containing all the possible things a game mode may be interested in, and most calls will be stubbed! How can I prevent this?
Edit 2: Concrete example

Seems like your Process logic sends out a lot of events. If you would give these events a name, you could subscribe your observers to them.
Then it would even be possible to create a 'filtering' observer that can forward the events to any other observer (a decorator pattern):
struct Event {
enum e { A, B, /*...*/ };
e name;
};
class IEventListener {
public:
virtual void event( Event e ) = 0;
};
// an event dispatcher implementation:
using namespace std;
class EventDispatcher {
public:
typedef std::shared_ptr<IEventListener> IEventListenerPtr;
map<Event::e,vector<IEventListenerPtr>> listeners;
void event(Event e){
const vector<IEventListenerPtr> e_listeners=listeners[e.name].second;
//foreach(begin(e_listeners)
// ,end(e_listeners)
// ,bind(IEventListener::event,_1,e));
for(vector<IEventListenerPtr>::const_iterator it=e_listeners.begin()
; it!=e_listeners.end()
; ++it)
{
(*it)->event(e);
}
}
};
You program could look like this:
Main main;
EventEventDispatcher f1;
f1.listeners[Event::A].push_back(listener1);
main.listener=f1;
Note: code untested - grab the idea.
If you really want to decouple the sender from the sink, you put an event system in between. The example given here is very dedicated and lightweight, but do sure take a look at various existing implementations: Signals and Slots implemented in Qt and in Boost, the delegates from C#, ...

Apologizes if I missed something but why not use event? Basically let IController expose void Callback() method, then Main would be able subscribe any callback to own event:
class Main
{
private event EventHandler SomeEvent;
public Main(IController controller)
{
// use weak events to avoid memory leaks or
// implement IDisposable here and unsubscribe explicitly
this.SomeEvent += controller.Callback;
}
public void ProcessStuff()
{
// invoke event here
SomeEvent();
}
}
EDIT:
This is what I would do: extract each rule action into the separate interface so you just implement what you need in concrete classes, for instance CaptureTheFlag class does only PickupFlag action for now so does not need Damage/Death methods, so just mark by IPickupable and that's it. Then just check whether concrete instance supports concrete actions and proceed with execute.
interface IPickupable
{
void NotifyPickup(object pickedUp);
}
interface IDeathable
{
void NotifyDeath();
}
interface IDamagable
{
void NotifyDamage();
}
class CaptureTheFlag : IPickupable
{
public void NotifyPickup(Pickup pickedUp)
{
if (pickedUp is Flag)
GameOver();
}
}
class DeathMatch : IPickupable, IDeathable
{
public void NotifyPickup(Pickup pickedUp)
{
points++;
}
public void NotifyDeath()
{
lives--;
}
}
class GameWorld
{
public void GameLoop()
{
foreach(object obj in worldObjects)
{
obj.Update();
IPickupable pickupable = gameMode as IPickupable;
IDeathable deathable = gameMode as IDeathable;
IDamagable damagable = gameMode as IDamagable;
if (pickupable != null)
{
pickupable.NotifyPickup();
}
if (deathable != null)
{
deathable.NotifyDeath();
}
if (damagable != null)
{
damagable.NotifyDamage();
}
}
}
}

My final solution was the C# equivalent of what xtofl posted. I created a class which stored a bunch of delegates in it. These delegates started off with default values (so they would never be null) and the different concrete IRules classes could choose to overwrite them or not. This worked better than abstract or stubbed methods because it doesn't clog the interface with unrelated methods.
class GameEvents
{
public Action<Player> PlayerKilled = p => {};
public Func<Entity, bool> EntityValid = e => true;
public Action ItemPickedUp = () => {};
public Action FlagPickedUp = () => {};
}
class IRules
{
GameEvents Events { get; }
}
class CaptureTheFlag : IRules
{
GameEvents events = new GameEvents();
public GameEvents Events
{
get { return events; }
}
public CaptureTheFlag()
{
events.FlagPickedUp = FlagPickedUp;
}
public void FlagPickedUp()
{
score++;
}
}
Each rule set can choose which events it wants to listen to. The game simply calls then by doing Rules.Events.ItemPickedUp();. It's guaranteed never to be null.
Thanks to xtofl for the idea!

Related

Correct way to disable base class functionality

Say, I have class A with method M:
private void M()
{
Do1();
Do2();
}
class B extends A.
Problem: I need Do2() to not to be executed when calling from an instance of B.
I have a couple of ideas but not sure which do not break OOP and SOLID rules.
Make Do2 virtual.
class A
{
protected virtual void Do2()
{
// Do something
}
}
class B
{
protected override void Do2()
{
// Do nothing
}
}
This solution looks weird to me because I override a method to "do nothing", when overriding is needed to "do something instead of something" or "do something in addition to something".
Create bool protected flag property
class A
{
protected virtual NeedCallDo2
{
get { return true; }
}
private void M()
{
Do1();
if (NeedCallDo2)
{
Do2();
}
}
}
class B
{
protected override NeedCallDo2
{
get { return false; }
}
}
This solution is also not perfect but I have a control of execution flow and can decide whether to call Do2 or not.
Pass constructor flag parameter
class A
{
private bool needCallDo2;
protected A(bool needCallDo2 = true)
{
this.needCallDo2 = needCallDo2;
}
private void M()
{
Do1();
if (this.needCallDo2)
{
Do2();
}
}
}
class B
{
public B()
: base(false)
{
}
}
This is a trick question! Given the solid-principles tag, there is no correct way to disable base class functionality, since that would violate liskov-substitution, which is the L in SOLID.
You could move the execution logic into an execution strategy class where class B uses a different strategy implementation than class A.

OOP - Override init method called in constructor

I have a simple class hierarchy of two classes. Both classes call an init-method specific to that class. Therefor the init-method is overriden in the subclass:
class A
{
public A() { this->InitHandlers(); }
public virtual void InitHandlers() { // load some event handlers here }
}
class B: public A
{
public B() { this->InitHandlers(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
I know this is evil design:
The call of an overriden method from constructor is error-prone.
B::InitHandlers() would be called twice with this setup.
But semantically it makes sense to me: I want to extend the behaviour of class A in class B by loading more handlers but still keeping the handlers loaded by class A. Further this is a task that has to be done in construction. So how can this be solved with a more robust design?
You can do something like this:
class A
{
protected boolean init = false;
public A() { this->Init(); }
public virtual void Init() {
if (!this->init) {
this->init = true;
this->InitHandlers();
}
}
public virtual void InitHandlers() {
// load some event handlers here
}
}
class B: public A
{
public B() { this->Init(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
You can see it as a design pattern template method.

How to initialize an object and override a method in objective c?

Like Other Language, We can create a object and override a method in the object during initialization. Please help me How can i do?
For Example:
public class DemoInitAndOverride {
public void handleMessage(){}
}
And in another class
public class SampleClass {
public void doSomeThing(){
DemoInitAndOverride demo = new DemoInitAndOverride(){
#Override
public void handleMessage() {
// TODO Auto-generated method stub
super.handleMessage();
}
};
}
}
****EDIT:****
Thanks everyone for possible solutions and suggestion. I think now it is important for me provide some details about the requirement which could help you in providing the solution.
The handler concept is some thing similar to the Android Framework where handlers are used to pass messages between 2 threads or 2 methods. Please see the code demonstration below:
UI Class (Here the user clicks a button, a request is dispatched to the processor class using handler)
This is the demo handler
/**
*
* Used for thread to thread communication.
* Used for non UI to UI Thread communication.
*
*/
public class DemoHandler {
public void handleMessage(Messages message){}
final public void sendMessage(final Messages message){
//Calling thread is platform dependent and shall change based on the platform
new Thread(new Runnable() {
#Override
public void run() {
synchronized (this) {
handleMessage(message);
}
}
});
}
}
This is simple message class
public class Messages {
public Object myObject;
//other hash map (key, values) and get data put data etc
}
This is simple user interface class demo code:
public class UIClass {
public UIClass(){
//INIT
}
void onClick(int id){
//Some Button is clicked:
//if id == sendParcel
//do
TransactionProcessor.getInstance().sendParcel(handler, "Objects");
}
DemoHandler handler = new DemoHandler(){
public void handleMessage(Messages message) {
//Inform the UI and Perform UI changes
//data is present in the messages
};
};
}
This is sample transaction processor class
public class TransactionProcessor {
public static TransactionProcessor getInstance(){
return new TransactionProcessor(); //for demonstration
}
//Various Transaction Methods which requires calling server using HTTP and process there responses:
public void sendParcel(final DemoHandler uiHander, String otherdetailsForParcel){
//INIT Code and logical code
//Logical Variables and URL generation
String computedURL = "abc.com/?blah";
DemoHandler serverConnectionHandler = new DemoHandler(){
#Override
public void handleMessage(Messages message) {
super.handleMessage(message);
//Process server response:
//create a new message for the UI thread and dispatch
Messages response = new Messages();
//add details to messages
//dispatch
uiHander.sendMessage(response );
}
};
new Thread(new ServerConnection(computedURL, serverConnectionHandler));
}
public void sendEmail(final DemoHandler uiHander, String otherdetailsForEmail){
//SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
public void sendNotification(final DemoHandler uiHander, String otherdetailsForNotifications){
//SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
}
This is a nasty one, and I recommend creating a subclass or something else.
Here's your answer, which is essentially the same, but at runtime. Proceed at your own risk:
Import this:
#import <objc/runtime.h>
And add this code to wherever:
- (void)methodName {
// whatever you want to do in there
}
And in your function:
Class subclass;
// Verifiy that you haven't created it already
subclass = objc_getClass("SampleClassSubclass");
if (!subclass) {
// Generate a new class, which will be subclass of your SampleClass
subclass = objc_allocateClassPair(subclass, "SampleClassSubclass", 0);
// Obtain the implementation of the method you want to overwrite
IMP methodImplementation = [self methodForSelector:#selector(methodName)];
// With that implementation, replace the method
class_replaceMethod(subclass, #selector(methodName), methodImplementation, "##:");
// Register the class you just generated
objc_registerClassPair(subclass);
}
SampleClass *obj = [[subclass alloc] init];
Not so easy to do in Objective-C, but this should work. It replaces the doSomething method of DemoInitAndOverride with its own implementation and returns a new instance of the class. Note however that once this has been done the new implementation remains in place for all new instances of the class, not just a single instance.
- (void)doSomething
{
NSLog(#"self doSomething called");
}
- (DemoInitAndOverride *)createObj
{
DemoInitAndOverride *obj = [[DemoInitAndOverride alloc] init];
SEL sel = #selector(doSomething);
Method theirMethod = class_getInstanceMethod([DemoInitAndOverride class], sel);
Method myMethod = class_getInstanceMethod([self class], sel);
theirMethod->method_imp = myMethod->method_imp;
return obj;
}

Adding State in Decorator Pattern

I wonder how to add state to the chain of decorators that will be available to the consumer. Given this simplified model:
abstract class AbstractPizza
{
public abstract print(...);
}
class Pizza : AbstractPizza
{
public int Size { get; set; }
public print(...);
}
abstract class AbstractPizzaDecorator
{
public Pizza:AbstractPizza;
public abstract print();
}
class HotPizzaDecorator : AbstractPizzaDecorator
{
public int Hotness { get; set; }
public print(...);
}
class CheesyPizzaDecorator : AbstractPizzaDecorator
{
public string Cheese { get; set; }
public print(...);
}
void Main()
{
BigPizza = new Pizza();
BigPizza.Size = 36;
HotBigPizza = new HotPizzaDecorator();
HotBigPizza.Pizza = BigPizza;
HotBigPizza.Hotness = 3;
HotBigCheesyPizza = new CheesyPizzaDecorator();
HotBigCheesyPizza.Pizza = HotBigPizza;
HotBigCheesyPizza.Cheese = "Blue";
HotBigCheesyPizza.print();
HotBigCheesyPizza.size = 28; // ERRRRRR !
}
Now if they all implement the print method and propagate that though the chain, it's all good. But how does that work for the state? I can't access the size property on the HotBigCheesyPizza.
What's the part that I'm missing? Wrong pattern?
Thanks for helping!
Cheers
The decorator pattern is for adding additional behavior to the decorated class without the client needing to adjust. Thus it is not intended for adding a new interface (e.g. hotness, cheese) to the thing being decorated.
A somewhat bad example of what it might be used for is where you want to change how size is calculated: you could create a MetricSizePizzaDecorator that converts the size to/from English/metric units. The client would not know the pizza has been decorated - it just calls getSize() and does whatever it needs to do with the result (for example, to calculate the price).
I would probably not use the decorator in my example, but the point is: it does not alter the interface. In fact, nearly all design patterns come down to that - adding variability to a design without changing interfaces.
one way of adding state is by using a self referential data structure (a list). but this uses the visitor pattern and does more than you probably want. this code is rewritten from A little Java, a few patterns
// a self referential data structure with different types of nodes
abstract class Pie
{
abstract Object accept(PieVisitor ask);
}
class Bottom extends Pie
{
Object accept(PieVisitor ask) { return ask.forBottom(this); }
public String toString() { return "crust"; }
}
class Topping extends Pie
{
Object topping;
Pie rest;
Topping(Object topping,Pie rest) { this.topping=topping; this.rest=rest; }
Object accept(PieVisitor ask) { return ask.forTopping(this); }
public String toString() { return topping+" "+rest.toString(); }
}
//a class to manage the data structure
interface PieManager
{
int addTopping(Object t);
int removeTopping(Object t);
int substituteTopping(Object n,Object o);
int occursTopping(Object o);
}
class APieManager implements PieManager
{
Pie p=new Bottom();
// note: any object that implements a rational version of equal() will work
public int addTopping(Object t)
{
p=new Topping(t,p);
return occursTopping(t);
}
public int removeTopping(Object t)
{
p=(Pie)p.accept(new RemoveVisitor(t));
return occursTopping(t);
}
public int substituteTopping(Object n,Object o)
{
p=(Pie)p.accept(new SubstituteVisitor(n,o));
return occursTopping(n);
}
public int occursTopping(Object o)
{
return ((Integer)p.accept(new OccursVisitor(o))).intValue();
}
public String toString() { return p.toString(); }
}
//these are the visitors
interface PieVisitor
{
Object forBottom(Bottom that);
Object forTopping(Topping that);
}
class OccursVisitor implements PieVisitor
{
Object a;
OccursVisitor(Object a) { this.a=a; }
public Object forBottom(Bottom that) { return new Integer(0); }
public Object forTopping(Topping that)
{
if(that.topping.equals(a))
return new Integer(((Integer)(that.rest.accept(this))).intValue()+1);
else return that.rest.accept(this);
}
}
class SubstituteVisitor implements PieVisitor
{
Object n,o;
SubstituteVisitor(Object n,Object o) { this.n=n; this.o=o; }
public Object forBottom(Bottom that) { return that; }
public Object forTopping(Topping that)
{
if(o.equals(that.topping))
that.topping=n;
that.rest.accept(this);
return that;
}
}
class RemoveVisitor implements PieVisitor
{
Object o;
RemoveVisitor(Object o) { this.o=o; }
public Object forBottom(Bottom that) { return new Bottom(); }
public Object forTopping(Topping that)
{
if(o.equals(that.topping))
return that.rest.accept(this);
else return new Topping(that.topping,(Pie)that.rest.accept(this));
}
}
public class TestVisitor
{
public static void main(String[] args)
{
// make a PieManager
PieManager pieManager=new APieManager();
// add some toppings
pieManager.addTopping(new Float(1.2));
pieManager.addTopping(new String("cheese"));
pieManager.addTopping(new String("onions"));
pieManager.addTopping(new String("cheese"));
pieManager.addTopping(new String("onions"));
pieManager.addTopping(new String("peperoni"));
System.out.println("pieManager="+pieManager);
// substitute anchovies for onions
int n=pieManager.substituteTopping(new String("anchovies"),new String("onions"));
System.out.println(n+" pieManager="+pieManager);
// remove the 1.2's
n=pieManager.removeTopping(new Float(1.2));
System.out.println(n+" pieManager="+pieManager);
// how many anchovies do we have?
System.out.println(pieManager.occursTopping(new String("anchovies"))+" anchovies");
}
}
I believe your component Pizza and your abstract decorator PizzaDecorator are supposed to share the same interface, that way each instance of the decorator is capable of the same operations as the core component Pizza.

RhinoMocks Testing callback method

I have a service proxy class that makes asyn call to service operation. I use a callback method to pass results back to my view model.
Doing functional testing of view model, I can mock service proxy to ensure methods are called on the proxy, but how can I ensure that callback method is called as well?
With RhinoMocks I can test that events are handled and event raise events on the mocked object, but how can I test callbacks?
ViewModel:
public class MyViewModel
{
public void GetDataAsync()
{
// Use DI framework to get the object
IMyServiceClient myServiceClient = IoC.Resolve<IMyServiceClient>();
myServiceClient.GetData(GetDataAsyncCallback);
}
private void GetDataAsyncCallback(Entity entity, ServiceError error)
{
// do something here...
}
}
ServiceProxy:
public class MyService : ClientBase<IMyService>, IMyServiceClient
{
// Constructor
public NertiAdminServiceClient(string endpointConfigurationName, string remoteAddress)
:
base(endpointConfigurationName, remoteAddress)
{
}
// IMyServiceClient member.
public void GetData(Action<Entity, ServiceError> callback)
{
Channel.BeginGetData(EndGetData, callback);
}
private void EndGetData(IAsyncResult result)
{
Action<Entity, ServiceError> callback =
result.AsyncState as Action<Entity, ServiceError>;
ServiceError error;
Entity results = Channel.EndGetData(out error, result);
if (callback != null)
callback(results, error);
}
}
Thanks
Played around with this a bit and I think I may have what you're looking for. First, I'll display the MSTest code I did to verify this:
[TestClass]
public class UnitTest3
{
private delegate void MakeCallbackDelegate(Action<Entity, ServiceError> callback);
[TestMethod]
public void CallbackIntoViewModel()
{
var service = MockRepository.GenerateStub<IMyServiceClient>();
var model = new MyViewModel(service);
service.Stub(s => s.GetData(null)).Do(
new MakeCallbackDelegate(c => model.GetDataCallback(new Entity(), new ServiceError())));
model.GetDataAsync(null);
}
}
public class MyViewModel
{
private readonly IMyServiceClient client;
public MyViewModel(IMyServiceClient client)
{
this.client = client;
}
public virtual void GetDataAsync(Action<Entity, ServiceError> callback)
{
this.client.GetData(callback);
}
internal void GetDataCallback(Entity entity, ServiceError serviceError)
{
}
}
public interface IMyServiceClient
{
void GetData(Action<Entity, ServiceError> callback);
}
public class Entity
{
}
public class ServiceError
{
}
You'll notice a few things:
I made your callback internal. You'll need to use the InternalsVisisbleTo() attribute so your ViewModel assembly exposes internals to your unit tests (I'm not crazy about this, but it happens in rare cases like this).
I use Rhino.Mocks "Do" to execute the callback whenever the GetData is called. It's not using the callback supplied, but this is really more of an integration test. I assume you've got a ViewModel unit test to make sure that the real callback passed in to GetData is executed at the appropriate time.
Obviously, you'll want to create mock/stub Entity and ServiceError objects instead of just new'ing up like I did.