Optional blocks in the middle of a method: safe? - objective-c

I have a method looking something like:
- (void)doSomething:(void(^)(MyItem *item))optionalBlock {
// 1. Do the regular stuff with the item
item.regularStuff = #"something_regular";
// 2. Run the optional block
// which may or may not make some extra modifications to the item
if (optionalBlock) optionalBlock(item);
// 3. Save the modified item into the Core Data
// etc
}
Which I’m planning to call either like this
[self doSomething:nil];
Or:
[self doSomething:^(MyItem *item) {
// Make some extra modifications to the item before it’s saved
item.custom = #"custom";
}];
Is it safe to assume that at the step three I’ll always get the item already modified by both the method and (potentially) the optional block, or do I need to implement some sort of a way to find out exactly when the block has finished executing so I can continue from there?

It's safe. You don't need any special check.

Yes and no.
Yes, it's safe, in that if the block contains only sequential code for modifying your item, all those modifications will be complete by the time control returns to your doSomething method.
However, if you allow the caller of your method to pass in an arbitrary block, there's no telling what it might do and when. It could set up timers, spawn threads, use dispatch_async, or do any number of other things which could cause it to in some sense not be truly "done" by the time it returns. You're handing over the car keys here -- there's nothing preventing the caller from taking a joyride.
Really, this is the sort of thing that's beyond the scope of the language and more about what sort of contract you define in the documentation of your API: if you want your callers to only modify the object during execution of that block, just tell them that's what you expect them to do and to not expect your API to work otherwise.

Related

Is there any delayed MultiCast-Event, which is able to be interruptable?

I am looking for an interruptable, delayed event, which I hope could be already part of Spring4D, or easily implemented there.
What would be best way anyway, to achieve this ?
Probably the Event wouldn't be the right place.
Basically looking for something like
Event.InvokeDelayed(1000, nil); and
Event.InvokeCancel;
procedure TTestMulticastEvent.Test;
var
e: Event<TNotifyEvent>;
begin
e.Add(HandlerA);
e.Invoke(nil); // Yes, this is the normal behaviour
// But would this make sense in Events,
// or better use other concept, like TTask.IdleWorker, e.g. ?
e.InvokeDelayed(1000, nil); // waits 1sec
Sleep(100); // Interrupts after 100ms
e.InvokeCancel; // Prevent future Event, started earlier
end;
Maybe I oversee something already available to solve this task in S4D.
Rollo
No, multicast events as they are in the library are synchronous. For them to work properly asynchronously in all cases it would require way more than just delaying their invokation but capturing any data you pass through them, make sure that data does not get invalid and so on.
If you need a mechanism like that you should use one of the existing libraries out there to do asynchronous things.
For example with the PPL (naive code to just show the concept):
var
e: Event<TNotifyEvent>;
t: ITask;
begin
e.Add(HandlerA);
t := TTask.Run(
procedure
begin
Sleep(1000);
if t.Status <> TTaskStatus.Canceled then
TThread.Synchronize(nil,
procedure
begin
e.Invoke(nil);
end);
end);
Sleep(100);
t.Cancel;
end;
You can probably wrap this into your own routine depending on your needs and the actual implementation. It will not be possible however to make a InvokeDelayed method with an additional parameter to what the event type has as signature because Event<T>.Invoke is not a method but a property returning T which you can invoke (which makes it look like a method call itself).
Anything beyond that requires as I said preserving the parameters passed to Invoke to pass them later (something that anonymous methods to for you to a certain degree) which is not trivial (at least not when we are talking about the generic Event<T>)

How to use OCMock to verify that an asynchronous method does not get called in Objective C?

I want to verify that a function is not called. The function is executed in an asynchronous block call inside the tested function and therefore OCMReject() does not work.
The way I have tested if async functions are indeed called would be as follows:
id mock = OCMClassMock([SomeClass class]);
OCMExpect([mock methodThatShouoldExecute]);
OCMVerifyAllWithDelay(mock, 1);
How would a test be done to test if a forbidden function is not called?
Something like:
VerifyNotCalled([mock methodThatShouoldExecute]);
OCMVerifyAllWithDelay(mock, 1);
I would recommend using an OCMStrictClassMock instead of the OCMClassMock (which gives you a nice mock). A strict mock will instantly fail your test if any method is called on it that you did not stub or expect, which makes your tests a lot more rigorous.
If that's not an option for you, you can do what you described with:
OCMReject([mock methodThatShouoldExecute]);
See the "Failing fast for regular (nice) mocks" section in the OCMock docs.
Now as for waiting for your code which may call the forbidden method, that's another matter. You can't use OCMVerifyAllWithDelay since that returns immediately as soon as all expectations are met, it doesn't wait around a full second to see if illegal calls will be made to it. One option is to put a 1 second wait before verifying the mock each time. Ideally, you could also wait explicitly on your asynchronous task with an XCTestExpectation. Something like:
XCTestExpectation *asyncTaskCompleted = [self expectationWithDescription:#"asyncTask"];
// Enqueued, in an onCompletion block, or whatever call
// ... [asyncTaskCompleted fulfill]
[self waitForExpectationsWithTimeout:1 handler:nil]

OCMock and overriding stub value

mockModule = OCMPartialMock(module);
OCMStub([mockModule send:#"FOO"]).andReturn(YES);
OCMStub([mockModule send:#"FOO"]).andReturn(NO);
In this example I have a simple mock module, and I set some stubs to return YES/NO when sent a String, the problem that occurs is that if I set the same string twice it only returns the first value, and not the new value.
In this example about the problem is demonstrated like so I would expect a call such as:
BOOL answer = [module send:#"FOO"]
//answer should be NO, but is YES
How can I make it respond with the most recently set value?
You could use the expect methods, e.g.
mockModule = OCMPartialMock(module);
OCMExpect([mockModule send:#"FOO"]).andReturn(YES);
OCMStub([mockModule send:#"FOO"]).andReturn(NO);
That's not exactly what they are meant for, but it does make some sense. You're basically saying, I expect that send: will be called, and when that has actually happened, then I want the method to be stubbed.
Also, if it were possible to "pile up" the stubs, figuring out what went wrong would be quite difficult, e.g. if the first invocation of the stub doesn't happen, then the second invocation will get the value meant for the first.

Alternative to the try (?) operator suited to iterator mapping

In the process of learning Rust, I am getting acquainted with error propagation and the choice between unwrap and the ? operator. After writing some prototype code that only uses unwrap(), I would like to remove unwrap from reusable parts, where panicking on every error is inappropriate.
How would one avoid the use of unwrap in a closure, like in this example?
// todo is VecDeque<PathBuf>
let dir = fs::read_dir(&filename).unwrap();
todo.extend(dir.map(|dirent| dirent.unwrap().path()));
The first unwrap can be easily changed to ?, as long as the containing function returns Result<(), io::Error> or similar. However, the second unwrap, the one in dirent.unwrap().path(), cannot be changed to dirent?.path() because the closure must return a PathBuf, not a Result<PathBuf, io::Error>.
One option is to change extend to an explicit loop:
let dir = fs::read_dir(&filename)?;
for dirent in dir {
todo.push_back(dirent?.path());
}
But that feels wrong - the original extend was elegant and clearly reflected the intention of the code. (It might also have been more efficient than a sequence of push_backs.) How would an experienced Rust developer express error checking in such code?
How would one avoid the use of unwrap in a closure, like in this example?
Well, it really depends on what you wish to do upon failure.
should failure be reported to the user or be silent
if reported, should one failure be reported or all?
if a failure occur, should it interrupt processing?
For example, you could perfectly decide to silently ignore all failures and just skip the entries that fail. In this case, the Iterator::filter_map combined with Result::ok is exactly what you are asking for.
let dir = fs::read_dir(&filename)?;
let todos.extend(dir.filter_map(Result::ok));
The Iterator interface is full of goodies, it's definitely worth perusing when looking for tidier code.
Here is a solution based on filter_map suggested by Matthieu. It calls Result::map_err to ensure the error is "caught" and logged, sending it further to Result::ok and filter_map to remove it from iteration:
fn log_error(e: io::Error) {
eprintln!("{}", e);
}
(|| {
let dir = fs::read_dir(&filename)?;
todo.extend(dir
.filter_map(|res| res.map_err(log_error).ok()))
.map(|dirent| dirent.path()));
})().unwrap_or_else(log_error)

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.