Page 1 of 1

Constants used all over the application

PostPosted: 19 Feb 2013, 22:20
by Ursego
Constants, used in the application globally, must be declared in not-autoinstantiated NVOs - one NVO for each constants group ("family"). Don't declare variables of those NVO's types; instead, use the automatically created global variable with the same name as the NVO (i.e. use it in the same way as static fields in Java).

For example, you can have an NVO named n_color for color constants, n_order_status for order statuses constants etc. It's a good idea to keep them all in one PBL so developers can easily check if the NVO for the group they need already exists (to avoid duplication). The constants are declared in the instance variables declaration section in a very straightforward way. Here is a possible set for n_order_status:

Code: Select all
public:

   constant string OPEN = "OPN"
   constant string CLOSED = "CLS"
   constant string CANCELED = "CNC"

If you open any not-autoinstantiated class in the "View Source" mode then you can see that PB automatically creates a global variable of that object's type with the same name as the class (violating the naming convention, ha-ha! :lol: ). For example, if you create n_order_status class (not-autoinstantiated, remember?) and look at its source, you see the following line:

Code: Select all
global n_order_status n_order_status

The first n_order_status is the data type, and the second - the name of that global variable. So, you don't need do declare a variable each time you need to use a constant - you always have one ready for use! That allows you to use the constant this way:

Code: Select all
if ls_order_status = n_order_status.OPEN then...

The created NVO must contain constants for ALL the codes of the group, even if now you need only some of them - that will help developers to see the whole picture for the given family when they have a look on the declaration section. If the codes are stored in the database then it's a good idea to add a comment with the SQL SELECT retrieving them.

For standalone constants (not belonging to any family) create one common NVO named, let's say, n_const.

----------------------------------------------------------------

Just to remind (I know that you know but...): If a constant is defined in the application for a value you are using, ALWAYS use the constant rather then hard-coded value! Otherwise why do we need constants at all?

----------------------------------------------------------------

Unfortunately, the method, described in this topic, doesn't create an enumeration like in other languages. If you need to pass an order status to a function, the argument type will be string (not n_order_status :cry: ), so it's your responsibility to validate the argument and throw an exception if its value is "kuku" or "bububu" rather than one of the constants of n_order_status.