AkkaNet deprecated scheduler - how to replace it? - akka.net

I have a method:
Context.System.Scheduler.Schedule(
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(5),
Self,
message);
I am getting that this is deprecated and I should use
Context.SelfTellRepeatedly()
But there is no method like that - or maybe I am missing something?
Thanks for your time.

I think you're correct, it looks like this method is missing. I don't know if this is deliberate or not, it may be that the Obsolete message is out of date. Probably worth raising it as issue for the maintainers.
However, hopefully the message you're seeing is this one.
[Obsolete("Use ScheduleTellRepeatedly() or Context.SelfTellRepeatedly() instead.
This method will be removed in future versions.")]
public static void Schedule(this IScheduler scheduler,
TimeSpan initialDelay, TimeSpan interval, IActorRef receiver, object message)
The correct replacement would be the Scheduler.ScheduleTellRepeatedly() method, which does exist.

Related

How to make a class that inherits the same methods as IO::Path?

I want to build a class in Raku. Here's what I have so far:
unit class Vimwiki::File;
has Str:D $.path is required where *.IO.e;
method size {
return $.file.IO.s;
}
I'd like to get rid of the size method by simply making my class inherit the methods from IO::Path but I'm at a bit of a loss for how to accomplish this. Trying is IO::Path throws errors when I try to create a new object:
$vwf = Vimwiki::File.new(path => 't/test_file.md');
Must specify a non-empty string as a path
in block <unit> at t/01-basic.rakutest line 24
Must specify a non-empty string as a path
I always try a person's code when looking at someone's SO. Yours didn't work. (No declaration of $vwf.) That instantly alerts me that someone hasn't applied Minimal Reproducible Example principles.
So I did and less than 60 seconds later:
IO::Path.new
Yields the same error.
Why?
The doc for IO::Path.new shows its signature:
multi method new(Str:D $path, ...
So, IO::Path's new method expects a positional argument that's a Str. You (and my MRE) haven't passed a positional argument that's a Str. Thus the error message.
Of course, you've declared your own attribute $path, and have passed a named argument to set it, and that's unfortunately confused you because of the coincidence with the name path, but that's the fun of programming.
What next, take #1
Having a path attribute that duplicates IO::Path's strikes me as likely to lead to unnecessary complexity and/or bugs. So I think I'd nix that.
If all you're trying to do is wrap an additional check around the filename, then you could just write:
unit class Vimwiki::File is IO::Path;
method new ($path, |) { $path.IO.e ?? (callsame) !! die 'nope' }
callsame redispatches the ongoing routine call (the new method call), with the exact same arguments, to the next best fitting candidate(s) that would have been chosen if your new one containing the callsame hadn't been called. In this case, the next candidate(s) will be the existing new method(s) of IO::Path.
That seems fine to get started. Then you can add other attributes and methods as you see fit...
What next, take #2
...except for the IO::Path bug you filed, which means you can't initialize attributes in the normal way because IO::Path breaks the standard object construction protocol! :(
Liz shows one way to workaround this bug.
In an earlier version of this answer, I had not only showed but recommended another approach, namely delegation via handles instead of ordinary inheritance. I have since concluded that that was over-complicating things, and so removed it from this answer. And then I read your issue!
So I guess the delegation approach might still be appropriate as a workaround for a bug. So if later readers want to see it in action, follow #sdondley's link to their code. But I'm leaving it out of this (hopefully final! famous last words...) version of this answer in the hope that by the time you (later reader) read this, you just need to do something really simple like take #1.

Can I compose an InvokeDynamic with a FixedValue using Implementation.Composable#andThen()?

I am building a method "by hand" in ByteBuddy. The method I'm building has one parameter of type ProductType. Let's say it looks like this:
public ProductType frob(ProductType product) {
// stuff that I'm implementing and asking about goes here
}
Inside that method I am building the equivalent of:
product.foo(); // more on this below; foo() has a void return type, which may be important
return product; // FixedValue.argument(0)
This works fine when I build an Implementation like this:
MethodCall.invoke(fooMethodDescription) // invoke foo()...
.onArgument(0) // ...on product...
.andThen(FixedValue.argument(0)); // ...and then return product
(I hope I've typed that right.)
If, however, I build an Implementation like this:
InvokeDynamic.bootstrap(...) // look up foo()'s MethodHandle via my bootstrap method...
.invoke("foo", TypeDescription.VOID) // ...invoke the method handle with a return type of void...
.withArgument(0) // ..."on" the first and only argument (product) and "with" no other arguments...
.andThen(FixedValue.argument(0)); // ...and then return product
…with, of course, the proper InvokeDynamic recipe, the resulting class cannot be verified because of an Operand stack underflow error (Attempt to pop empty stack).
I have a similar InvokeDynamic recipe used many places elsewhere so I know that my problem is not with the InvokeDynamic usage. Rather, it seems to be with the composing? maybe? Is it possible that MethodCall and InvokeDynamic behave differently, even though both are Implementations? Maybe InvokeDynamic doesn't push something on the operand stack (maybe just in the case of void returns?) whereas MethodCall does? Is there something I'm missing in the andThen() usage?
Using ByteBuddy 1.11.2.
As you pointed out correctly, this is a bug in Byte Buddy that is now fixed. Thanks for that. It will be released with version 1.11.3.

#Around aspect and Kotlin suspended function

I try to understand how to create an #Around aspect for a Kotlin’s suspended function (for example, to measure time spent in this function, or for a custom #Transactional aspect):
#Timed("my-timer")
suspend fun test() {
println("before")
delay(50) // invokes ProceedingJoinPoint#proceed() before this line
println("after")
}
Since this function has a suspend function call, the #Around aspect’s proceed function will be invoked right before delay() call. But obviously I’d like to measure full time spent in the function.
What is the right way to solve it? Maybe I can somehow subscribe on the last continuation in the method, or smth like that?
I think you can solve your problem easily, if you want to measure, the execution time of function, you can do it using built-in functionality like this:
val time = measureTimeMillis {
// yourSuperFunc()
}
Also, you can use measureNanoTime. For full reference look at here.
This is tracked by https://github.com/spring-projects/spring-framework/issues/22462 and will most likely be fixed in 5.3
The same issue happens for #Transactional.

Mocking void functions using EasyMock with dynamic behaviour

I need to mock a void function with EasyMock such that the first call returns an Exception, while the next succeeds.
For example:
this.myObject.move((String) EasyMock.anyObject());
EasyMock.expectLastCall().once().andThrow(new RetryableDependencyException());
EasyMock.expectLastCall().once();
But this is not working.
That's not going to work as the second expectLastCall() cannot find any call.
Have you tried this:
this.myObject.move((String) EasyMock.anyObject());
EasyMock.expectLastCall().once().andThrow(new RetryableDependencyException());
this.myObject.move((String) EasyMock.anyObject());
EasyMock.expectLastCall().once();
I know it's a bit verbose but it should get you sorted :)
The shortest is
myObject.move(anyString());
expectLastCall().andThrow(new RetryableDependencyException()).asStub();
which assumes that is doesn't matter if the method is called more than once after the exception. If it matters, it will be
myObject.move(anyString());
expectLastCall().andThrow(new RetryableDependencyException());
myObject.move(anyString());
Interesting facts:
You can chain andReturn
I highly suggest static imports to get a cleaner code
anyString is used to prevent the cast in String
once() is not required as it is the default
expectLastCall isn't required, calling the void method is enough to record a call without any side effect (like a throw)

What is the appropriate amount of error-checking?

public void PublicMethod(FooBar fooBar)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null");
// log the call [added: Thanks S.Lott]
_logger.Log("PublicMethod called with fooBar class " + fooBar.Classification);
int action = DetermineAction();
PrivateMethod(fooBar, action);
}
private void PrivateMethod(FooBar fooBar, int action)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null"); // Is this line superfluous?
/*
Do something
*/
}
Is it OK to skip this kind of error checking in private methods if the input is already checked on the public interface? Usually there's some sort of rule-of-thumb one can go by...
Edit:
Maybe ArgumentNullException isn't such a good example because the argument can be made that you should check at both levels but return different error messages.
I would say no.
While it certainly holds true that you in this case knows that it has already been checked for nullability, in two months time the youngest intern will come along and write
PublicMethod2 that also calls PrivateMethod, but lo and behold he forgot to check for null.
Since the public method doesn't really use foobar, I'm not sure why it's checking. The current private method cares, but it's the private method's responsibility to care. Indeed, the whole point of a private method is to delegate all the responsibilities to it.
A method checks the input it actually uses; it doesn't check stuff it's just passing through.
If a different subclass has the same public method, but some different private method implementation -- one that can tolerate nulls -- what now? You have a public method that now has wrong constraints for the new subclass.
You want to do as little as possible in the public method so that various private implementations are free to do the right thing. Don't "over-check" or "just-in-case" check. Delegate responsibility.
I'd error check everything you can, you never know when something might happen that you didn't think about. (and its better safe than sorry)
When using design by contract (http://en.wikipedia.org/wiki/Design_by_contract) it’s normally client’s (public method) responsibility to make correct invocation, i.e. pass on valid parameters. In this particular scenario it depends whether null belongs to a set of valid input values, therefore there are 3 options:
1) Null is valid value: throwing exceptions or errors would have meant breaking the contract, the server (private method) has to process the null and shouldn’t complain.
2) Null is invalid value and passed by code within your control: it is up to the server (private method) to decide how to react. Obviously, throwing an exception is more graceful way of handling the situation, but it has a cost of having to handle that exception somewhere else up the stack. Exceptions are not the best way to deal with violation of contract caused by programming blunders. You really should throw exceptions not when a contract is already violated but when it cannot be fulfilled because of environmental problems what cannot be controlled in software. Blunders are better handled by sticking an assertion into the beginning of the private method to check that the parameter is not null. This will keep the complexity of your code down, there is no cost of having to handle the exception up the stack and it will achieve the goal of highlighting broken contracts during testing.
3) Then there is defensive programming (http://en.wikipedia.org/wiki/Defensive_programming). When dealing with parameters passed by an external code outside your control the immediate layer of your code needs to run paranoid level of checks and return errors according to its communication contract with the external world. Then, going deeper into the code layers not exposed externally, it still makes more sense to stick to the programming by contract.
At least put a comment that PrivateMethod must have a non-null FooBar and that PublicMethod checks this.
You might want to also mark the "private" method as private or protected.
That depends if a null-value indicates an error for a method. Remember that methods could also be called messages to an object; they operate on the state of the object aswell. Parameters can specialize the kind of message sent.
If publicMethod() does not use a parameter and changes the state of the instance while privateMethod() uses the parameter, do not consider it an error in publicMethod, but do in privateMethod().
If publicMethod() does not change state, consider it an error.
You could see the latter case as providing an interface to the internal functioning of an object.
I'd consider the answer to be "yes, do the check again" because:-
The private member could be reused again in the future from a different path through the code, so program defensively against that situation.
If you perform unit tests on private methods
My view might change if I had a static analyser that could pick this up and not flag the potential use of a null reference in the private method.
In cases where PrivateMethod will be called frequently with input that has already been verified, and only rarely with user input, Then I would use the PublicMethod/PrivateMethod concept with no error checking on PrivateMethod (and with PublicMethod doing nothing other then checking the parameters and calling PrivateMethod)
I would also call the private method something like PublicMethod_impl (for "implementation") so it's clear that it's an internal use/ no checking method.
I maintain that this design leads to more robust application, as it forces you to think about what's checked when. Too often people who always check parameters fall into the trap of "I've checked something, therefore I've checked everything".
As an example of this, a former co-worker (programming in C) would, before using a pointer, always check to see if it was null. Generally, the pointers in his code were initialized as startup and never changed, so the chances of it being null were quite low. Moreover, the pointer has one correct value and 65535 possible wrong values, and he was only checking for one of those wrong values.