abap reference variables and dynamic types - abap

I'm fluent in ABAP and have a grasp on OO and light reference variables, but can't seem to get a deeper handle on reference variables and dynamic types etc. I've done a bit of reading, but can't seem to get the deep understanding I feel I need.
Does anyone know of some great tutorials or websites that might give clear and concise? Thanks!

First of all just google this post title and You're golden.
Second:
I'm not sure if I understand You correctly, do You want to know about such constructions as:
DATA lo_ref_var TYPE REF TO zcl_my_class.
And by dynamic types do You mean in ABAP 7.4/7.5 (ex. DATA(lv_var) = 123)?
If yes, I'll try to give You the general idea:
Reference variable is just a variable that's "ready to become" an object.
If You'll take this for example:
DATA lo_ref_var TYPE REF TO zcl_my_class.
CREATE OBJECT lo_ref_var.
Then assuming the constructor doesn't need any variables You'll get an instance of zcl_my_class Class with all it's attributes and methods. Also if You have an abstract class zcl_abs_class as a super-class and zcl_sub_class1 and zcl_sub_class2 as it's non-abstract subclass' than:
DATA:
lo_abs TYPE REF TO zcl_abs_class,
lo_sub1 TYPE REF TO zcl_sub_class1,
lo_sub2 TYPE REF TO zcl_sub_class2.
CREATE OBJECT: lo_sub1, lo_sub2.
lo_abs ?= lo_sub1.
lo_abs ?= lo_sub2.
What You can do (as seen above) is cast a subclass object to the super-class reference variable since the subclass' inherits from zcl_abs_class.
For more, do some digging.
Dynamic types:
This is in fact very simple, all You need to remember is that a variable has to have a type when being created dynamically. So for example:
DATA(lv_text) = text-000.
DATA(lv_int) = 1.
Line with lv_text will not work (will not compile) since text-000 does not have a precise type.
The second line on the other hand will take the type I.
If one would like to decide which type to choose You can do this by writing:
DATA(lv_bukrs) = CONV bukrs( '1234' ).
You can even use the type that an already existing variable has by writing:
DATA(lv_bukrs2) = CONV #( lv_bukrs ).
since the "#" means "use the type of variable inside brackets".
Hope this will help You start :)

Related

How to import parameter of type ANY?

How can I put what a method - in this example get_properties - is giving me into a local variable when the type of the parameter is ANY?
"ES_ATTRIBUTES Exporting Type ANY
some_object->get_properties( IMPORTING es_attributes = ????? ).
I tried to put it into this variable, but that didn't work:
FIELD-SYMBOLS:
<ls_attributes> TYPE any.
In ABAP, it means that you may use a data object of any type (the simplest way is to declare it with DATA).
But it may be more restrictive according to the way the developer has coded his method.
Here, I recognize a method of WebUI Components (CRM, SOLMAN, …) so the data object must correspond to the "some_object" you are accessing. Do a debug of GET_PROPERTIES if you are not sure.
Actually as a caller, you should know the type you want to import for this ANY parameter.
You have to know the protocol of GET_PROPERTIES and debug it to know the return type of the parameter. In your method, you create a DATA REFERENCE and have it assigned to a ANY field symbol.
Data:
lr_data type ref to data.
Field-symbols:
<lt_properties> type any.
create data lr_data type TYPE_NAME. 'You should know the type
assign lr_data->* to <lt_properties>.
From my personal view, it is not a very good practice to define a method with EXPORTING parameter type ANY.
You either define a interface with IF_**_PROPERTY and you have a return TABLE of this interface.
or you return a name-value pair table. (From the method signature, it should return a TABLE, GET_PROPERTIES).

Single-line method calls with untyped parameters

Can I define an ABAP method where the RETURNING parameter and any IMPORTING parameters have a generic type but that can still be called in a single line as a functional method?
In other words I'd like to replace this:
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
EXPORTING
input = lv_external_value
IMPORTING
output = lv_internal_value.
With:
lv_internal_value= zcl_conversion=>alpha_input( lv_external_value ).
Unfortunately the fact that Class Methods can't have an untyped returning parameter is preventing me from declaring the functional method's return value as type ANY or CLIKE. The accepted standard of creating generic method parameters seems to be to define them as TYPE REF TO DATA and dereference/assign them. But as far as I know that prevents me from calling the method in a single statement as I have to first assign the importing parameter and then dereference the returning parameter, resulting in the same or more lines of code than a simple FM call.
Is there a way around this?
Unfortunately, there is no other way to dereference data than to use the dereference operator, either in the form ->* for the full value segment, or in the form ->comp, if the data object is structured and has a component named comp (and, even worse, there are a lot of places in ABAP code where you would like to use a value from a derefenced data object but can't do it for internal reasons / syntax restrictions).
However, you could simply keep the data reference object retrieved by your method in a variable of the calling code and work with that variable (instead of using a field symbol or a variable for the derefenced value segment itself). Either generically, as a ref to data variable, or typed, using the CAST operator (new ABAP syntax).
Most things that can be done with a field-symbol, can also be done directly with a data reference as well.
Example: Working with a variable result of the expected return type:
data(result) = cast t000( cl=>m( ) ).
write result->mandt.
See here the full example:
report zz_new_syntax.
class cl definition.
public section.
class-methods m returning value(s) type ref to data.
endclass.
start-of-selection.
data(result) = cast t000( cl=>m( ) ).
write: / result->mandt. " Writes '123'.
class cl implementation.
method m.
s = new t000( mandt = '123' ).
endmethod.
endclass.
On ABAP NW Stack 7.4 you could just use parameters type STRING and then use the new CONV Operator to convert your actual input in string. Little ugly but should work.
lv_internal_value = CONV #(zcl_conversion=>alpha_input( CONV #(lv_external_value) )).

How to declare variables with a type in Lua

Is it possible to create variables to be a specific type in Lua?
E.g. int x = 4
If this is not possible, is there at least some way to have a fake "type" shown before the variable so that anyone reading the code will know what type the variable is supposed to be?
E.g. function addInt(int x=4, int y=5), but x/y could still be any type of variable? I find it much easier to type the variable's type before it rather than putting a comment at above the function to let any readers know what type of variable it is supposed to be.
The sole reason I'm asking isn't to limit the variable to a specific data type, but simply to have the ability to put a data type before the variable, whether it does anything or not, to let the reader know what type of variable that it is supposed to be without getting an error.
You can do this using comments:
local x = 4 -- int
function addInt(x --[[int]],
y --[[int]] )
You can make the syntax a = int(5) from your other comment work using the following:
function int(a) return a end
function string(a) return a end
function dictionary(a) return a end
a = int(5)
b = string "hello, world!"
c = dictionary({foo = "hey"})
Still, this doesn't really offer any benefits over a comment.
The only way I can think of to do this, would be by creating a custom type in C.
Lua Integer type
No. But I understand your goal is to improve understanding when reading and writing functions calls.
Stating the expected data type of parameters adds only a little in terms of giving a specification for the function. Also, some function parameters are polymorphic, accepting a specific value, or a function or table from which to obtain the value for a context in which the function operates. See string.gsub, for example.
When reading a function call, the only thing known at the call site is the name of the variable or field whose value is being invoked as a function (sometimes read as the "name" of the function) and the expressions being passed as actual parameters. It is sometimes helpful to refactor parameter expressions into named local variables to add to the readability.
When writing a function call, the name of the function is key. The names of the formal parameters are also helpful. But still, names (like types) do not comprise much of a specification. The most help comes from embedded structured documentation used in conjunction with an IDE that infers the context of a name and performs content assistance and presentations of available documentation.
luadoc is one such a system of documentation. You can write luadoc for function you declare.
Eclipse Koneki LDT is one such an IDE. Due to the dynamic nature of Lua, it is a difficult problem so LDT is not always as helpful as one would like. (To be clear, LDT does not use luadoc; It evolved its own embedded documentation system.)

Common name for variable and constant

In programming (and math) there are variables and constants. Is there a name to describe both of them?
I was thinking value, but that's not it. A value is what variables/constants contain, not what they are.
I would call it a symbol. From google:
sym·bol/ˈsimbəl/Noun
1. A thing that represents or stands for something else,
esp. a material object representing something abstract.
...
From what I know Its called a field
How about:
maths and logic: term
programming: l-value and r-value.
There are a few different terms I use, depending on context. I'll give you a list of the terms I (might) use - sometimes I'll just default to calling everything 'variables'.
Field - a variable or constant that's declared as part of the class definition.
Parameter - one of the inputs specified when defining a method in a class.
Argument - the actual value that you provide for a parameter when calling a method.
Method variable - a variable declared inside a method.
Method constant - a constant declared inside a method.
In OOP, the attribute can be both a variable and a constant.
Identifiers
In computer languages, identifiers are tokens (also called symbols) which name language entities. Some of the kinds of entities an identifier might denote include variables, types, labels, subroutines, and packages.
Symbols are super set of Identifiers
https://en.wikipedia.org/wiki/Identifier#In_computer_languages
How about "data item"?
One definition: https://www.yourdictionary.com/data-item
Example showing it can be used for local variables/constants as well (unlike "field" or "attribute"): https://www.microfocus.com/documentation/visual-cobol/VC222/EclWin/GUID-A3B817EE-1D63-4F67-A62C-61DE681C6719.html

Does static typing mean that you have to cast a variable if you want to change its type?

Are there any other ways of changing a variable's type in a statically typed language like Java and C++, except 'casting'?
I'm trying to figure out what the main difference is in practical terms between dynamic and static typing and keep finding very academic definitions. I'm wondering what it means in terms of what my code looks like.
Make sure you don't get static vs. dynamic typing confused with strong vs. weak typing.
Static typing: Each variable, method parameter, return type etc. has a type known at compile time, either declared or inferred.
Dynamic typing: types are ignored/don't exist at compile time
Strong typing: each object at runtime has a specific type, and you can only perform those operations on it that are defined for that type.
Weak typing: runtime objects either don't have an explicit type, or the system attempts to automatically convert types wherever necessary.
These two opposites can be combined freely:
Java is statically and strongly typed
C is statically and weakly typed (pointer arithmetics!)
Ruby is dynamically and strongly typed
JavaScript is dynamically and weakly typed
Genrally, static typing means that a lot of errors are caught by the compiler which are runtime errors in a dynamically typed language - but it also means that you spend a lot of time worrying about types, in many cases unnecessarily (see interfaces vs. duck typing).
Strong typing means that any conversion between types must be explicit, either through a cast or through the use of conversion methods (e.g. parsing a string into an integer). This means more typing work, but has the advantage of keeping you in control of things, whereas weak typing often results in confusion when the system does some obscure implicit conversion that leaves you with a completely wrong variable value that causes havoc ten method calls down the line.
In C++/Java you can't change the type of a variable.
Static typing: A variable has one type assigned at compile type and that does not change.
Dynamic typing: A variable's type can change while runtime, e.g. in JavaScript:
js> x="5" <-- String
5
js> x=x*5 <-- Int
25
The main difference is that in dynamically typed languages you don't know until you go to use a method at runtime whether that method exists. In statically typed languages the check is made at compile time and the compilation fails if the method doesn't exist.
I'm wondering what it means in terms of what my code looks like.
The type system does not necessarily have any impact on what code looks like, e.g. languages with static typing, type inference and implicit conversion (like Scala for instance) look a lot like dynamically typed languages. See also: What To Know Before Debating Type Systems.
You don't need explicit casting. In many cases implicit casting works.
For example:
int i = 42;
float f = i; // f ~= 42.0
int b = f; // i == 42
class Base {
};
class Subclass : public Base {
};
Subclass *subclass = new Subclass();
Base *base = subclass; // Legal
Subclass *s = dynamic_cast<Subclass *>(base); // == subclass. Performs type checking. If base isn't a Subclass, NULL is returned instead. (This is type-safe explicit casting.)
You cannot, however, change the type of a variable. You can use unions in C++, though, to achieve some sort of dynamic typing.
Lets look at Java for he staitically typed language and JavaScript for the dynamc. In Java, for objects, the variable is a reference to an object. The object has a runtime type and the reference has a type. The type of the reference must be the type of the runtime object or one of its ancestors. This is how polymorphism works. You have to cast to go up the hierarchy of the reference type, but not down. The compiler ensures that these conditions are met. In a language like JavaScript, your variable is just that, a variable. You can have it point to whatever object you want, and you don't know the type of it until you check.
For conversions, though, there are lots of methods like toInteger and toFloat in Java to do a conversion and generate an object of a new type with the same relative value. In JavaScript there are also conversion methods, but they generate new objects too.
Your code should actally not look very much different, regardless if you are using a staticly typed language or not. Just because you can change the data type of a variable in a dynamically typed language, doesn't mean that it is a good idea to do so.
In VBScript, for example, hungarian notation is often used to specify the preferred data type of a variable. That way you can easily spot if the code is mixing types. (This was not the original use of hungarian notation, but it's pretty useful.)
By keeping to the same data type, you avoid situations where it's hard to tell what the code actually does, and situations where the code simply doesn't work properly. For example:
Dim id
id = Request.QueryString("id") ' this variable is now a string
If id = "42" Then
id = 142 ' sometimes turned into a number
End If
If id > 100 Then ' will not work properly for strings
Using hungarian notation you can spot code that is mixing types, like:
lngId = Request.QueryString("id") ' putting a string in a numeric variable
strId = 42 ' putting a number in a string variable