How to initialize an object and override a method in objective c? - 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;
}

Related

GWT with Serialization

This is my client side code to get the string "get-image-data" through RPC calls and getting byte[] from the server.
CommandMessage msg = new CommandMessage(itemId, "get-image-data");
cmain.ivClient.execute(msg, new AsyncCallback<ResponseMessage>() {
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(ResponseMessage result) {
if (result.result) {
result.data is byte[].
}
}
});
From the server side I got the length of the data is 241336.
But I could not get the value in onSuccess method. It is always goes to onFailure method.
And I got log on Apache:
com.google.gwt.user.client.rpc.SerializationException: Type '[B' was
not included in the set of types which can be serialized by this
SerializationPolicy or its Class object could not be loaded.
How can I do serialisation in GWT?
1) Create a pojo which implements Serializable interface
Let this pojo has all the data you want in the response of RPC service, in this case image-data
2) Pass this pojo in the response for your RPC service.
The below tutorial has enough information for creating RPC service
http://www.gwtproject.org/doc/latest/tutorial/RPC.html
The objects you transfer to and from the server has to implement IsSerializable.
All your custom Objects within the Object you are transferring also needs to implement IsSerializable.
Your objects cannot have final fields and needs an no argument constructor.
You need getters and setters.
A common serialize object in GWT:
public class MyClass implements IsSerializable {
private String txt;
private MyOtherClass myOtherClass; // Also implements IsSerializable
public MyClass() {
}
public String getTxt() {
return this.txt;
}
public void setTxt(String txt) {
return this.txt = txt;
}
public String getMyOtherClass() {
return this.myOtherClass;
}
public void setMyOtherClass(MyOtherClass myOtherClass) {
return this.myOtherClass = myOtherClass;
}
}

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.

Jmockit Expectations/Verifications for calls to private methods when testing a public method?

Can anyone advise if it is possible to use an expectations/verifications to test that private methods are being called the-right-number-of-times/right-parameters.
The Class under test has been Mocked-Up - with one private method overridden.
Am Testing a public method which calls into a number of private methods.
I wish to know if it is possible to verify the calls to other private methods which will be called when the public method is being executed ?
Some idea of the code/class under test;
public class UnderTest {
public void methodPublic(arg 1){
.....
methodPrivate1(var1);
....
methodPrivate2(var2);
}
private void methodPrivate1(var1){
//do stuff
}
private void methodPrivate2(var1){
//do stuff
}
}
In my test case
#Test
public void stateBasedTestMethod()
{
UnderTest underTest;
new MockUp<UnderTest>() {
#Mock(invocations = 1)
private void methodPrivate2(var1) {
//do nothing in the mocked case
}
};
underTest = new UnderTest();
underTest.methodPublic(arg1);
new Verifications() {{
// Is there a way to test that methodPrivate1 has been called-once/with-expected-arguments
}};
}
Edited in response to the answer from Rogério.
I am using jmockit 1.12
and the Verifications is FAILING as the method using the provided solution is invoking the method twice as I thought from the JMockit documentation.
Failure Trace;
mockit.internal.UnexpectedInvocation: Expected exactly 1 invocation(s) of MyHelperTest$1#method3..., but was invoked 2 time(s)
Included is the full code I am using for this.
As described above - my goal is to mock one of the private methods to do nothing.
And ensure that I can verify that the other private method is called only once.
Thanks in advance and hopefully will get a better understanding if this is possible with Jmockit.
Test Code.
public class MyHelperTest {
#Test
public void testHelper(#Mocked final MyDependent myDependent) {
final MyHelper myHelper;
new MockUp<MyHelper>() {
#Mock(invocations = 1)
private void method3(MyDependent myTable) {
System.out.println("In Mocked Method");
//do nothing in the mocked case
}
};
myHelper = new MyHelper();
myHelper.method1(myDependent);
new Verifications() {{
invoke(myHelper, "method2", myDependent); times = 1;
}};
}
}
Class under test.
public class MyHelper {
public void method1(MyDependent myDependent){
method2(myDependent);
}
private void method2(MyDependent myDependent) {
myDependent.setValue(1);
method3(myDependent);
}
private void method3(MyDependent myDependent) {
myDependent.setValue(2);
}
}
Dependent Class
public class MyDependent {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
It's possible, though not recommended to mock private methods.
Using the Expectations API:
#Tested #Mocked MyHelper myHelper;
#Test
public void testHelper(#Mocked final MyDependent myDependent)
{
new NonStrictExpectations() {{ invoke(myHelper, "method3", myDependent); }};
myHelper.method1(myDependent);
new Verifications() {{ invoke(myHelper, "method2", myDependent); times = 1; }};
}
... where the invoke(...) method is statically imported from class mockit.Deencapsulation.
I noticed that if a method you want to verify is not mocked, when the static block in an Expectations or Verifications instance is executed that the code calls the method that you are trying to mark as expected or verify.
This might explain the extra invocation that you are seeing.
One suggestion: if you are already mocking the class with MockUp (and thus creating an anonymous subclass) so you can override the private method, why not change the access of the overridden private method to protected or public? Then you can create an expectation or verification on it.
You could also provide a public field "public int counter=0;" and have your overridden method increment the counter. Then you can use an assert on it after the test is complete.

Interface Bloated with Callbacks

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!

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.