Why should I use Reify instead of proxy in clojure?
The method bodies of reify are lexical closures, and can refer to the surrounding local scope. reify differs from proxy in that:
Only protocols or interfaces are supported, no concrete superclass.
The method bodies are true methods of the resulting class, not external fns.
Invocation of methods on the instance is direct, not using map lookup.
No support for dynamic swapping of methods in the method map.
The result is better performance than proxy, both in construction and invocation. reify is preferable to proxy in all cases where its constraints are not prohibitive.
Source: http://clojure.org/datatypes
Use reify where you would once use proxy, unless you need to override base class methods.
Related
I implemented a class which depended on an interface for sending data.
Concrete versions of the interface were implemented for testing and for production and they were injected at construction (depending if the class was being tested or used in production)
This works but there is a maintainence overhead on maintaining multiple overloaded send functions that do very similiar things.
I would like to template the send function however that is impossible on an overriden function.
My next idea is rather than the class depending on an interface, it will contain a map of datatypes to callbacks. This means I can specify the functionality for each datatype and inject it into the class depending on if I want test functionality or real functionality.
The difficulty comes because the map has to store functions with different signatures because the paramter type is different for every function.
How best can I do this? Is the idea sound or is there a better design?
Ember's Em.ArrayProxy and Em.Array have many programatic methods available for notifying observers of changes to content. For example:
arrayContentDidChange
arrayContentWillChange
enumerableContentDidChange
enumerableContentWillChange
contentArrayWillChange
Em.ArrayProxy also has several methods for manipulating the ArrayProxy's content. For example:
this.pushObject('something random');
// Or
this.insertAt(2, 'something random');
When using the latter methods, does one have to use them in conjunction with the former methods? It seems silly that Ember's usually-automated property observers would require a manual kick here but I don't find the documentation very clear.
No, you don't have to use any methods in conjunction.
If you want to add items to your ArrayProxy, simply pushObject(). You would know this by just using the method and seeing that it just works.
From the docs:
This mixin implements Observer-friendly Array-like behavior. It is not a concrete implementation, but it can be used up by other classes that want to appear like arrays.
http://emberjs.com/api/classes/Ember.Array.html
Ember.Array is a type of class that in other programming languages (without mixins) receives the name of an interface.
An ArrayProxy wraps any other object that implements Ember.Array
http://emberjs.com/api/classes/Ember.ArrayProxy.html
Ember.ArrayProxy is exactly what the name says, a proxy, that wraps around any object that has implemented the Ember.Array interface.
The other methods, that you mention, might be implemented/overridden if you are making your own "subclass" of Ember.Array. Some must be implement to make your subclass ArrayProxy friendly. Or if you want to add custom behaviour, maybe write to a log whenever arrayContentDidChange, then you override that method and add whatever logic your app needs.
That is Object Oriented Programming and all those explanations are out of scope for the documentation of any framework.
Are you asking whether pushObject et cetera trigger those events?
From the documentation for insertAt:
This will use the primitive replace() method to insert an object at the specified index.
From the documentation for replace:
You should also call this.enumerableContentDidChange()
So, yes, a properly implemented ArrayProxy will trigger those events when you add or remove things.
What are the differences between Module and Class in OCaml.
From my searching, I found this:
Both provide mechanisms for abstraction and encapsulation, for
subtyping (by omitting methods in objects, and omitting fields in
modules), and for inheritance (objects use inherit; modules use
include). However, the two systems are not comparable.
On the one hand, objects have an advantage: objects are first-class
values, and modules are not—in other words, modules do not support
dynamic lookup. On the other hand, modules have an advantage: modules
can contain type definitions, and objects cannot.
First, I don't understand what does "Modules do not support dynamic lookup" mean. From my part, abstraction and polymorphism do mean parent pointer can refer to a child instance. Is that the "dynamic lookup"? If not, what actually dynamic lookup means?
In practical, when do we choose to use Module and when Class?
The main difference between Module and Class is that you don't instantiate a module.
A module is basically just a "drawer" where you can put types, functions, other modules, etc... It is just here to order your code. This drawer is however really powerful thanks to functors.
A class, on the other hand, exists to be instantiated. They contains variables and methods. You can create an object from a class, and each object contains its own variable and methods (as defined in the class).
In practice, using a module will be a good solution most of the time. A class can be useful when you need inheritance (widgets for example).
From a practical perspective dynamic lookup lets you have different objects with the same method without specifying to which class/module it belongs. It helps you when using inheritance.
For example, let's use two data structures: SingleList and DoubleLinkedList, which, both, inherit from List and have the method pop. Each class has its own implementation of the method (because of the 'override').
So, when you want to call it, the lookup of the method is done at runtime (a.k.a. dynamically) when you do a list#pop.
If you were using modules you would have to use SingleList.pop list or DoubleLinkedList.pop list.
EDIT: As #Majestic12 said, most of the time, OCaml users tend to use modules over classes. Using the second when they need inheritance or instances (check his answer).
I wanted to make the description practical as you seem new to OCaml.
Hope it can help you.
There are a few different ways to create Java classes in Clojure, so what are the tradeoffs when picking between gen-class, proxy, and reify in Clojure? (are there other ways to create Java classes that I haven't listed?)
My basic understanding is that I have listed these constructs in decreasing order of power.
Use gen-class when you want a named class or you want to add new methods to objects you create. gen-class relies on AOT compilation.
When you want an anonymous, one-off implementation of a type you use reify or proxy. They do not rely on AOT compilation. Here are their differences:
reify only supports protocols or interfaces, proxy also supports concrete superclasses.
reify uses true class methods, proxy uses external functions.
Because of #2, reify uses direct method lookup, while proxy uses a map for method lookup.
Because of #3, reify does not support dynamic swapping of methods, but proxy does.
reify will perform better than proxy, so you should always use reify when possible. Only use proxy when reify's constraints are too prohibitive.
In addition to gen-class, proxy and reify, we have defrecord and deftype. These latter two options should be your first choices for the creation of named java classes (and in the case of defrecord, your first choice for any kind of struct with named components.)
The datatypes page on clojure.org is a good reference on this topic. Defrecord, deftype and reify are newer than gen-class and proxy, having been introduced in version 1.2 (I think -- possibly 1.1). Defrecord and deftype both create classes that conform to interfaces, but do not allow for inheritance. If you need inheritance, gen-class (and proxy for anonymous classes) is still your only option.
Defrecord and deftype differ in what you are given for free. Defrecord automatically creates a class which conforms to IPersistentMap and ISeq. Deftype, on the other hand, gives you more control over your class, even allowing for mutable fields (not allowed in defrecord). In general, deftype is intended for low-level implementation of data structures, whereas defrecord is intended for most day-to-day use.
Can anybody elaborate the Bridge design pattern and the Decorator pattern for me. I found it similar in some way. I don't know how to distinguish it?
My understanding is that in Bridge, it separate the implementation from the interface, generally you can only apply one implementation. Decorator is kind of wrapper, you can wrap as many as you can.
For example,
Bridge pattern
class Cellphone {
private:
Impl* m_OS; // a cellphone can have different OS
}
Decorator pattern
class Shirt {
private:
Person * m_p; //put a shirt on the person;
}
The Decorator should match the interface of the object you're decorating. i.e. it has the same methods, and permits interception of the arguments on the way in, and of the result on the way out. You can use this to provide additional behaviour to the decorated object whilst maintaining the same interface/contract. Note that the interface of the Decorator can provide additional functionality to create a more useful object.
The Bridge has no such constraint. The client-facing interface can be different from the underlying component providing the implementation, and thus it bridges between the client's interface, and the actual implementation (which may not be client-friendly, subject to change etc.)
Your decorator pattern implementation isn't quite right - It would make more sense if you did:
class PersonWearingShirt : IPerson
{
private:
IPerson * m_p; //put a shirt on the person;
}
The idea is that, when you decorate a class, you expose the exact same interface. This makes your "decorated" instance look and act like the original. This allows you to wrap an instance many times with multiple decorators, but treat it exactly the same as you treat the original instance.
Decorator:
Add behaviour to object at run time. Inheritance is the key to achieve this functionality, which is both advantage and disadvantage of this pattern.
It enhances the behaviour of interface.
Decorator can be viewed as a degenerate Composite with only one component. However, a Decorator adds additional responsibilities - it isn't intended for object aggregation.
Decorator supports recursive composition
The Decorator class declares a composition relationship to the LCD (Lowest Class Denominator) interface, and this data member is initialized in its constructor.
Decorator is designed to let you add responsibilities to objects without sub-classing
Refer to sourcemaking article for more details.
UML diagram of Decorator from wikipedia:
Bridge pattern:
Bridge is structural pattern
Abstraction and implementation are not bound at compile time
Abstraction and implementation - both can vary without impact in client
Use the Bridge pattern when:
you want run-time binding of the implementation,
you have a proliferation of classes resulting from a coupled interface and numerous implementations,
you want to share an implementation among multiple objects,
you need to map orthogonal class hierarchies.
UML diagram of Bridge from wikipedia:
From UML diagram, you can observe the difference:
In Decorator pattern, Decorator is implementing Component, which will be replaced by ConcreteComponent at run time.
In Bridge pattern, RedefinedAbstraction is not implementing Implementor. Instead, it uses composition so that Implementor can vary dynamically at run time without client knowledge.
Decorator can't decouple abstraction from implementation unlike Bridge pattern.
Few more useful posts:
When to Use the Decorator Pattern?
When do you use the Bridge Pattern? How is it different from Adapter pattern?
Brian is correct. I'll add that conceptually, the client will "know" it's using a bridge to an underlying object, but with a decorator, the client will be unable to know there's a decorator layer between it and the target object.
The purpose of the bridge is to create a layer of abstraction to protect the client. The purpose of the decorator is to add functionality to the object without the client knowing. Most decorators will pass along all function calls directly to a pointer to their parent class, except for functions relating directly to what the decorator is designed to change.