Pluggable Adapter as mentioned in the GOF - java
The related Posts on Stackover flow for this topic :
Post_1 and Post_2
Above posts are good but still I could not get answer to my confusion, hence I am putting it as a new post here.
MY Questions based on the GOF's Elements of Reusable Object-Oriented Software book content about Pluggable Adapters (mentioned after questions below), hence I would appreciate if the discussions/answers/comments are more focused on the existing examples from GOF regarding the pluggable Adapters rather than other examples
Q1) What do we mean by built-in interface adaptation ?
Q2) How is Pluggable Interface special as compared to usual Adapters ? Usual Adapters also adapt one interface to another.
Q3) Even in the both the use cases, we see both the methods of the Extracted "Narrow Interface" GetChildren(Node) and CreateGraphicNode(Node)depending on Node. Node is an internal to Toolkit. Is Node same as GraphicNode and is the parameter passed in CreateGraphicNode only for populating the states like (name, parentID, etc) of an already created Node object ?
As per the GOF (I have marked few words/sentences as bold to emphasis the content related to my Questions)
ObjectWorks\Smalltalk [Par90] uses the term
pluggable adapter to describe classes with built-in interface adaptation.
Consider a TreeDisplay widget that can display tree structures graphically.
If this were a special-purpose widget for use in just one application, then
we might require the objects that it displays to have a specific interface;
that is, all must descend from a Tree abstract class. But if we wanted to
make TreeDisplay more reusable (say we wanted to make it part of a toolkit
of useful widgets), then that requirement would be unreasonable.
Applications will define their own classes for tree structures. They
shouldn't be forced to use our Tree abstract class. Different tree
structures will have different interfaces.
Pluggable adapters. Let's look at three ways to implement pluggable adapters
for the TreeDisplay widget described earlier, which can lay out and display
a hierarchical structure automatically.
The first step, which is common to all three of the implementations discussed
here, is to find a "narrow" interface for Adaptee, that is, the smallest
subset of operations that lets us do the adaptation. A narrow interface
consisting of only a couple of operations is easier to adapt than an
interface with dozens of operations. For TreeDisplay, the adaptee is any
hierarchical structure. A minimalist interface might include two
operations, one that defines how to present a node in the hierarchical
structure graphically, and another that retrieves the node's children.
Then there are two use cases
"Narrow Interface" being made as abstract and part of the TreeDisplay
Class
Narrow Interface extracted out as a separate interface and having a composition of it in the TreeDisplay class
(There is a 3rd approach of Parameterized adapter also but skipping it for simplicity, Also this 3rd one is I guess more specific to Small talk)
When we talk about the Adapter design pattern, we typically consider two preexisting APIs that we would like to integrate, but which don't match up because they were implemented at different times with different domains. An Adapter may need to do a lot of mapping from one API to the other, because neither API was designed with this sort of extensibility in mind.
But what if the Target API had been designed with future adaptations in mind? A Target API can simplify the job of future Adapters by minimizing assumptions and providing the narrowest possible interface for Adapters to implement. Note this design requires a priori planning. Unlike typical use cases for the Adapter pattern, you cannot insert a Pluggable Adapter between any two APIs. The Target API must have been designed to support pluggable adaptations.
Q1) This is what the GoF means by built-in interface adaptation: an interface is built into the Target API in order to support future adaptations.
Q2) As mentioned, this is a relatively unusual scenario for an Adapter, since the typical strength of the pattern is its ability to handle APIs that have no common design.
The GoF lists three different approaches to design a Target API for adaptation. The first two are recognizable as a couple of their Behavioral design patterns.
Template Method
Strategy
Closures (what Smalltalk calls code blocks)
Q3) Without getting caught up in details of the GoF's GUI examples, the basic idea behind designing what they call a "narrow interface" is to remove as much domain specificity as possible. In Java, the starting point for a domain-agnostic API would almost certainly be the functional interfaces.
A Target API with dependencies on these interfaces should be much simpler to adapt than an API built around domain-specific methods. The former allows for creation of Pluggable Adapters, while the latter would require a more typical Adapter with heavy mapping between APIs.
Let me share a couple of thoughts.
First, since the question has been posted with the Smalltalk tag, I'll use the Smalltalk syntax which is less verbose (e.g. #children instead of GetChildren(Tree,Node), etc.)
As an introduction to this issue (which may be useful for some readers), let's say that (generic) frameworks need to use a generic language (e.g. #children). However, generic terms may not be natural for the specific object you are considering. For example, in the case of a File System, one usually has #files, #directories, etc., but may not have the selector #children. Even if adding these selectors won't kill anyone, you don't want to populate your classes with new "generic" selectors every time an "abstract" class imposes its naming conventions. In the real life, if you do that, sooner or later you will end-up having collisions with other frameworks for which the very same selector has a different meaning. This implies that every framework has the potential of producing some impedance (a.k.a. friction) with the objects that try to benefit from it. Well, adapters are meant to mitigate these side effects.
There are several ways to do this. One is making your framework pluggable. This means that you will not require the clients to implement specific behavior. Instead you will ask the clients to provide a selector or a block whose evaluation will produce the required behavior.
In the Directory example, if your class Directory happens to implement, say #entities, then instead of creating #children as a synonym, you will tell the appropriate class in the framework something like childrenSelector: #entities. The object receiving this method will then "plug" (remember) that it has to send you #entities when looking for children. If you don't have such a method, you still can provide the required behavior using a block that does what's needed. In our example the block would look like
childrenSelector: [self directories, self files].
(Side note: the pluggable framwork could provide a synonym #childrenBlock: so to make its interface more friendly. Alternatively, it could provide a more general selector such as childrenGetter:, etc.)
The receiver will now keep the block in its childrenGetter ivar and will evaluate it every time it needs the client's children.
Another solution one might want to consider consists in requiring the client to subclass an abstract class. This has the advantage of exposing very clearly the client's behavior. Note however than this solution has some drawbacks because, in Smalltalk, you can only inherit from one parent. So, imposing the superclass may result in an undesirable (or even unfeasible) constraint.
The other option you mention consists in adding one indirection to the previous one: instead of subclassing the main "object" you offer an abstract superclass for subclassing the behavoir your object needs to adapt. This is similar to the first approach in that you don't need to change the client, except that this time you put the adapted protocol in a class by itself. This way, instead of plugging several parameters into the framework, you put them all in an object and pass (or "plug") that object to the framework. Note that these adapting objects act as wrappers in that they know the real thing, and know how to deal with it for translating the few messages the framework needs to send. In general, the use of wrappers provides a lot of flexibility at the cost of populating your system with more classes (which entails the risk of duplicated hierarchies). Moreover, wrapping many objects might impact the performance of your system. Note by the way that GraphicNode also looks like a wrapper of the intrinsic/actual Node.
I'm not sure I've answered your question, but since you asked me to somehow expand my comment, I've happily tried so.
Q1) Interface adaptation just means adapting one interface to implement another, i.e., what adapters are for. I'm not sure what they mean by "built-in", but it sounds like a specific feature of Smalltalk, with which I'm not familiar.
Q2) A "Pluggable Adapter" is an adapter class that implements the target interface by accepting implementations for its individual methods as constructor arguments. The purpose is to allow adapters to be expressed succinctly. In all cases, this requires the target interface to be small, and it usually requires some kind of language facility for succinctly providing a computation - a lambda or delegate or similar. In Java, the facility for inline classes and functional interfaces means that a specific adapter class that accepts lambda arguments is unnecessary.
Pluggable adapters are a convenience. They are not important beyond that. However...
Q3) The quoted text isn't about pluggable adapters, and neither of the two use cases has a pluggable adapter in it. That part is about the Interface Segregation Principle, and it is important.
In the first example, TreeDisplay is subclassed. The actual adapter interface is the subset of methods in TreeDisplay that require implementation. This is less than ideal, because there is no concise definition of the interface that the adapter must implement, and the DirectoryTreeDisplay cannot simultaneously implement another similar target interface. Also such implementations tend interact with the subclass in complex ways.
In the second example, TreeDisplay comes with a TreeAccessorDelegate interface that captures the requirements for things it can display. This is a small interface that that can be easily implemented in a variety of ways, including by a pluggable adapter. (although the example DirectoryBrowser is not pluggable). Also, interface adaptation does not have to be the sole purpose of the adapter class. You see that DirectoryBrowser class implements methods that have nothing to do with tree display.
The Node type in these examples would be an empty/small interface, i.e., another adapter target, or even a generic type argument so that no adaptation is required. I think this design could be improved, actually, by making Node the only adaptation target.
Related
Is it safe to rely on javafx.util.Callback?
Is it safe to use the javafx.util.Callback on a server machine? As I understand, and I may be wrong, not all JavaFX components are available on a server installation where graphics arent available. Should I create my own callback interface, or just use one from javafx?
At first, I didn’t like using it either, because this interface was losing quality in my code. I no longer had self-explaining interface names. But in the end, I realized that the advantages overweigh the lack of quality. The advantages being: We end up writing less code. No specialized interface, no default implementations. The developer using the API does not have to remember different factories, instead, he can focus on the object that he wants to create and the parameters that are available to him. The Callback interface is a functional interface. We can use Lambda expressions, which makes the code more elegant and we once again have to write less code. Therefore I would suggest using javafx.util.Callback instead of custom one
Class structure for client library
I need to make a couple of services that will talk to both Amazon S3 and Riak CS. They will handle the same operations, e.g. retrieve images. Due to them returning different objects, in S3's case an S3Object. Is the proper way to design this to have a different class for each without a common interface? I've been thinking on how to apply a common interface to both, but the return type of the methods is what's causing me some issues, due to them being different. I might just be going wrong about this and probably should just separate them but I am hoping to get some clarification here. Thanks all!
Typically, you do this by wrapping the responses from the various external services with your own classes that have a common interface. You also wrap the services themselves, so when you call your service wrappers they all return your wrapped data classes. You've then isolated all references to the external service into one package. This also makes it easy to add or remove services.
A precise answer to your question would require knowing the language you are using and/or the platform. Eric in his answer above is correct that wrapping the data inside one of you own class is one way to handle this. However, depending on the language, the details of the final implementation will vary and the amount of work required when adding possible return value type will also vary. In Java for example one way to handle this would be to return an heterogeneous container. Take a look at this thread: Type safe heterogeneous container pattern to store lists of items
How can I apply oo design patterns in this situation?
Situation: Suppose we're designing the UI of Windows 9 using Java API. We need to build up 3 classes main, BuildInWindow and ApplicationWindow. main - the window for rendering the system UI (i.e. the start botton & wallpaper page) BuildInWindow- windows for rendering buildt-in apps (e.g. IE) ApplicationWindow- windows for rendering apps from third party (e.g. eclipse) all of them have to implement 3 Java API interfaces, WindowFocusListener, WindowListener and WindowStateListener and have the methods onExit() and onCrushing(). onExit() performs when the system/built-in app/ third-party app is shut down normally onCrushing() captures any system/application crush and send system state back to server This is the original design: http://i.stack.imgur.com/JAJiY.png I have some ideas of how to design it in a OO manner, but I am not sure if that's the right way. Here's my thoughts: Create an abstract class with method onExit() and onCrushing(). Since the code of onExit()would vary from 3 classes, it should be an abstract method & onCrushing()would be same fo all classes, so it would be an concrete method tHE MAIN WINdow should use singleton design to ensure user only create one instance of main. Use the facade design to save the trouble of implementing 3 interfaces to three classes My question is I don't really understand facade design, so I am not sure if it can be applied in this case. Also I am not really sure if onExit() would be different for 3 classes and onCrushing() would perform the same function. I tried my best to explain the question clearly...if you don't understand free free to comment. Thank you very much!
I've left some questions in a comment linked to your question but here's some guidance for you: You shouldn't create an abstract class on the basis of both BuildInwindow and ApplicationWindow both having to have methods #onExit and #onCrushing if they are not to share any implementation. Abstract classes are most useful where there is a common implementation. An interface containing these methods would be sufficient. That said, your two windows may share other functionality and, if so, it could be shared through a common superclass (abstract if it relies on subclass implementation detail). You may find the Template Method pattern useful for managing the overall window mechanism with specific tailoring for different window types. You may also find the Factory Method means of instance creation (for your window classes) will help separate the object creation and set-up from the creation mechanism. A single shared instance would seem sensible and a singleton would serve this purpose (so long as you're able to handle termination, etc). Alternatively, your application may just launch a single Main instance - you may even just hide the constructor through package access to ensure no others are created. The facade pattern just serves to simplify a complex interface. It mainly does this by rolling calls to collaborating instances together under a single (coarser) interface. This wouldn't normally be a done to hide which interfaces a class supports. Indeed, publishing which interfaces a class extends is important to API users. You could roll the three interfaces into a single interface for "convenience" but I think this is unnecessary. If you do settle on a common superclass then that would "extend" the three interfaces (if all subclasses were expected to support them). It may also implement some default implementation of these interfaces (again, watch access modifiers to ensure those you intend to be can be overridden while others may be final). Edit: Guidance You just have to identify the classes and relationships: I suggest you just grab some paper and draw. You already have your nouns and verbs (you can otherwise go noun and verb spotting to identify classes and methods on them). So, why not draw a simple diagram containing all the info (A, B, C, Main, etc) and draw the relationships between them. This is your start point. You may have some confusion when working out how Main links to the window classes (given there are two kinds). Just write a note on it and move on to clarify the rest of the picture. Next, refine your diagram to start moving common features into a single place (abstraction). You know this exists with regards to your interfaces and the methods you suggest but you may need to decide which (if any) have any common functionality. Then decide if interfaces satisfies your needs (methods are common but implementations are different) or if the implementation itself is the same and so a parent superclass may be useful (this addresses abstraction [who is responsible for what], encapsulation [individual implementations at the appropriate level] and polymorphism [which classes support common methods]). Note that, even if you settle on an superclass, you'd be wise to back it with an interface (it makes introduction of sibling or replacement classes easier in time - think maintenance). Next, work on the issues you found. Has your draft design clarified any of them? For instance, your Main needs to know about its windows but - what type are they? So, has any of your refinement made this clearer? Do any patterns present themselves? for this you need to already have a feel for design patterns I'm afraid so buy and absorb the GoF Design Patterns book. It'll put you in good stead for spotting patterns as you go. I'd also recommend reading this specific book before taking on any others as it's technology agnostic (and some other books arebloated with tech-specific workarounds). Perhaps study the two patterns I pointed out and see if they fit your requirement. On the whole though, your ideas seem to be going in the right direction.
Java Interfaces Methodology: Should every class implement an interface?
I've been programming in Java for a few courses in the University and I have the following question: Is it methodologically accepted that every class should implement an interface? Is it considered bad practice not to do so? Can you describe a situation where it's not a good idea to use interfaces? Edit: Personally, I like the notion of using Interfaces for everything as a methodology and habit, even if it's not clearly beneficial. Eclipse automatically created a class file with all the methods, so it doesn't waste any time anyway.
You don't need to create an interface if you are not going to use it. Typically you need an interface when: Your program will provide several implementations for your component. For example, a default implementation which is part of your code, and a mock implementation which is used in a JUnit test. Some tools automate creating a mock implementation, like for instance EasyMock. You want to use dependency injection for this class, with a framework such as Spring or the JBoss Micro-Container. In this case it is a good idea to specify the dependencies from one class with other classes using an interface.
Following the YAGNI principle a class should implement an interface if you really need it. Otherwise what do you gain from it? Edit: Interfaces provide a sort of abstraction. They are particularly useful if you want to interchange between different implementations(many classes implementing the same interface). If it is just a single class, then there is no gain.
No, it's not necessary for every class to implement an interface. Use interfaces only if they make your code cleaner and easier to write. If your program has no current need for to have more than 1 implementation for a given class, then you don't need an interface. For example, in a simple chess program I wrote, I only need 1 type of Board object. A chess board is a chess board is a chess board. Making a Board interface and implementing that would have just required more code to write and maintain. It's so easy to switch to an interface if you eventually need it.
Every class does implement an interface (i.e. contract) insofar as it provides a non-private API. Whether you should choose to represent the interface separately as a Java interface depends on whether the implementation is "a concept that varies". If you are absolutely certain that there is only one reasonable implementation then there is no need for an interface. Otherwise an interface will allow you to change the implementation without changing client code. Some people will shout "YAGNI", assuming that you have complete control over changing the code should you discover a new requirement later on. Other people will be justly afraid that they will need to change the unchangeable - a published API. If you don't implement an interface (and use some kind of factory for object creation) then certain kinds of changes will force you to break the Open-Closed Principle. In some situations this is commercially acceptable, in others it isn't. Can you describe a situation where it's not a good idea to use interfaces? In some languages (e.g. C++, C#, but not Java) you can get a performance benefit if your class contains no virtual methods. In small programs, or applications without published APIs, then you might see a small cost to maintaining separate interfaces. If you see a significant increase in complexity due to separating interface and implementation then you are probably not using interfaces as contracts. Interfaces reduce complexity. From the consumer's perspective, components become commodities that fulfil the terms of a contract instead of entities that have sophisticated implementation details in their own right.
Creating an interface for every class is unnecessary. Some commonly cited reasons include mocking (unneeded with modern mocking frameworks like Mockito) and for dependency injection (e.g. Spring, also unneeded in modern implementations). Create an interface if you need one, especially to formally document public interfaces. There are a couple of nifty edge cases (e.g. marker interfaces). For what it's worth, on a recent project we used interfaces for everything (both DI and mocking were cited as reasons) and it turned out to be a complete waste and added a lot of complexity - it was just as easy to add an interface when actually needed to mock something out in the rare cases it was needed. In the end, I'm sure someone will wind up going in and deleting all of the extraneous interfaces some weekend. I do notice that C programmers first moving to Java tend to like lots of interfaces ("it's like headers"). The current version of Eclipse supports this, by allowing control-click navigation to generate a pop-up asking for interface or implementation.
To answer the OP's question in a very blunt way: no, not all classes need to implement an interface. Like for all design questions, this boils down to one's best judgment. Here are a few rule of thumbs I normally follow: Purely functional objects probably don't need to (e.g. Pattern, CharMatcher – even though the latter does implement Predicate, it is secondary to its core function) Pure data holders probably don't need to (e.g. LogRecord, Locale) If you can envision a different implementation of a given functionality (say, in-memory Cache vs. disk-based Cache), try to isolate the functionality into an interface. But don't go too far trying to predict the future either. For testing purposes, it's very convenient when classes that do I/O or start threads are easily mockable, so that users don't pay a penalty when running their tests. There's nothing worse than a interface that leaks its underlying implementation. Pay attention where you draw the line and make sure your interface's Javadoc is neutral in that way. If it's not, you probably don't need an interface. Generally speaking, it is preferable for classes meant for public consumption outside your package/project to implement interfaces so that your users are less coupled to your implementation du jour. Note that you can probably find counter-examples for each of the bullets in that list. Interfaces are very powerful, so they need to be used and created with care, especially if you're providing external APIs (watch this video to convince yourself). If you're too quick in putting an interface in front of everything, you'll probably end up leaking your single implementation, and you are only making things more complicated for the people following you. If you don't use them enough, you might end up with a codebase that is equally hard to maintain because everything is statically bound and very hard to change. The non-exhaustive list above is where I try to draw the line.
I've found that it is beneficial to define the public methods of a class in a corresponding interface and when defining references to other classes strictly use an interface reference. This allows for easy inversion of control, and it also facilitates unit testing with mocking and stubbing. It also gives you the liberty of replacing the implementation with some other class that implements that interface, so if you are into TDD it may make things easier (or more contrived if you are a critic of TDD)
Interfaces are the way to get an polymorphism. So if You have only one implementation, one class of particularly type, You don't need an interface.
A good way of learning what are considered good methodologies, especially when it comes to code structure design, is to look at freely available code. With Java, the obvious example is to take a look at the JDK system libraries. You will find many examples of classes that do not implement any interfaces, or that are meant to be used directly, such as java.util.StringTokenizer.
If you use Service Provider Interface pattern in your application interfaces are harder to extend than abstract classes. If you add method to interface, all service providers must be rewritten. But if you add non-abstract method to the abstract class, none of the service providers must be rewritten. Interfaces also make programming harder if only small part of the interface methods usually have meaningfull implementation.
When I design a new system from scratch I use a component oriented approach, each component (10 or more classes) provide an interface, this allows me (sometimes) to reuse them. When designing a Tool (Or a simple system) I think this must not necessarily be an extensible framework I introduce interfaces when I need a second implementation as an option. I saw some products which exposed nearly every functionality by an interface, it took simply too much time to understand unnecessary complexity.
An interface is like a contract between a service provider (server) and the user of such a service (client). If we are developing a Webservice and we are exposing the rest routes via controller classes, controller classes can implement interfaces and those interfaces act as the agreement between web service and the other applications which use this web service. Java interfaces like Serializable, Clonnable and Remote used to indicate something to compiler or JVM.When JVM sees a class that implement these interfaces, it performs some operation on the to support Serialization, cloning or Remote Method Invocation. If your class needs these features, then you will have to implement these interfaces.
Using Interface is about to make your application framework resilient to change. Since as I mentioned here (Multiple Inheritance Debates II: according to Stroustrup) multiple inheritance was cancelled in java and c# which I regret, one should always use Interface because you never know what the future will be.
In C# could we imagine writing our own events without writing delegates?
I learned the object-oriented in Java. Now in develop in C#. This means that I never really understood the functioning of delagates but I know how to use them. Lately I discovered this page http://java.sun.com/docs/white/delegates.html. If Java is able to create event without delagates is it possible to do the same in C#? Could we imagine writing our own events without writing a single delegate? (Question already asked in french here)
Yes, you could use a single-method interface instead of a delegate. You'd also need an implementation of the multi-cast nature of delegates, both in terms of add/remove and invoke. It would be tough to have a single class implementing multicast and also implementing Invoke in a typesafe way, however, due to the interfaces having different numbers and types of parameters. You could have a bunch of them of course: Multicast<T>, Multicast<T1, T2> etc. (The same class would handle asynchronous execution too, probably.) The other pain in the neck is that you could only implement the interface once per class, even if you wanted several different handlers - so you'd have a lot of nested classes. There's little that's particularly magical about delegates - they're just a very useful abstraction, and with the syntactic sugar of lambda expressions, anonymous methods and expression trees, they're even nicer.
No, you can't do events in C# without delegates. In C#, events are defined as delegates: An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type. However, you could mimic events using the Observer pattern. Microsoft's answer to Sun's White Paper is worth reading.
That's a pretty old document and look where it's gotten them. You can do the exact same thing in .NET if you want. All the "Java Way" is doing is taking advantage of inheritance. That's fine but for many the "function pointer" semantic is much more straightforward and less verbose.
Yes you can. You can use predefined delegates. (I'm not sure what's your level of experience and what are you really asking about)
Why on earth would you want to do that? I mean, if you have a rules engine, or commands that are more than just eventhandlers, then sure: You will want to implement an interface, because you will have state and behavior besides the actual piece of code you want to fire. But if providing some code to fire when the event is raised, then there's no reason to not use delegates. Delegates are thin abstractions over method/function pointers and as such they add very little overhead. And IMO, one should not add overhead just for the sake of it.