What is the general term for Mouse Listener? - mouseevent

In Java, they use the term "Listener" to refer to the objects that are used to handle mouse events.
What is the general term for these kind of objects in event-driven GUI programming ?

After a bit of search, I think the most general term for this kind of objects is : Mouse Event Handler.

Related

Kotlin basics : RatingBar, listeners

I started learning Kotlin few weeks ago and I need help understanding the basics.
What is a listener? For example, what is RatingBar's listener? How do I find a listener of other widgets?
What are the parameters? Again, what is RatingBar's parameters? How do I find the parameters of other widgets?
What is View.____?
If you're writing a component that handles events of some kind, you'll probably want a way to inform other components about those events. There are lots of ways to do this (in a software design sense), and one of those is the idea of a listener.
The basic idea is that components can register themselves as listeners, and when a relevant thing happens, they get a callback. The component generating the events doesn't need to know what those listeners are, it just needs to hold a reference to one (or more) and call some callback function when the event happens. The key thing here is that the component doesn't have a listener, you have to provide them. You're hooking components up.
So a typical way to do this is for a component to implement a callback interface, which basically says "I have a function called this with these parameters" and the event component can just call that function with the details when an event happens. You could also create an object that implements that interface, or in Kotlin's case you can just pass a function in that matches the signature of the callback function - basically providing a block of code that says "when the event happens, do this stuff in response". That's typically how you define behaviour, like setting an on-click listener - you write a block of code to execute when the user clicks a thing, and when the event happens, that code gets run.
I hope that makes sense generally - if any of it's confusing (since you're new) I'd recommend reading the basic trails in the Java Tutorials (which Kotlin is based on) to get a handle on interfaces and the like.
As for the other questions... if you're asking what the parameters are when you construct a RatingBar or whatever, the best place to look is the documentation (although you generally won't be constructing Views in code anyway, just adding them to a layout XML file) - Android Studio should pop up some hints too (you can hit ctrl+q for documentation on the thing your cursor is currently over, or ctrl+p for parameter hints).
If you're asking what a View is, it's the base class for Android's UI components, it's really anything that's able to draw itself and be included in a layout. It has a lot of methods because it has a lot of functionality built in to handle all these UI responsibilities.
If you're asking what View.something is, that's a static method or field defined on the View class - if you don't know what that means, read the Java tutorial link I included! You'll typically be referencing things like View.VISIBLE which is a set value you provide to a View's setVisibility method - it knows what those values mean and what to do with them

OOP - Can and should events be part of the abstractions?

Imagine that I have a system of objects that are event emitters and also can listen to events in other objects. In this system these objects communicate between them mainly using events.
I want to follow good object-oriented practices an I'm interested in creating abstractions for my objects. The actual language that I would use doesn't matter that much: those abstractions could be interfaces or abstract classes for example.
These kind of abstractions define methods and properties in the object, but don't define event names. New implementations could decide to throw totally new events... It's true that you are using always the same method to throw them, but if you are creating new event names my impression is that you are in a way violating the open/closed principle: I would say that that's equivalent to adding new methods.
Would there be a way to state the possible events that an object like that can emit, in the abstraction that that object follows?
I'm interested in how this would work in languages like Java, C++, Javascript and Typescript. I'm not entirely sure as I don't know C# but I think that in that language events can be a part of the interfaces. But I am interested in how would you make events part of the abstractions in those other languages that don't support that in a straightforward way.
The ability to enforce those contracts in code efficiently will differ depending on the language being used, therefore the optimal solution is not really language agnostic: there's an idiomatic way of doing things in every language.
One solution that can be implemented in probably all typed languages is to make every event an emitter and rely on composition.
That basically boils down to someObject.onSomeEvent.listen(handler) instead of someObject.listenTo('someEvent', handler).
That's the approach they used in Google Dart when refactoring the DOM Events API. Since events are now class members they can easily become part of the code contract.
There are obviously other ways, such as creating a concrete event class per event rather than using strings. The advantage of this solution is that the contract wouldn't have to change when new events are added.

What is the relation of 'Event Driven' and 'Object Oriented' programming?

These days, I hear almost everywhere about 'event driven' programming.
Wikipedia says:
In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs/threads. Event-driven programming is the dominant paradigm used in graphical user interfaces and other applications (e.g. Javascript web applications) that are centered around performing certain actions in response to user input.
Isn't this exactly our old friend OOP? And if this is not OOP what is the difference?
Object Oriented Programming (OOP) and Event-Driven Programming (EDP) are orthogonal, which means that they can be used together.
In OOP with EDP all OOP principles (encapsulation, inheritance and polymorphism) stay intact.
In OOP with EDP objects acquire some mechanism of publishing event notifications and subscribing to event notifications from other objects.
The difference between OOP with / without EDP is control flow between objects.
In OOP without EDP control moves from one object to another object on a method call. Object mainly invokes methods of other objects.
In OOP with EDP control moves from one object to another object on event notification. Object subscribes on notifications from other objects, then waits for notifications from the objects it is subscribed on, does some work based on notification and publishes it's own notifications.
Conclusion: OOP+EDP is "exactly our old friend OOP" with control flow inverted thanks to Event-Driven Design.
Object Oriented Programming is defined by the pairing together of data and actions into a model of a real world object. Event driven programming is a style of programming in which we have a server, whether it be on a communications port or a user interface, waiting for an input command. It will then process that command and display/produce desired results.
Most event driven languages are object oriented. The objects await the events. A program in an object oriented language is not necessarily event driven, and event driven programming does not necessarily require an object oriented language. They are unrelated.
The algorithm of a sequential (non-event-driven) program is like a recipe: begin at the beginning, work through until you get to the end, then stop.
An event-driven program is more like the controls of a car: anything can happen any time in any order.
The Object-Oriented principle seems more applicable to an event-driven model because each of the "controls" is basically unrelated to the others (separation of concerns), and order of events is mostly not important, as is coincidence in time: you can turn on the wipers, turn off the defroster, steer and accelerate all at the same time, and the actions do not affect each other. That is also possible in some cases with a recipe, but it is up to the chef (compiler / optimizer / cpu) to deduce it.
A sequential program can be OO: nobody minds if the blender and the oven are disconnected and do their own thing. I hope this was a useful analogy.
My stab at it. Here are three metaphors:
Event programming seems to be similar to how hardware buses work: a bus is used for peripherals to talk to one another. Similarly, a cell tower is the message bus by which cellphones talk to one another. Also consider the good old Star Network topology model (https://en.wikipedia.org/wiki/Star_network). Heck, look at how a home router connects computers and IoT devices to a home network.
Instead of peripherals or cellphones or devices, we code objects. Instead of sending packets along a transmission protocol, we send events or messages to a message broker (a message queue, for instance, or Kafka). The event is available to be acted upon by whomever is interested in it, or in the case of a workflow, the event is expected to be worked by someone in particular and the sender will expect to find a resulting event with a response appropriate to the outcome.
ASIDE: Lessons Learned
Potentially, we therefore also have solutions about problems that hardware manufacturers and telecom engineers have already encountered and solved regarding event-driven messaging.

Event Handling Without Subclassing

I've recently watched some Lynda tutorials on how to program in Objective C and Cocoa. Coming from a PHP and C# background, one thing caught my attention - event handling. As I was watching the tutorials, the mentor was going through subclassing in order to attach to events.
He eventually discussed creating delegates and attaching to the events that way - better, but still not near as easy as C#. However, I later found out that not everything has a delegate, which makes things even more difficult.
I've been searching the Internet for a way to handle events without making a subclass so that I don't end up with this application that has an enormous amount of files, but to no avail.
I'm specifically trying to attach to a mouseLeave or mouseOut event for a NSSlider object so that I can hide a label once it's finished sliding.
Is there some way I can attach to the event without doing any subclassing, or is creating subclass after subclass something that I should just get used to?
There are a few ways for event-handling.
Like you said, subclassing, is probably the easiest.
Using delegates is another way. In my opinion often the best.
Another alternative is using blocks.
In my opinion Objective-C is very structured, and I prefer it a lot over C#.

Why should the observer pattern be deprecated?

I've noticed that my dependency injected, observer-pattern-heavy code (using Guava's EventBus) is often significantly more difficult to debug than code I've written in the past without these features. Particularly when trying to determine when and why observer code is being called.
Martin Oderski and friends wrote a lengthy paper with an especially alluring title, "Deprecating the Observer Pattern" and I have not yet made the time to read it.
I'd like to know what is so wrong with the observer pattern and so much better about the (proposed or other) alternatives to lead such bright people to write this paper.
As a start, I did find one (entertaining) critique of the paper here.
Quoting directly from the paper:
To illustrate the precise problems of the observer pattern,
we start with a simple and ubiquitous example: mouse dragging.
The following example traces the movements of the
mouse during a drag operation in a Path object and displays
it on the screen. To keep things simple, we use Scala closures
as observers.
var path: Path = null
val moveObserver = { (event: MouseEvent) =>
path.lineTo(event.position)
draw(path)
}
control.addMouseDownObserver { event =>
path = new Path(event.position)
control.addMouseMoveObserver(moveObserver)
}
control.addMouseUpObserver { event =>
control.removeMouseMoveObserver(moveObserver)
path.close()
draw(path)
}
The above example, and as we will argue the observer
pattern as defined in [25] in general, violates an impressive
line-up of important software engineering principles:
Side-effects Observers promote side-effects. Since observers
are stateless, we often need several of them to simulate
a state machine as in the drag example. We have to save
the state where it is accessible to all involved observers
such as in the variable path above.
Encapsulation As the state variable path escapes the scope
of the observers, the observer pattern breaks encapsulation.
Composability Multiple observers form a loose collection
of objects that deal with a single concern (or multiple,
see next point). Since multiple observers are installed at
different points at different times, we can’t, for instance,
easily dispose them altogether.
Separation of concerns The above observers not only trace
the mouse path but also call a drawing command, or
more generally, include two different concerns in the
same code location. It is often preferable to separate the
concerns of constructing the path and displaying it, e.g.,
as in the model-view-controller (MVC) [30] pattern.
Scalablity We could achieve a separation of concerns in our
example by creating a class for paths that itself publishes
events when the path changes. Unfortunately, there is no
guarantee for data consistency in the observer pattern.
Let us suppose we would create another event publishing
object that depends on changes in our original path, e.g.,
a rectangle that represents the bounds of our path. Also
consider an observer listening to changes in both the
path and its bounds in order to draw a framed path. This
observer would manually need to determine whether the
bounds are already updated and, if not, defer the drawing
operation. Otherwise the user could observe a frame on
the screen that has the wrong size (a glitch).
Uniformity Different methods to install different observers
decrease code uniformity.
Abstraction There is a low level of abstraction in the example.
It relies on a heavyweight interface of a control
class that provides more than just specific methods to install
mouse event observers. Therefore, we cannot abstract
over the precise event sources. For instance, we
could let the user abort a drag operation by hitting the escape
key or use a different pointer device such as a touch
screen or graphics tablet.
Resource management An observer’s life-time needs to be
managed by clients. Because of performance reasons,
we want to observe mouse move events only during a
drag operation. Therefore, we need to explicitly install
and uninstall the mouse move observer and we need to
remember the point of installation (control above).
Semantic distance Ultimately, the example is hard to understand
because the control flow is inverted which results
in too much boilerplate code that increases the semantic
distance between the programmers intention and
the actual code.
[25] E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design
patterns: elements of reusable object-oriented software.
Addison-Wesley Longman Publishing Co., Inc., Boston, MA,
USA, 1995. ISBN 0-201-63361-2.
I believe the Observer pattern has the standard drawbacks that come with decoupling things. The Subject gets decoupled from Observer but you cannot just look at its source code and find out who observes it. Hardcoded dependencies are usually easier to read and think about but they are harder to modify and reuse. It's a tradeoff.
As to the paper, it does not address the Observer pattern itself but a particular usage of it. In particular: multiple stateless Observer objects per single object being observed. This has the obvious drawback of the separate observers needing to synchronize with each other ("Since observers are stateless, we often need several of them to simulate
a state machine as in the drag example. We have to save
the state where it is accessible to all involved observers
such as in the variable path above.")
The above drawback is specific to this kind of usage, not to the Observer pattern itself. You could as well create a single (stateful!) observer object that implements all the OnThis, OnThat,OnWhatever methods and get rid of the problem of simulating a state machine across many stateless objects.
I will be brief because I'm new to the topic (and didn't read that specific article yet).
Observer Pattern is intuitively wrong: The Object to be observed knows who is observing (Subject<>--Observer).
That is against real-life (in event-based scenarios). If I scream, I have no idea who is listening; if a lightening, hits the floor... lightning doesn't know that there is a floor till it hits!. Only Observers know what they can observe.
When this kind of of things happen then software use to be a mess -because constructed against our way of thinking-.
It is as if and object knew what other objects can call his methods.
IMO a layer such as "Environment" is the one in charge of taking the events and notifying the affected. (OR mixes the event and the generator of that event)
Event-Source (Subject) generates events to the Environment. Environment delivers the event to the Observer. Observer could register to the kind of events that affects him or it is actually defined in the Environment. Both possibilities make sense (but I wanted to be brief).
In my understanding the Observer Pattern puts together environment & subject.
PS. hate to put in paragraphs abstract ideas! :P