In Squeak, how to wrap every method send? - smalltalk

I created a class, and in that class I have a method 'sendMessage: to: withArgs:' which recieves an object, a message and an array of arguments.
The method is used to send messages to object and perform some algorithm.
To use this method I have to create an instance x of the class I created and do something like x sendMessage: '+' to: '7' withArgs: '#(5)'.
The result of this sending the message '+' to the object 7 with the parameter 5, plus some stuff that my algorithm does. But what I want is that the algorithm will be used in every method call, meaning 7+5 will call my 'sendMessage: to: withArgs:'.
How can I do that? Or at least, Is there something called in each method sent to every object?

It's kinda funny, we were just discussing that in the Squeak irc channel. Take a peek at ObjectViewer, perhaps.
In your example, you want to intercept the message sends to a SmallInteger. Funnily enough, ObjectViewer works with very much every class BUT SmallInteger.
So, to intercept message sends to myObject, do this.
Create class Intercepter, let it inherit from ObjectTracer, perhaps. Change doesNotUnderstand to something that serves you:
doesNotUnderstand: aMessage
"do Mojo to aMessage as you describe it"
Then, to get your stuff going, create your Intercepter:
myIntercepter := Intercepter on: myObject.
And then
myObject become: myInterceptor.

In Squeak, see the class ObjectTracer. The class comment describes how to use it. You should be able to accomplish what you need with that, or at least using that as a model.

Have a look at the Reflectivity.
Unfortunately some of the paper links are not working, and I don't remember the exact invocation from the top of my head, but it's really easy to instrument code as you want, and even do it at runtime. Look for examples using class Link.

You can use method wrappers. To see what method wrappers are you can look for a paper called "Wrappers to the rescue". I think there is a package for squeak that already implements method wrappers.
In addition, you can see how a test code coverage analysis is made in the last version of Pharo because it uses a kind of method wrapper to see what methods are evaluated during a test run.
cheers,
Gaboto

Related

From a ByteBuddy-generated method, how do I set a (public) instance field in an object received as an argument to the return value of a MethodCall?

I am generating a class in ByteBuddy.
As part of one method implementation, I would like to set a (let's just say) public instance field in another object to the return value of a MethodCall invocation. (Keeping the example public means that access checks etc. are irrelevant.)
I thought I could use MethodCall#setsField(FieldDescription) to do this.
But from my prior question related to this I learned that MethodCall#setsField(FieldDescription) is intended to work only on fields of the instrumented type, and, looking at it now, I'm not entirely sure why or how I thought it was ever going to work.
So: is there a way for a ByteBuddy-generated method implementation to set an instance field of another object to the return value of a method invocation?
If it matters, the "instrumented method" (in ByteBuddy's terminology) accepts the object whose field I want to set as an argument. Naïvely I'd expect to be able to do something like:
MethodCall.invoke(someMethod).setsField(somePublicField).onArgument(2);
There may be problems here that I am not seeing but I was slightly surprised not to see this DSL option. (It may not exist for perfectly good reasons; I just don't know what they would be.)
This is not possible as of Byte Buddy 1.10.18, the mechanism was originally created to support getters/setters when defining beans, for example. That said, it would not be difficult to add; I think it would even be easiest to allow any custom byte code to be dispatched as a consumer of the method call.
I will look into how this can be done, but as a new feature, this will take some time before I find the empty space to do so. The change is tracked on GitHub.

Is there a way to mark a method as pending to implement in Pharo?

Just wondering if you can mark a method as pending to implement in pharo, like you can do in java using "todo"
I'ts really hard for me to keep track of what's complete on pharo without something like that
Methods whose implementation is still pending should send the notYetImplemented message like this:
methodImNotSureHowToImplement
^self notYetImplemented
if the unimplemented message gets sent anyway, it will signal a NotYetImplemented exception which will know the offending selector, #methodImNotSureHowToImplement in my example.
Note also that this will make it easy finding all methods that need to be implemented as senders of #notYetImplemented.
The implementation of #notYetImplemented is straightforward, thanks to the existence of NotYetImplemented.
notYetImplemented
"Announce that this message is not yet implemented"
NotYetImplemented signalFor: thisContext sender selector
Note also that NotYetImplemented is one of the subclasses of SelectorException which model several situations of similar kinds:
SelectorException
NotYetImplemented
PrimitiveFailed
ShouldBeImplemented
ShouldNotImplement
SubclassResponsibility
I found the solution for this by myself 2 days after asking about it, almost accidentally, just using the context menu option jump to test method over a method without any test. Pharo automatically generated an empty test with this:
self flag: #toImplement.
self assert: false`
the first line, which can be used not only on tests, gives me the behavior I expected as it automatically categorizes the method containing it on a flags category marked with a big "!" allowing to easily check at glance which methods are pending.
The second line forces test to fail and be shown on yellow which is pretty useful because if it's empty it will pass and be shown on green, probably leading to believe it's already done when is not the case. A similar effect can be achieved just using self notYetImplemented
I would probably start doing something like this with my incomplete methods:
MyIncompleteMethod
self flag: #toImplement.
self notYetImplemented.`
you also can use pragmas to mark such methods
As Smalltalk provides the origin of agile development, let me provide a different answer. In a failing unit test. As you are not supposed to have a lot of those, it automatically provides the pressure to limit work in progress (the number of open #toDo's).

Reusing Java classes with procedural-style code?

There's a solid chance I'm misusing classes here which is why I need your help.
I've started developing with Java EE and one of the problems I am facing is I have a process which I have organised in a class, call it: "SendEmail.java".
Now let's say I have two other classes called "Thunderalert.java" and "FloodAlert.java" which will use all the methods that SendEmails.java has within it.
So I want to know the best way of using the SendEmails methods from each of the other classes.
Should I be creating an instance of SendEmails and accessing each method individually and error checking along the way (what if an exception is thrown?).. It's methods are just procedural code, so it's not really an 'object' as such
Shall I just be using the one method that runs all the other internal ones from within SendMail
Should this SendMail be redesigned as a helper class-type design?
I'm still quite new at Java EE so I'm not sure if there are any options available which I am missing
I think you should have one public method inside SendEmail class.
Btw, I would consider changing its name. I think having method send() when class is called SendEmail is not the best way (not to mention about names like call(), invoke() etc).
This is great article about this problem (The Kingdom of Nouns) in java.
What about something like: new Email(recipient, body).send()?
Or if you want to do it in a service style, I'd call it for example MailService

Why do we need a "receiver" class in the Command design pattern

I am learning command design pattern. As far as I know, four terms always associated with the command pattern are command, receiver, invoker and client.
A concrete command class has an execute() method and the invoker has a couple of commands. The invoker decides when to call the execute() method of a command.
When the execute() method is called, it calls a method of the receiver. Then, the receiver does the work.
I don't understand why do we need the receiver class? We can do the work inside execute() method, it seems that the receiver class is redundant.
Thank in advance.
Design patterns are used to solve software problems.
You have to understand the problem before trying to understand the solution (in this case Command pattern)
The problems which command pattern apply are in the context of an object A (client) invoking a method in an object B (receiver), so the Receiver is part of the problem, not part of the solution.
The solution or idea that command pattern offers is to encapsulate the method invocation from A to B in an object (Command), in fact this is close to the formal pattern definition. When you manage a request as an object you are able to solve some problems or to implement some features. (you also will need other pieces like the one called Invoker)
This list can give you some good examples of what kind of problems o features are suitable for command pattern.
note: Comamnd pattern is not necesary about decoupling, in fact the most common example pattern immplementation, the client needs to make a new instance of the receiver so we cannot talk about decoupling here.
Imagine a class that can do couple of things, like Duck, it can eat and quack. Duck is a receiver in this example. To apply command pattern here, you need to be able to wrap eating and quacking into a command. They should be separate classes that derive from Command base class with execute() method because Duck can have only single execute() method. So EatCommand.execute() calls Duck.eat() and QuackCommand.execute() calls Duck.quack().
The goal of the command pattern is to decouple the invoker from the receiver.
The receiver must do the work ,not the command itself , the command just knows what is the receiver method to call, or the command can execute other commands . With the command pattern the invoker doesnt know what is being called expect for the command.
So a command can be reused by many invokers to execute the same action on the receiver.
Short answer is depends. This is not based on my opinion alone. From GOF, Command Pattern, Implementation (page 238)
"How intelligent should a command be? A command can have a wide range of abilities. At one extreme it merely defines a binding between a receiver and the actions that carry out the request. At the other extreme it implements everything itself without delegating to a receiver at all. The latter extreme is useful when you want to define commands that are independent of existing classes, when no suitable receiver exists, or when a command knows its receiver implicitly. For example, a command that creates another application window may be just as capable of creating the window as any other object."
So I do not think one should create a receiver class just for the sake of it, or because most example say so. Create it only if there is a real need. One such case is when a class that acts as a receiver already exists as a separate class. If you have to write the code that is going to be invoked/executed and see no reason to create a separate class for that, then I do not see any fault in adding the invoker code to Command itself.

Generate a Mock object with a Method which raises an event

I am working on a VB.NET project which requires the extensive used of Unit Tests but am having problems mocking on of the classes.
Here is a breakdown of the issue:
Using NUnit and Rhino Mock 3.6
VS2010 & VB.NET
I have an interface which contains a number of methods and an Event.
The class which implements that Interface raises the event when one of the methods is called.
When I mock the object in my tests I can stub methods and create/assert expectations on the methods with no problems.
How do I configure the mock object so that when a method is called the event is raised so that I can assert that is was raised?
I have found numerous posts using C# which suggest code like this
mockObject.MyEvent += null...
When I try this 'MyEvent' does not appear in Intellisense.
I'm obviously not configuring my test/mock correctly but with so few VB.NET examples out there I'm drawing a blank.
Sorry for my lack of VB syntax; I'm a C# guy. Also, I think you should be congratulated for writing tests at all, regardless of test first or test last.
I think your code needs refactoring. It sounds like you have an interface that requires implementations to contain an event, and then another class (which you're testing) depends on this interface. The code under test then executes the event when certain things happen.
The question in my mind is, "Why is it a publically exposed event?" Why not just a method that implementations can define? I suppose the event could have multiple delegates being added to it dynamically somewhere, but if that's something you really need, then the implementation should figure out how that works. You could replace the event with a pair of methods: HandleEvent([event parameters]) and AddEventListener(TheDelegateType listener). I think the meaning and usage of those should be obvious enough. If the implementation wants to use events internally, it can, but I feel like that's an implementation detail that users of the interface should not care about. All they should care about is adding their listener and that all the listeners get called. Then you can just assert that HandleEvent or AddEventListener were called. This is probably the simplest way to make this more testable.
If you really need to keep the event, then see here for information on mocking delegates. My advice would be to mock a delegate, add it to the event during set up, and then assert it was called. This might also be useful if you need to test that things are added to the event.
Also, I wouldn't rely on Intellisense too much. Mocking is done via some crafty IL code, I believe. I wouldn't count on Intellisense to keep up with members of its objects, especially when you start getting beyond normal methods.