In C# could we imagine writing our own events without writing delegates? - java

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.

Related

Pluggable Adapter as mentioned in the GOF

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.

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

Why do we need interfaces to achieve event listeners in java?

I have this doubt in Java: when people are writing an event listener they implement an interface and they define a particular function in the interface to achieve a particular task. My doubt is instead of implementing an interface can we just define the function with the an appropriate name.
Also, how interfaces help in achieving event listeners?
Because many different classes would want to listen to the same event and Java does not allow multiple inheritance.
The Listener interface gives you a lot a implementation freedom.
This way you don't have to implement a specific function in a specific class. Though implementing an interface seemes to be the same, it isn't. The functionality of a listener is just still ja single function, but the function is usualy in a lightweight object. Yet you are able to implement a lot of program mechanics inside a listener, if you need to.
Also, you can change the listeners at runtime. You can't change an overriden function.
There are a lot of good reasons to use composition (over inheritance) here.
If you really want to understand this, I encourage you to look inside "Heads first: Design Patterns". The "look inside" feature of amazon contains the complete chapter 1, which explains this pattern greatly.

Java - is better to directly access other object components or through method?

this is more theoretical question. I have written simple chat with my friend. We have few classes, but most important are Client (handles network stuff) and GUI (self-explanatory :)).
Now, I write messages into JTextArea. And I want to ask, from the OOP theory, is it better to send to Client reference to JTextArea and directly append text to it, OR is better to create function in GUI which makes the same and call it from Client? When message comes from server of course.
I know the most efficient way is the first, but I believe its not the proper OOP way. I have found that OOP is less efficient than procedural, not becouse its more complex on abstraction, but becouse many OOP standarts just seems ineficient. Thanks.
You should encapsulate the functionality of the GUI. The client shouldn't have any knowledge of its inner workings whatsoever. Instead, you should provide a semantically meaningful public method that describes the task it will perform - in this case updating the display.
Ideally you should have an interface that represents your GUI actions also - this will decouple the client from the GUI and will mean you can have multiple UIs implement the interface and the client doesn't care which UI it is using.
Desktop applications usually consist of a business layer and a presentation layer. The GUI belongs to the presentation layer. I presume Client belongs to the business layer.
The business layer should not know anything about the presentation layer.
In this case, the Client can introduce an interface. Something like:
interface MessageListener {
void handleNewMessage();
}
And then, we can have an observer pattern. The client invoke registered MessageListener. And the GUI implements MessageListener and registry to the Client.
Regarding this:
I know the most efficient way is the
first, but I believe its not the
proper OOP way. I have found that OOP
is less efficient than procedural, not
becouse its more complex on
abstraction, but becouse many OOP
standarts just seems ineficient.
Thanks.
For about 99% of all code you'll ever write, efficiency is totally and utterly irrelevant because it won't run often enough to notice any inefficiencies. And that's certainly the case here: GUI event handling code is about the most performance-uncritical code there is because user's can't even notice delays of less than 1/100th of a second, and on modern hardware that's an eternity.
Furthermore, for 100% of all code you'll ever write, being complete and correct matters more than efficiency. Nobody cares how efficient your code does the wrong thing. And producing correct and complete code is much easier when it's maintainable, clean, decoupled. Which is exactly what OO and its conventions try to (and generally do) make easier.

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.

Categories