Has anyone implemented Futures in Objective-C? I (hopefully not naively) assume that it should be reasonably simple to wrap NSInvocations in a nice API?
Mike Ash has implemented Futures using Blocks:
http://www.mikeash.com/pyblog/friday-qa-2010-02-26-futures.html
http://www.mikeash.com/pyblog/friday-qa-2010-03-05-compound-futures.html
PromiseKit seems quite popular. There's my Collapsing Futures library. There's also RXPromise. And plenty more.
Some notes between those three:
PromiseKit has Swift support
Each can be installed via CocoaPods.
Each automatically flattens doubly-future values into singly-future values.
Each is thread-safe.
RXPromise and PromiseKit act like Promises/A+ from JavaScript.
They differ in how futures are controlled. In collapsing futures there's a FutureSource, which has-a future instead of is-a future. In RXPromise and PromiseKit, a future is its own source.
They differ in how future are cancelled. In RXPromise the consumer calls cancel on the future itself. In collapsing futures, the producer cancels a token it gave to the method that made the future. I don't know what PromiseKit does.
All have excellent documentation on each method.
I'm biased towards collapsing futures, since I wrote it and so clearly prefer the design decisions it made. I think keeping control separate is hugely important because it helps prevent self-sustaining reference cycles (not an issue in JS, but definitely an issue in Obj-C when working with blocks). I also think cancel tokens simply make things easier. On the other hand, acting like a well-known spec from a well-known language would be really nice.
MPWFoundation has futures based on Higher Order Messaging:
Assuming you have a regular computation with a message computeResult:
result = [someObject computeResult];
prefixing that message with the future message will compute the result in the background:
result = [[someObject future] computeResult];
The object in result is a proxy that will block when messages are sent to it until the value is received.
Apple's documentation on blocks in Grand Central Dispatch may be of interest.
Related
I would think this question have been asked before, but I was not immediately able to find related SO questions, or articles elsewhere for that matter.
It strikes me that certain terms in AOP are rather strange. It seems I'm not the only one - this article, for instance, notes that "unfortunately, AOP terminology is not particularly intuitive". However, I have not found a resource explaining why they are not more "intuitive", if that's possible.
More specifically: I can somewhat understand "aspect" and "join points" - they seem descriptive enough. But "pointcuts" and "advice" seem somewhat odd. How did these terms come about?
I think knowing the etymology of these terms will help in remembering them better, if not allowing for some insight into the thinking of AOP's designers. At least, I hope this will help me from ever blubbering out nonsensical things like "cut points" or "advice points" in meetings...
Totally agree with your frustration. Each terminology has it's use but everytime I have to deal with AOP I sometimes have to refresh my memory on what each terminology does.
What helps me is that the whole AOP is based on single concept of Method interceptor that can be applied to method, can decide if it needs to take action on that method call and apply custom logic to before and after that method call.
Take a look at Springs org.aopalliance.intercept.MethodInterceptor and it's inheritance hierarchy. For example the advice is actually an abstract definition of MethodInterceptor and pointcut is the logic of selecting to which methods to apply that advice (or MethodIntercptor).
As far as I can remember even pointcut is just another method interceptor that delegates to a method interceptor.
Etymology will not help much. You will just have to learn the terminology. But as for historical information about how some terms came about to be used, maybe you need to perform a web search, it is not really a question for Stack Overflow. At least I found some background info about the term advice for you.
Update: Actually there are not so many technical terms you need to be familiar with. The following is from one of my AOP slides. I use them in order to introduce AOP to developers when coaching them:
What is an aspect?
An aspect contains all necessary elements to implement a cross-cutting concern in a modular way. So, it is much like what a class is for a core concern.
An aspect can, like a class, contain some kind of "methods" called advice and data. It can be a singleton or instantiated multiple times, depending on its usage.
Because an aspect is defined independently of the core system, we need something else to weave its orthogonal functionality into the core code. This something is called a pointcut and determines where an advice should be applied, e.g. before or after certain method calls, upon an exception, when an object is created and so forth.
Any place or event in the core code where aspect code can potentially be woven in is called a joinpoint.
If you need a crib or memory hook, maybe this helps (please note the words in italics):
The aspect method which advises the core code about how to apply a cross-cutting concern, is called advice.
Each point in your core code which you can hook into in order to apply a cross-cutting concern, is called a joinpoint.
You cut a slice (or subset) off of your core code joinpoints by means of a query syntax (like SQL selects table rows) called pointcut.
I was looking into Fractal (tldr : data object/collection to json formatting library) today and saw some benefits to using it. However it's functionality seems to span across multiple layers of the app I'm working on. Hence a question appeared -- where does a code utilising Fractal belong to? Model, service, controller, some other place? The examples given in the documentation at the project docs seem to favour putting it in the controller or right in a route callback (more complex examples seem to be coming from Laravel app and the author mentioned it in his book on API).
My concern is coupling -- if I put it in the controller, as most of the usage examples show, then I'm pretty much bound to it in the future. My first instinct is to abstract it a little, make that abstraction bound to a contract and then put it to use. Might sound over engineered, but the API I'm working on "is aspiring" to be JSON-API compliant, so exchanging such a "json formatter" for something else sounds less crazy. Besides I still need to format error messages and Fractal seems no to touch that at all.
I'd like to take advantage of support for Eloquent's paginator and embedded resources, because that's always a pain. Only doing that makes it awkward (to say the least) at presentation/control layer. Even in the Fractal docs they resort to adding some extra methods to the controller class to prep Fractal objects. It seems a bit weird to me, but maybe it's just me. That's why take it here.
I'm aware that it might be a matter of preference, but I'm counting on somebody to have a reasonably sounding one :). Or perhaps a better solution altogether, keeping in mind that automation and json-api compliance are key reasons.
I did this once with an API class for a proprietary system with which my application needed to interface. The API returned objects that looked a lot like models, so I implemented a number of classes for the objects I needed and implemented a library to make the API calls and return the objects. Luckily, I only needed read access to the API, so my library implements only a small subset of the actions available.
Maybe you could abstract all the functionality you need (both Fractal and any Eloquent features) into a library class for which you have defined an interface. That way all the Fractal code is in one place and if you ever need to replace it, you just rewrite your custom library class (which might be a lot of work, but probably better than hunting down references to Fractal sprinkled throughout your code).
I'm new to Reactive Programming. I have gone through the documentation of Reactive Cocoa but couldn't realize the differences between RACAble(), RACObserve() and RACBind().
Please, help ,me in understanding the aspects by some example code snippets.
I think the RACAble() is replaced with RACObserve() with some options/arguments. If I am not correct then please correct me in this regard.
Is RACObserve() skip: similar to RACAble()?
I think one big source of confusion here is that 3 months ago the ReactiveCocoa team released v2.0, which had quite a few breaking changes. This was a great release - and has some amazing features, but it does mean that much of the information you will find on the web is now out-dated.
To your specific points:
RACAble has been replaced with RACObserve
RACBind has been replaced with RACChannelTo
RACObserve is used to create a signal from an object and a keypath, in other words it allows you to take regular properties and 'lift' them into the ReactiveCocoa world. It is a handy replacement for KVO.
RACChannelTo provides a mechanism for two-way binding. In other words you can keep two properties synchronised. A good example of this is if you want to have a property in your view controller, or some model class, bound to a property on a UIKit control.
Another macro you will probably come across is RAC, this provides one-way binding. In other words it will set the value of the given property based on the latest value from a signal.
While implementating aspect oriented programming i am getting confuse
Why Dojo having to two differentaspect library files?
When to use
dojo.aspect and dojox.lang.aspect ?
I have never heard about dojox.lang.aspect before, but according to git log the latest commit dates to 2008.
You can find an explanation why dojox.lang.aspect exists in an article by its author Eugene Lazutkin: AOP aspect of JavaScript with Dojo.
While it doesn't make much sense in some cases, we should realize that the primary role of dojo.connect() is to process DOM events.
[...]
To sum it up: events != AOP. Events cannot simulate all aspects of AOP, and AOP cannot be used in lieu of events.
So AOP in JavaScript sounds simple! Well, in reality there are several sticky places:
Implementing every single advice as a function is expensive.
Usually iterations are more efficient than recursive calls.
The size of call stack is limited.
If we have chained calls, it'll be impossible to rearrange them. So if we want to remove one advice in the middle, we are out of luck.
The “around” advice will “eat” all previously attached “before” and “after” advices changing the order of their execution. We cannot guarantee anymore that “before” advices run before all “around” advices, and so on.
Usually in order to decouple an “around” advice from the original function, the proceed() function is used. Calling it will result in calling the next-in-chain around advice method or the original method.
Our aspect is an object but in some cases we want it to be a static object, in other cases we want it to be a dynamic object created taking into account the state of the object we operate upon.
These and some other problems were resolved in dojox.lang.aspect (currently in the trunk, will be released in Dojo 1.2).
As of the latest Dojo 1.7, there is a strong tendency to differentiate between events and aspects, i.e. between dojo/on and dojo/aspect (both were implemented via dojo.connect before).
From a usage standpoint, dojo/aspect is a very simplified version of dojox/lang/aspect.
With dojo/aspect, you can create aspects corresponding to a named function (e.g. the "get" method in the "xhr" class), allowing you to create a before, after or around advice anytime xhr.get is called.
On the other hand, (TMHO) only dojox/lang/aspect provides enough features to play with aop.
It allows you to define your pointcuts with regular expressions, therefore allowing things like "execute an around advice for any functions whose name starts with get on any object"...
You can even pass-in an array of function names or regular expressions to which your aspects will be applied.
The blog post pointed by phusick gives good examples of that.
I'm currently making a client-client approach on some simulation with objective-c with two computers (mac1 and mac2).
I have a class Client, and every computer has a instance of the "Client" on it (client1,client2). I expect that both clients will be synchronized: they will both be equal apart from memory locations.
When a user presses a key on mac1, I want both client1 and client2 to receive a given method from class Client (so that they are synchronized, i.e. they are the same apart from it's memory location on each mac).
To this approach, my current idea is to make 2 methods:
- (void) sendSelector:(Client*)toClient,...;
- (void) receiveSelector:(Client*)fromClient,...;
sendSelector: uses NSStringFromSelector() to transform the method to a NSString, and send it over the network (let's not worry about sending strings over net now).
On the other hand, receiveSelector: uses NSSelectorFromString() to transform a NSString back to a selector.
My first question/issue is: to what extent is this approach "standard" on networking with objective-c?
My second question:
And the method's arguments? Is there any way of "packing" a given class instance and send it over the network? I understand the pointer's problem when packing, but every instance on my program as an unique identity, so that should be no problem since both clients will know how to retrieve the object from its identity.
Thanks for your help
Let me address your second question first:
And the method's arguments? Is there any way of "packing" a given
class instance and send it over the network?
Many Cocoa classes implement/adopt the NSCoding #protocol. This means they support some default implementation for serializing to a byte stream, which you could then send over the network. You would be well advised to use the NSCoding approach unless it's fundamentally not suited to your needs for some reason. (i.e. use the highest level of abstraction that gets the job done)
Now for the more philosophical side of your first question; I'll rephrase your question as "is it a good approach to use serialized method invocations as a means of communication between two clients over a network?"
First, you should know that Objective-C has a not-often-used-any-more, but reasonably complete, implementation for handling remote invocations between machines with a high level of abstraction. It was called Distributed Objects. Apple appears to be shoving it under the rug to some degree (with good reason -- keep reading), but I was able to find an old cached copy of the Distributed Objects Programming Topics guide. You may find it informative. AFAIK, all the underpinnings of Distributed Objects still ship in the Objective-C runtime/frameworks, so if you wanted to use it, if only to prototype, you probably could.
I can't speculate as to the exact reasons that you can't seem to find this document on developer.apple.com these days, but I think it's fair to say that, in general, you don't want to be using a remote invocation approach like this in production, or over insecure network channels (for instance: over the Internet.) It's a huge potential attack vector. Just think of it: If I can modify, or spoof, your network messages, I can induce your client application to call arbitrary selectors with arbitrary arguments. It's not hard to see how this could go very wrong.
At a high level, let me recommend coming up with some sort of protocol for your application, with some arbitrary wire format (another person mentioned JSON -- It's got a lot of support these days -- but using NSCoding will probably bootstrap you the quickest), and when your client receives such a message, it should read the message as data and make a decision about what action to take, without actually deriving at runtime what is, in effect, code from the message itself.
From a "getting things done" perspective, I like to share a maxim I learned a while ago: "Make it work; Make it work right; Make it work fast. In that order."
For prototyping, maybe you don't care about security. Maybe when you're just trying to "make it work" you use Distributed Objects, or maybe you roll your own remote invocation protocol, as it appears you've been thinking of doing. Just remember: you really need to "make it work right" before releasing it into the wild, or those decisions you made for prototyping expedience could cost you dearly. The best approach here will be to create a class or group of classes that abstracts away the network protocol and wire format from the rest of your code, so you can swap out networking implementations later without having to touch all your code.
One more suggestion: I read in your initial question a desire to 'keep an object (or perhaps an object graph) in sync across multiple clients.' This is a complex topic, but you may wish to employ a "Command Pattern" (see the Gang of Four book, or any number of other treatments in the wild.) Taking such an approach may also inherently bring structure to your networking protocol. In other words, once you've broken down all your model mutation operations into "commands" maybe your protocol is as simple as serializing those commands using NSCoding and shipping them over the wire to the other client and executing them again there.
Hopefully this helps, or at least gives you some starting points and things to consider.
These days it would seem that the most standard way is to package everything up on JSON.