Structures or javascript/json objects in progress ABL? - progress-4gl

We're migrating to 11.6 and I think it's a great moment to rethink old habits and improve some concepts.
One of these things is the way we've been dealing with parameter definitions in functions and procedures.
Often times we have procedures and functions that need a lot of parameters, either inputs or outputs. Personally, for readability and maintainability reasons, I don't like to have methods with too many parameters explicitly declared.
In order to avoid this problem and still allow a large number of parameters, we've manually implemented a key-value pair approach with a single parameter.
But there are some drawbacks with this approach:
It's not possible to tell which parameters are needed just by inspecting
the method signature.
You'll always need some boilerplate code, like methods for pushing and pulling values.
So with that said, I would like to hear some others' thoughts.
Have you ever implemented something similar?
Is there something that could work as a javascript/json object in ABL?
Current implementation.
DEFINE VARIABLE param as CHARACTER NO-UNDO.
addValue('id', '1', param).
addValue('date', STRING(TODAY), param).
RUN internalProc (INPUT param).
Desired implementation
param.id = 1
param.date = TODAY
RUN internalProc (INPUT param)

Since you are mentioning 11.6, why not use a real class based object (available since 10.1A).
yourpackage\yourparameter.cls:
CLASS yourpackage.yourclass:
DEFINE PUBLIC PROPERTY date AS DATE NO-UNDO
GET.
SET.
DEFINE PUBLIC PROPERTY id AS INTEGER NO-UNDO
GET.
SET.
CONSTRUCTOR PUBLIC yourclass ():
SUPER ().
END CONSTRUCTOR.
CONSTRUCTOR PUBLIC yourclass (pid AS INTEGER, pdate AS DATE):
SUPER ().
ASSIGN THIS-OBJECT:id = pid
THIS-OBJECT:date = DATE .
END CONSTRUCTOR.
END CLASS.
and the internal procedure:
DEFINE INPUT PARAMETER poParameter AS yourpackage.yourclass NO-UNDO .
and the caller:
DEFINE VARIABLE o AS yourpackage.yourclass NO-UNDO.
o = NEW yourpackage.yourclass().
o:id = 42.
o:date = TODAY.
RUN internalProc (o) .
alternative caller:
RUN internalProc (NEW yourpackage.yourclass (1, TODAY)) .
The ABL provides full OO capabilities from 10.1A on and that can be mixed nicely with procedural code. And parameter objects (structs) is a great way to get started with a few inital classes in legacy code.

Related

Tell IPython to use an object's `__str__` instead of `__repr__` for output

By default, when IPython displays an object, it seems to use __repr__.
__repr__ is supposed to produce a unique string which could be used to reconstruct an object, given the right environment.
This is distinct from __str__, which supposed to produce human-readable output.
Now suppose we've written a particular class and we'd like IPython to produce human readable output by default (i.e. without explicitly calling print or __str__).
We don't want to fudge it by making our class's __repr__ do __str__'s job.
That would be breaking the rules.
Is there a way to tell IPython to invoke __str__ by default for a particular class?
This is certainly possible; you just need implement the instance method _repr_pretty_(self). This is described in the documentation for IPython.lib.pretty. Its implementation could look something like this:
class MyObject:
def _repr_pretty_(self, p, cycle):
p.text(str(self) if not cycle else '...')
The p parameter is an instance of IPython.lib.pretty.PrettyPrinter, whose methods you should use to output the text representation of the object you're formatting. Usually you will use p.text(text) which just adds the given text verbatim to the formatted representation, but you can do things like starting and ending groups if your class represents a collection.
The cycle parameter is a boolean that indicates whether a reference cycle is detected - that is, whether you're trying to format the object twice in the same call stack (which leads to an infinite loop). It may or may not be necessary to consider it depending on what kind of object you're using, but it doesn't hurt.
As a bonus, if you want to do this for a class whose code you don't have access to (or, more accurately, don't want to) modify, or if you just want to make a temporary change for testing, you can use the IPython display formatter's for_type method, as shown in this example of customizing int display. In your case, you would use
get_ipython().display_formatter.formatters['text/plain'].for_type(
MyObject,
lambda obj, p, cycle: p.text(str(obj) if not cycle else '...')
)
with MyObject of course representing the type you want to customize the printing of. Note that the lambda function carries the same signature as _repr_pretty_, and works the same way.

how single and double type variables work in the same copy of code in Matlab like template in C++

I am writing a signal processing program using matlab. I know there are two types of float-pointing variables, single and double. Considering the memory usage, I want my code to work with only single type variable when the system's memory is not large, while it can also be adapted to work with double type variables when necessary, without significant modification (simple and light modification before running is OK, i.e., I don't need runtime-check technique). I know this can be done by macro in C and by template in C++. I don't find practical techniques which can do this in matlab. Do you have any experience with this?
I have a simple idea that I define a global string containing "single" or "double", then I pass this string to any memory allocation method called in my code to indicate what type I need. I think this can work, I just want to know which technique you guys use and is widely accepted.
I cannot see how a template would help here. The type of c++ templates are still determined in compile time (std::vector vec ...). Also note that Matlab defines all variables as double by default unless something else is stated. You basically want runtime checks for your code. I can think of one solution as using a function with a persistent variable. The variable is set once per run. When you generate variables you would then have to generate all variables you want to have as float through this function. This will slow down assignment though, since you have to call a function to assign variables.
This example is somehow an implementation of the singleton pattern (but not exactly). The persistent variable type is set at the first use and cannot change later in the program (assuming that you do not do anything stupid as clearing the variable explicitly). I would recommend to go for hardcoding single in case performance is an issue, instead of having runtime checks or assignment functions or classes or what you can come up with.
function c = assignFloat(a,b)
persistent type;
if (isempty(type) & nargin==2)
type = b;
elseif (isempty(type))
type = 'single';
% elseif(nargin==2), error('Do not set twice!') % Optional code, imo unnecessary.
end
if (strcmp(type,'single'))
c = single(a);
return;
end
c = double(a);
end

Using LuaJ with Scala

I am attempting to use LuaJ with Scala. Most things work (actually all things work if you do them correctly!) but the simple task of setting object values has become incredibly complicated thanks to Scala's setter implementation.
Scala:
class TestObject {
var x: Int = 0
}
Lua:
function myTestFunction(testObject)
testObject.x = 3
end
If I execute the script or line containing this Lua function and pass a coerced instance of TestObject to myTestFunction this causes an error in LuaJ. LuaJ is trying to direct-write the value, and Scala requires you to go through the implicitly-defined setter (with the horrible name x_=, which is not valid Lua so even attempting to call that as a function makes your Lua not parse).
As I said, there are workarounds for this, such as defining your own setter or using the #BeanProperty markup. They just make code that should be easy to write much more complicated:
Lua:
function myTestFunction(testObject)
testObject.setX(testObject, 3)
end
Does anybody know of a way to get luaj to implicitly call the setter for such assignments? Or where I might look in the luaj source code to perhaps implement such a thing?
Thanks!
I must admit that I'm not too familiar with LuaJ, but the first thing that comes to my mind regarding your issue is to wrap the objects within proxy tables to ease interaction with the API. Depending upon what sort of needs you have, this solution may or may not be the best, but it could be a good temporary fix.
local mt = {}
function mt:__index(k)
return self.o[k] -- Define how your getters work here.
end
function mt:__newindex(k, v)
return self.o[k .. '_='](v) -- "object.k_=(v)"
end
local function proxy(o)
return setmetatable({o = o}, mt)
end
-- ...
function myTestFunction(testObject)
testObject = proxy(testObject)
testObject.x = 3
end
I believe this may be the least invasive way to solve your problem. As for modifying LuaJ's source code to better suit your needs, I had a quick look through the documentation and source code and found this, this, and this. My best guess says that line 71 of JavaInstance.java is where you'll find what you need to change, if Scala requires a different way of setting values.
f.set(m_instance, CoerceLuaToJava.coerce(value, f.getType()));
Perhaps you should use the method syntax:
testObject:setX(3)
Note the colon ':' instead of the dot '.' which can be hard to distinguish in some editors.
This has the same effect as the function call:
testObject.setX(testObject, 3)
but is more readable.
It can also be used to call static methods on classes:
luajava.bindClass("java.net.InetAddress"):getLocalHost():getHostName()
The part to the left of the ':' is evaluated once, so a statement such as
x = abc[d+e+f]:foo()
will be evaluated as if it were
local tmp = abc[d+e+f]
x = tmp.foo(tmp)

Why some variable of struct take preprocessor to function?

Variables of struct declared by data type of language in the header file. Usually data type using to declare variables, but other data type pass to preprocessors. When we should use to a data type send to preprocessor for declare variables? Why data type and variables send to processor?
#define DECLARE_REFERENCE(type, name) \
union { type name; int64_t name##_; }
typedef struct _STRING
{
int32_t flags;
int32_t length;
DECLARE_REFERENCE(char*, identifier);
DECLARE_REFERENCE(uint8_t*, string);
DECLARE_REFERENCE(uint8_t*, mask);
DECLARE_REFERENCE(MATCH*, matches_list_head);
DECLARE_REFERENCE(MATCH*, matches_list_tail);
REGEXP re;
} STRING;
Why this code is doing this for declarations? Because as the body of DECLARE_REFERENCE shows, when a type and name are passed to this macro it does more than just the declaration - it builds something else out of the name as well, for some other unknown purpose. If you only wanted to declare a variable, you wouldn't do this - it does something distinct from simply declaring one variable.
What it actually does? The unions that the macro declares provide a second name for accessing the same space as a different type. In this case you can get at the references themselves, or also at an unconverted integer representation of their bit pattern. Assuming that int64_t is the same size as a pointer on the target, anyway.
Using a macro for this potentially serves several purposes I can think of off the bat:
Saves keystrokes
Makes the code more readable - but only to people who already know what the macros mean
If the secondary way of getting at reference data is only used for debugging purposes, it can be disabled easily for a release build, generating compiler errors on any surviving debug code
It enforces the secondary status of the access path, hiding it from people who just want to see what's contained in the struct and its formal interface
Should you do this? No. This does more than just declare variables, it also does something else, and that other thing is clearly specific to the gory internals of the rest of the containing program. Without seeing the rest of the program we may never fully understand the rest of what it does.
When you need to do something specific to the internals of your program, you'll (hopefully) know when it's time to invent your own thing-like-this (most likely never); but don't copy others.
So the overall lesson here is to identify places where people aren't writing in straightforward C, but are coding to their particular application, and to separate those two, and not take quirks from a specific program as guidelines for the language as a whole.
Sometimes it is necessary to have a number of declarations which are guaranteed to have some relationship to each other. Some simple kinds of relationships such as constants that need to be numbered consecutively can be handled using enum declarations, but some applications require more complex relationships that the compiler can't handle directly. For example, one might wish to have a set of enum values and a set of string literals and ensure that they remain in sync with each other. If one declares something like:
#define GENERATE_STATE_ENUM_LIST \
ENUM_LIST_ITEM(STATE_DEFAULT, "Default") \
ENUM_LIST_ITEM(STATE_INIT, "Initializing") \
ENUM_LIST_ITEM(STATE_READY, "Ready") \
ENUM_LIST_ITEM(STATE_SLEEPING, "Sleeping") \
ENUM_LIST_ITEM(STATE_REQ_SYNC, "Starting synchronization") \
// This line should be left blank except for this comment
Then code can use the GENERATE_STATE_ENUM_LIST macro both to declare an enum type and a string array, and ensure that even if items are added or removed from the list each string will match up with its proper enum value. By contrast, if the array and enum declarations were separate, adding a new state to one but not the other could cause the values to get "out of sync".
I'm not sure what the purpose the macros in your particular case, but the pattern can sometimes be a reasonable one. The biggest 'question' is whether it's better to (ab)use the C preprocessor so as to allow such relationships to be expressed in valid-but-ugly C code, or whether it would be better to use some other tool to take a list of states and would generate the appropriate C code from that.

Difference between a function and procedure?

I had a doubt
I know that main difference between a function and procedure is
The function compulsory returns a value where as a procedure may or may not returns value.
But when we use a function of type void it returns nothing.
Can u people please clarify my doubt.
Traditionally, a procedure returning a value has been called a function (see below), however, many modern languages dispense with the term procedure altogether, preferring to use the term function for all named code blocks.
Read more at Suite101: Procedure, subroutine or function?: Programming terminology 101 - a look at the differences in approach and definition of procedures, subroutines and functions. http://www.suite101.com/content/procedure--subroutine-or-function--a8208#ixzz1GqkE7HjE
In C and its derivatives, the term "procedure" is rarely used. C has functions some of which return a value and some of which don't. I think this is an artefact of C's heritage where before the introduction of void in ANSI C, there was no way to not return a value. By default functions returned an int which you could ignore (can still) and might be some random number if no explicit return value was specified.
In the Pascal language family, the difference is explicit, functions return a value and procedures don't. A different keyword is used in each case for the definition. Visual Basic also differentiates with functions and subroutines(?).
Since we are talking about Objective-C, there are some further issues to confuse you. Functions associated with a class or object are known as "methods" (class methods and instance methods respectively).
Also, if we are being pedantic, you don't call Objective-C methods, you invoke them by sending a message to the object. The distinction is actually quite important because the message name (aka "selector") does not necessarily always refer to the same method, it can be changed at run time. This is fundamentally different to languages like Java and C++ where a particular method name for a particular class is really just a symbolic name for the address of the block of code constituting the body of the method.
Depending on the programming language, the distinction may be not so clear. Let's take a conservative language, Pascal:
procedure indeed has no return value. It is used for operations which do not have a return value, or have multiple return values. In the latter case, multiple arguments (the return-arguments or output-arguments) are passed by reference (using the var keyword) and their values are directly modified from inside the procedure. (Note that this latter case may not be considered good practice, depending on the circumstances).
function has a single return value, and usually we do not expect it to change the value of any of its arguments (which arguments may then be passed by value, or via the const keyword). Multiple return values may be returned by bundling them into a record.
C or Java does not distinguish syntactically, so a function of return type void can be thought of as a procedure. Scala distinguished between them by the presence of an equals sign between the method head and method body.
Generally, no matter how an actual language calls its construct, we would ideally expect that
A function takes arguments, doesn't modify any state (like mutating arguments, global variables, or printing info for the user to the console), and returns the result of computation.
A procedure takes arguments, performs operations which can have side-effects (writing to a database, printing to the console, maybe mutating variables), but hopefully doesn't mutate any arguments.
In practice however, depending on the situation, blends of these expectations can be observed. Sticking to these guidelines helps I think.