What is the purpose of events in ABAP? - oop

Learning ABAP from a book, I got to the object/class events. I know events from other languages (as C#/WinForms) as connection between user action in GUI (e.g. button click) and some piece of code executed after the interaction. There is also possibility to trigger such event from a code to simulate user action, which can be sometimes useful.
The book ends the example with RAISE EVENT statement triggering the event manually from the code. It is same in other sources online (e.g. 1, 2, 3, 4, 5). I don’t see any reason to raise event from code if I can call the object method directly. It seems like needless layer of code to me. What is the purpose or benefit of using events in ABAP? What do I miss?

Thank you for the comments; they got me on the right track. Problem with many sources is they show very simple example where events bring no benefit. It is same as using OOP for a few lines of code, or recursion instead of simple cycle. Such easy example is good to learn the syntax, but it is insufficient to understand the purpose or benefits.
Using events and handlers in one class doesn’t make much sense for me. Most of examples come with two classes (still putting together things that can be alone). For me, an example with three separate pieces of code brought the biggest benefit. According to my understanding, the key points are:
Class A has an event defined by command EVENTS. Class A needs no reference to other classes. In my words: Some situation interesting for the others can happen inside. The class has no knowledge of the outside world (no dependency), but it can signal to the world that the situation happened.
Only the object A can raise (fire, trigger) the event from its inside code by command RAISE EVENT. In my words: It is broadcasted outside (to anyone who could concern and subscribes) that the situation happened.
Class B defines method/handler for the class A by command METHODS - FOR EVENT – OF that CAN be used to handle the event. This class needs to know class A and its event. In my words: Class B offers code to handle situation that can occur in class A.
Some third piece of code having knowledge of both classes (probably creating them) says: when the event in class A raises use this handler by command SET HANDLER - FOR. Most importantly, it can be also another handler from different class than B. In my words: When using class A, I can easily set what will happen after the situation in A by selecting from a range of suitable handlers that A doesn’t know.
Because I miss a good example, here is a demonstration of the points:
CLASS lcl_class_a DEFINITION.
PUBLIC SECTION.
DATA a1 TYPE I.
EVENTS: my_event.
METHODS: method_raising_event.
ENDCLASS.
CLASS lcl_class_a IMPLEMENTATION.
METHOD method_raising_event.
"some working code would be here
RAISE EVENT my_event.
ENDMETHOD.
ENDCLASS.
CLASS lcl_class_b DEFINITION.
PUBLIC SECTION.
"This methods could be run after the event.
METHODS: handle_event1 FOR EVENT my_event OF lcl_class_a,
handle_event2 FOR EVENT my_event OF lcl_class_a.
ENDCLASS.
CLASS lcl_class_b IMPLEMENTATION.
METHOD handle_event1.
WRITE: / 'Event in class raised'.
ENDMETHOD.
METHOD handle_event2.
" Some code, e.g. logging to a file.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA(object_a) = new lcl_class_a( ).
DATA(object_b) = new lcl_class_b( ).
"Binding event and handler.
SET HANDLER object_b->handle_event1 FOR object_a.
CALL METHOD object_a->method_raising_event.
Additions:
In real life scenarios, it is useful to have reference to object of class A (raiser) in the object of class B (handler). You may need to get an additional information about the event from class A. But it is not necessary.
More handlers can be attached to one event.
The purpose or benefits are much clearer when aware of some design patterns. Some were mentioned in benefits. I would go with this hierarchy from general to particular:
SOLID
Loose coupling / Decoupling / Separation of concerns
Dependency inversion principle
Observer – Observable / Subscriber – Publisher
Happy to read comments on my answer.

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

OO design for logging

I am developing an application in which one part is a logging mechanism. I have defined a business logic when in every setter of each class an event is raised with the reference to the object that was changed and old value of the changed attribute. I have created a class called Logger that listens to that events and creates a log.
But, I don't want to have a event handler for each of the events. I would like the Logger to catch events, which parameters is an interface, let's call it 'Logging'. So from Logger's point of view, the logging would be unified.
The question is, how to use this Logging interface. I don't want my business classes to implement it. Could you give me some ideas what would be the best approach to do this in a nice OO design?
Thank you.

How to share local classes?

I'm currently working on a rather complex ABAP application that is going to be split into several modules each performing a specific part of the job:
one for gathering some data from multiple sources;
one for displaying that data in UI (SALV grid, if that matters);
one for doing some business things based on that data.
According to my plan each module will be a global class. However, there is some logic that may need to be shared between these classes: helper subroutines, DB access logic and so on. All of this is a set of local classes at the moment.
I know could these classes global as well, but this would mean exposing them (as well as a number of internal data structures) to the public which I would not like to. Another approach would be sharing the includes with them between my global classes, but that is said to be a bad design.
So, my question is: how do real ABAPers solve problems like this?
Here is an example of how one can access a local class defined in a report.
The report with the class.
REPORT ZZZ_PJ1.
CLASS lcl_test DEFINITION FINAL.
PUBLIC SECTION.
METHODS:
test.
ENDCLASS.
CLASS lcl_test IMPLEMENTATION.
METHOD test.
WRITE 'test'.
ENDMETHOD.
ENDCLASS.
The report which uses the class.
REPORT ZZZ_PJ2.
CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
PUBLIC SECTION.
CLASS-METHODS:
main.
ENDCLASS.
CLASS lcl_main IMPLEMENTATION.
METHOD main.
DATA:
lr_object TYPE REF TO object.
CREATE OBJECT lr_object
TYPE ('\PROGRAM=ZZZ_PJ1\CLASS=LCL_TEST')
CALL METHOD lr_object->('TEST').
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
lcl_main=>main( ).
Of course this is not a clever solution as each method call would have to be a dynamic call.
CALL METHOD lr_object->('TEST').
This could be solved however by using global interfaces that would define the methods of your classes (of course if they are not static which I assume they are not). Then you have to control each of the instances through the interface. Your target would be fulfilled then, as only the interface would be exposed globally, the implementations would remain in local classes.
You may want to do some reading on Model-View-Controller design patterns. Displaying data in a UI - would be a "view". Both the gathering and updating of data would be incorporated into a "Model" . Business logic should likely be implemented as an interaction between the view and the model in a "Controller".
That said, one approach to this is would be to utilize the friendship feature offered in ABAP OO.
As an example: create the model and view classes globally but only allow them to be instantiated privately, then grant private component access to the controller. Class definitions would be follows:
CLASS zcl_example_view DEFINITION
PUBLIC
FINAL
CREATE PRIVATE
GLOBAL FRIENDS zcl_example_controller
CLASS zcl_example_model DEFINITION
PUBLIC
FINAL
CREATE PRIVATE
GLOBAL FRIENDS zcl_example_controller
CLASS zcl_example_controller DEFINITION
PUBLIC
FINAL
CREATE PUBLIC
Additionally it may be a good idea to make the controller singleton and store a reference to it in both the view and the model. By enforcing that the controller IS BOUND when the view and model are instantiated we can effectively ensure that these three classes exist as only you desire.
Stepping back to your initial problem: I sounds to me like you're already using something like a MVC pattern in your development so your only problem is that some routines shall be used publicly by both models, views and controllers.
In this case I strongly recommend to put these routines in global available classes or to implement getter methods in your already existing classes to access those functionality.
Any hacks like \PROGRAM=ZZZ_PJ1\CLASS=LCL_TEST are sometimes essential but not here imho.
If your application is as large as you make it sound, you should organize it using multiple packages. You will certainly have to deal with non-OO stuff like function modules, data dictionary objects and other things that can not be part of a class, so using classes as the basic means to organize your application won't work outside of very small and specialized applications.
Furthermore, it sounds like you have some really severe flaws embedded in your plan if you think that "DB access logic" is something that should be "shared between classes". It is hard to guess without further information, but I would strongly suggest that you enlist someone who has experience in designing and implementing applications of that scale - at least to get the basic concept right.

Do I correctly understand what a class is?

I've had trouble finding a clear, concise laymans definition of a class. Usually, they give general ideas without specifically spelling it out, and I'm wondering if I'm understanding this correctly. As I understand it, a class is the set of code that controls an object. For example, in an app that has a button for 'Yes' and a button for 'No', and a text box for output, the code that tells the computer what to do when the user uses the Yes button is one class, the code for hitting No is another class, and an object is the two buttons and what they do together to influence the output box. Am I right, or am I confusing terms here?
Thanks
A class is a kind of thing, an object is an actual thing. So, in the real world, "person" is a class, you and I are objects (or instances) of that class. "Car" is a class, my 1996 beater Volvo station wagon is an object.
Objects all have certain similarities in form and function because of the class they belong to. When I say my station wagon is a "car", you have a pretty good idea of what it looks like, what it's used for, and what it can do. But objects of a class can also differ from each other. Just because something's a car doesn't tell you exactly what shape it is or how many seats it has or what color it is.
In the example you gave, it's likely that the yes and no buttons are both objects of the class "button" (or some similar name) and that the differences in their behavior are due to changes added by the programmer without his or her bothering to create a new class. However, it is possible that the programmer made the decision to make each type of button a subclass of the original class "button".
What's a subclass? Well, if you think of "car" as a class, it is obvious that there are several intermediate "kinds" of things between "car" and "Larry's 1996 beater Volvo station wagon". These could be "station wagon" and "Volvo station wagon". So my car would be an instance of "Volvo station wagon" which itself would be subclass of "station wagon" which would be a subclass of "car". From the "car" part, we know a good deal about my object, from the "station wagon" part we learn a little more, and from the "Volvo station wagon" a little more still.
The way in which classes and subclasses are arranged is a decision made by the programmer. In my example above, another programmer might have made the classes "car", "Volvos", "pre-Ford", and "Wagons". It depends on the problem you're trying to solve.
This is going to be a very simplified explanation. A class is a set of functions and variables and is used to create objects. I think it's good to use real examples instead of dog / bark / talk etc.
Class Email
Subject (string)
Message (string)
ToAddress (string)
FromAddress (string)
Send (function)
When you call 'new Email()' it creates a new object with those variables and functions. Then you can populate the variables and send it.
In object-oriented programming, a class is a type for objects. An object is a bundle of data together with functionality that can operate in the context of that data; the definition of what the object is and does when it is first created is determined by its class.
Like a type for data, the class of an object specifies what is common to all instances of that class. Instances, which are the objects themselves, then get to override that common baseline (otherwise there's not much point having distinct instances). In many OO systems, instances may or may not have new members that are not part of the class definition.
What that means in the context of a specific object-oriented language is going to differ from language to language. But if you think of classes as types, and build on that, you won't go far wrong.
A class is basically a way to organize your code.
It allows you to put all of the code related to one abstraction (think "concept" or "idea") in one place.
As an example - in your example of an app, the Window with the two buttons, a text box, and some code for handling what happens when the user types in the information may be organized into a single class: something like "PromptWindow". This class would be made up of multiple classes internally (two buttons, a textbox, etc) This would probably be used by some separate class, which would create an instance of the PromptWindow class, call a method on the class to show the window, then use the results.
At the very basis, there's procedural code:
var a = 4
var b = 5;
print a + b;
… and so on, statements following statements…
To make such pieces of code reusable, you make a function out of them:
function a_plus_b() {
var a = 4
var b = 5;
print a + b;
}
Now you can use that piece of code as often as you want, but you only had to write it once.
Usually an application depends on a certain way of how pieces of code and variables have to work together. This data needs to be processed by that function, but cannot be processed by that other function.
function foo(data) {
…do something…
return data;
}
function bar(data) {
…do something else…
return data;
}
a = "some data";
b = 123456;
a = foo(a);
b = bar(b);
c = bar(a); // ERROR, WRONG DATA FOR FUNCTION
To help group these related parts together, there are classes.
class A {
var data = 'some data';
function foo() {
…do something…
return data;
}
}
The function foo now has a variable data that is "bundled" with it in the same class. It can operate on that variable without having to worry about that it may be the wrong kind of data. Also there's no way that data can accidentally end up in function bar, which is part of another class.
The only problem is, there's only one variable data here. The function is reusable, but it can only operate on one set of data. To solve this, you create objects (also called instances) from the class:
instance1 = new A();
instance2 = new A();
instance1 and instance2 both behave exactly like class A, they both know how to perform function foo (now called an instance method) and they both hold a variable data (now called an instance variable or attribute), but that variable data can hold different data for both instances.
That's the basics of classes and objects. How your particular "OK", "Cancel" dialog box is implemented is a different story. Both buttons could be linked to different methods of different classes, or just to different methods of the same class, or even to the same method of the same class. Classes are just a way to logically group code and data, how that's going to be used is up to you.
In a language agnostic fasion, I would describe a class as being an object that contains related information.
A person class would have methods like Talk(), Walk(), Eat(); and attributes like Height, Color, Language, etc.
A class is like a blueprint of things that you can instantiate, and also procedures that are related to each other.
If you have a Database class, you might have many methods related to databases that do all sorts of voodoo with a database.
A class is a bunch of code that defines an entity in your application. There may be many such entities, but the behaviour of each is the same, as defined by the class. The class will typically define fields, whose contents are local to the instances (or objects) of that class. It is these fields that provide the objects with state and make them distinguishable from one another.
To use your example, there might be a Button class that defines what a button is in your application. This class would then be instantiated twice to provide two objects: one for the "No" button and another for the "Yes" button. The Button class could have a Text field/property that defines what text it contains – this could be set to "No" and "Yes" on the appropriate Button instances to give them their different appearances.
As for the click behaviour of the buttons, this would typically be implemented via the observer pattern, in which the subject class (Button in this case) maintains a list of separate "observer" objects which it notifies whenever some event occurs (i.e. when the button is clicked).
You should look at some sample code, in your language of choice. Just reading about the concept of classes will not answer many questions.
For example, I could tell you that a class is a "blueprint" for an object. Using this class, you can instantiate multiple such objects, each one of them (potentially) having unique attributes.
But you didn't understand a thing, now, did you? Your example with the buttons is very limited. Classes have nothing to do with user interfaces or actions or whatever. They define a way of programming, just like functions/methods/whatever you want to call them do.
So, to give a concrete example, here's a class that defines a ball, written in Python:
class Ball:
color = ''
def __init__(self, color):
self.color = color
def bounce(self):
print "%s ball bounces" % self.color
blueBall = Ball("blue")
redBall = Ball("red")
blueBall.bounce()
redBall.bounce()
Running this produces the expected output:
blue ball bounces
red ball bounces
However, there is much more to classes than I described here. Once you understand what a class is, you go on to learn about constructors, destructors, inheritance and a lot of other good stuff. Break a leg :)
From the definition of Class at Wikipedia:
In object-oriented programming, a
class is a construct that is used as
a blueprint (or template) to create
objects of that class. This blueprint
describes the state and behavior that
the objects of the class all share. An
object of a given class is called an
instance of the class. The class that
contains (and was used to create) that
instance can be considered as the type
of that object, e.g. an object
instance of the "Fruit" class would be
of the type "Fruit".
A class usually represents a noun,
such as a person, place or (possibly
quite abstract) thing - it is a model
of a concept within a computer
program. Fundamentally, it
encapsulates the state and behavior of
the concept it represents. It
encapsulates state through data
placeholders called attributes (or
member variables or instance
variables); it encapsulates behavior
through reusable sections of code
called methods.
Your understanding of a Class isn't at all incorrect but to make things clear consider the following...
The Yes and No buttons plus the TextBox are usually specified within a class taking for example code written in C# (Microsoft .NET Framework). Let's name this class MyClass.
The actions the buttons cause are handled by what are called handlers (methods). You could write your code in such a way that when you click the Yes button something gets written in the TextBox.
To instantiate MyClass you'd do the following:
MyClass myClass = new MyClass();
myClass.ButtonYes += new EventHandler(YourMethodForYes);
myClass.ButtonNo += new EventHandler(YourMethodForNo);
myClass.TextBox.Text = "Yes button was clicked";
Hope you get the idea.
I wrote usually above because this cenario you described could be implemented in a number of ways. OOP gives you plenty of ways to accomplish the same task.
Besides the definition of Class I think that reading about Object Oriented Programming (OOP) can help you a lot to understand it even more. Take a look at Fundamental Concepts.

Purpose of final and sealed

Why would anyone want to mark a class as final or sealed?
According to Wikipedia, "Sealed classes are primarily used to prevent derivation. They add another level of strictness during compile-time, improve memory usage, and trigger certain optimizations that improve run-time efficiency."
Also, from Patrick Smacchia's blog:
Versioning: When a class is originally sealed, it can change to unsealed in the future without breaking compatibility. (…)
Performance: (…) if the JIT compiler sees a call to a virtual method using a sealed types, the JIT compiler can produce more efficient code by calling the method non-virtually.(…)
Security and Predictability: A class must protect its own state and not allow itself to ever become corrupted. When a class is unsealed, a derived class can access and manipulate the base class’s state if any data fields or methods that internally manipulate fields are accessible and not private.(…)
Those are all pretty good reasons - I actually wasn't aware of the performance benefit implications until I looked it up just now :)
The versioning and security points seem like a huge benefit in terms of code confidence, which is very well justified on any kind of large project. It's no drop-in for unit testing, of course, but it would help.
Because creating a type for inheritance is much harder work than most folks think. It is best to mark all types this way by default as this will prevent others from inheriting from a type that was never intended to be extended.
Whether or not a type should be extended is a decision of the developer who created it, not the developer who comes along later and wants to extend it.
Joshua Bloch in his book Effective Java talks about it. He says "document for inheritance or disallow it".
The point is that class is sort of a contract between author and client. Allowing client to inherit from base class makes this contract much more strict. If you are going to inherit from it, you most likely are going to override some methods, otherwise you can replace inheritance with composition. Which methods are allowed to be overridden, and what you have to do implementing them - should be documented, or your code can lead to unpredictable results. As far as I remember, he shows such example - here is a collection class with methods
public interface Collection<E> extends Iterable<E> {
...
boolean add(E e);
boolean addAll(Collection<? extends E> c);
...
}
There is some implementation, i.e. ArrayList. Now you want to inherit from it and override some methods, so it prints to console a message when element is added. Now, do you need to override both add and addAll, or only add? It depends on how addAll is implemented - does it work with internal state directly (as ArrayList does) or calls add (as AbstractCollection does). Or may be there is addInternal, which is called by both add and addAll. There were no such questions until you decided to inherit from this class. If you just use it - it does not bother you. So the author of the class has to document it, if he wants you to inherit from his class.
And what if he wants to change the implementation in the future? If his class is only used, never inherited from, nothing stops him from changing implementation to more efficient. Now, if you inherited from that class, looked at source and found that addAll calls add, you override only add. Later author changes implementation so addAll no longer calls add - your program is broken, message is not printed when addAll is called. Or you looked at source and found that addAll does not call add, so you override add and addAll. Now author changes implementation, so addAll calls add - your program is broken again, when addAll is called message is printed twice for each element.
So - if you want your class to be inherited from, you need to document how. If you think that you may need to change something in the future that may break some subclasses - you need to think how to avoid it. By letting your clients inherit from your class you expose much more of internal implementation details that you do when you just let them use your class - you expose internal workflow, that is often subject to changes in future versions.
If you expose some details and clients rely on them - you no longer can change them. If it is ok with you, or you documented what can and what can not be overriden - that's fine. Sometimes you just don't want it. Sometimes you just want to say - "just use this class, never inherit from it, because I want a freedom to change internal implementation details".
So basically comment "Because the class doesn't want to have any children and we should respect it's wishes" is correct.
So, someone wants to mark a class as final/sealed, when he thinks that possible implementation details changes are more valuable than inheritance. There are other ways to achieve results similar to inheritance.