Monday, September 3, 2012

Getting Your Product Into the Habit Zone

[source] http://techcrunch.com/2012/09/02/getting-your-product-into-the-habit-zone/



Editor’s Note: Nir Eyal is a Lecturer in Marketing at the Stanford Graduate School of Business and the author of the forthcoming book “Hooked: How to Drive Engagement by Creating User Habits.” Nir blogs about the intersection of psychology, technology, and business at NirAndFar.com.
As the web becomes an increasingly crowded place, users are desperate for solutions to sort through the online clutter. The Internet has become a giant hairball of choice-inhibiting noise and the need to make sense of it all has never been more acute.
Just ask high-flying sites like Pinterest, Reddit, and Tumblr. These curated web portals connect millions of people to information they never knew they were looking for. Some have started monetizing this tremendous flow of traffic and though it’s too early to call winners and losers, their strategy of driving user engagement by creating daily habits is clear. These companies are following a plan implemented by web titans like Amazon and Google and are hoping to yield similar results.
Creating user habits leverages two critical factors that should be considered by every company attempting to build high-engagement products.

ACTION WITHOUT COGNITION

Habits are one of the ways the brain learns complex behaviors. In order to allow us to focus our attention on obtaining new insights, neuroscientists believe habitual behaviors are moved to the basal ganglia, an area of the brain associated with actions requiring little or no cognition. Habits form when the brain takes a shortcut and stops actively deliberating about the decision being made.
The brain quickly learns to codify behaviors that provide a solution to whatever problem it encounters. For example, nail biting is a common behavior, which occurs with little or no thought, typically triggered by the unpleasant feeling of stress. The biter associates the satisfaction of nail chomping with the temporary relief it provides. As any habitual nail bitter knows, the conditioned response is extremely difficult to break.
Like nail biting, many of the decisions we make in our daily lives are made simply because that’s the way we’ve found satisfaction in the past. The brain automatically deduces that if the decision was a good one yesterday, then it’s a safe bet again today.

THE MIND MONOPOLY

In a recent study at the University College London, researchers followed participants as they attempted to form a habit of flossing their teeth. As one of its findings, the study concluded that the more frequently the new behavior occurred, the stronger the habit. Like flossing, frequent engagement with a web site or app increases the likelihood of forming new habits.
Google search provides an example of a service built upon a frequent behavior creating users habits. If you’re skeptical that Google is habit-forming, just try using Bing. In a head-to-head comparison of the efficacy of an incognito search, the products are nearly identical. Even if the geniuses at Google have in fact perfected a faster algorithm, the time saved is imperceptible to everyone but robots and Mister Spock. Milliseconds matter, but they don’t hook users.
Instead, habits are what keep users loyal. If a user is familiar with the Google interface, switching to Bing requires cognitive effort. Though many aspects or Bing are identical to Google, even a slight change in pixel placement forces the would-be convert to learn something new. Adapting to the differences in the Bing interface is what actually slows the user down and makes Bing feel inferior.
Internet searches occur so frequently that Google is able to cement its tool as the one and only solution in the habitual users’ mind. Users no longer need to think about whether or not to use Google, they just do. Furthermore, whenever the company can identify the user, it improves search results based on past behaviors. The more the product is used, the better the algorithm gets and thus, the more it is used. The result is a virtuous cycle of habit-driven behavior resulting in total market domination.

HABITS AS STRATEGY

But sometimes a behavior does not occur as frequently as flossing or Googling, and yet becomes a habit. For an infrequent action to become a habit, the user must perceive a high degree of utility, either from gaining pleasure or avoiding pain.
Take Amazon as an example; the e-tailer has its sights set on becoming the world’s one-stop shop. Amazon is so confident in its ability to form user habits that it runs ads for directly competitive products on its site. Customers often see the item they are about to buy listed at a cheaper price and regularly click away to transact elsewhere. To some, this sounds like a formula for financial suicide. But to Amazon, it’s a shrewd business strategy.
Not only does Amazon make money from the ads it runs from competing businesses, but it also utilizes other people’s marketing dollars to form a habit in the shopper’s mind. Amazon seeks to become the solution to a frequently occurring pain point: the customer’s needs to find the item they’re looking for at the best possible price. By addressing the shopper’s price concerns, Amazon earns loyalty even if it doesn’t make the sale.
The tactic is backed by a 2003 study by Trifts and Hubl, which demonstrated that consumer’s preference for an online retailer increases when they are offered competitive price information. The technique has also been used by Progressive to drive over $15 billion of annual insurance sales, up from just $3.4 billion before the tactic was implemented.
By allowing users to comparison shop from within the site, Amazon provides tremendous perceived utility to its customers. Though shopping on Amazon may not occur as frequently as searching on Google, the company solidifies its place as the default solution to customers’ purchasing needs with each successful transaction.

IN THE ZONE

Companies can begin to determine their product’s potential for forming a habitual behavior by plotting two factors: frequency (how often the behavior occurs) and perceived utility (how rewarding the behavior is in the eyes of the user). “The Habit Zone,” as I call it, is where an action occurs with enough frequency and perceived utility for it to become the default behavior.
Established companies like Google and Amazon, along with new entrants like Pinterest and Reddit, succeed by creating user habits. They help people find what they are looking for amid the ever-increasing online clutter. In return, users reward them with engagement and loyalty, turning to them as their go-to solutions in their respective categories. When a habit is formed, the script for what to do next is written, making the behavior more likely to occur in the future. These companies leverage habits to earn their places in users’ lives and minds.

Sunday, September 2, 2012

CALL - Calling a Method in ABAP Objects


Variants:

Effect

Call a method meth within ABAP objects.

Methods belong to the components of classes. They are accessed either statically using variants 1 through 4 ordynamically using variant 5. Dynamic access to methods is called Dynamic Invoke. Dynamic access via class references allows you to call all methods of an object, irrespective of the type of reference variables. 

The interface of a method is completely defined when the method is declared using the METHODS or CLASS-METHODS statement. The additions of the statement CALL METHOD pass actual parameters to this interface, or accept actual parameters from it. 

Variant 1a

CALL METHOD meth    [additions].

Variant 1b

[CALL METHOD] meth( [additions] ).


Extras:

Effect

Static Method Call

Additions 1 through 5 are used to pass parameters statically. They can also be used for static method calls. If no additions are used, the method meth is called without parameter passing and without exception handling.

For variant 1a, you must specify the statement CALL METHOD. For variant 1b, where the additions are specified in brackets, you can omit the statment CALL METHOD. Variants 2 through 4 are short forms of variant 1b. As before, methods can be called as operands in expressions if they meet certain requirements (see note below).

Addition 1

... EXPORTING p1 = f1       ... pn = fn

Effect

With the EXPORTING addition, the caller must pass type-suitable actual parameters f1 ... fn to allIMPORTING parameters p1 ... pn of a statically called method. These parameters must not be declared as optional. 

Example

CLASS C1 DEFINITION.
  PUBLIC SECTION.
    METHODS M1 IMPORTING P1 TYPE I DEFAULT 5
                         P2 TYPE C OPTIONAL
                         P3 TYPE D.
ENDCLASS.

DATA: F TYPE D,
      O1 TYPE REF TO C1.

CREATE OBJECT O1.

CALL METHOD O1->M1 EXPORTING P3 = F.

CLASS C1 IMPLEMENTATION.
  METHOD M1.
    ...
  ENDMETHOD.
ENDCLASS. 

The method M1 is called using variant 1a.

Addition 2

... IMPORTING  p1 = f1       ... pn = fn

Effect

Using the optional IMPORTING addition, the caller can copy the EXPORTING parameters p1 ... pn of a method into type-suitable actual parameters f1 ... fn

Example

CLASS C1 DEFINITION.
  PUBLIC SECTION.
    METHODS M1 EXPORTING P1 TYPE I
                         P2 TYPE C
                         P3 TYPE D.
ENDCLASS.

DATA: F TYPE D,
      O1 TYPE REF TO C1.

CREATE OBJECT O1.

O1->M1( IMPORTING P3 = F ).

CLASS C1 IMPLEMENTATION.
  METHOD M1.
    ...
  ENDMETHOD.
ENDCLASS. 

You call the method M1 using variant 1b, while omitting the statement CALL METHOD.

Addition 3

... CHANGING p1 = f1       ... pn = fn

Effect

Using the CHANGING addition, the caller must pass type-suitable actual parameters f1 ... fn to all CHANGINGparameters p1 ... pn of a statically called method. These parameters are not declared as optional. As soon as the method is complete, the caller automatically copies the CHANGING parameters into the actual parameters. 

Example

CLASS C1 DEFINITION.
  PUBLIC SECTION.
    METHODS M1 CHANGING P1 TYPE I OPTIONAL
                        P2 TYPE C
                        P3 TYPE D DEFAULT SY-DATUM.
ENDCLASS.

DATA: F TYPE C,
      O1 TYPE REF TO C1.

CREATE OBJECT O1.

CALL METHOD O1->M1 CHANGING P2 = F.

CLASS C1 IMPLEMENTATION.
  METHOD M1.
    ...
  ENDMETHOD.
ENDCLASS. 

Methode M1 is called using variant 1a.

Addition 4

... RECEIVING p = f 

Effect

Using the optional RECEIVING addition, the caller can copy the return value p of a method meth into a type-suitable actual parameter f. The formal parameter is transferred to the actual parameter in the same way as with an assignment (MOVE). You must be able to convert the data type of the formalparameter into the data type of the actual parameter.

Example

CLASS C1 DEFINITION.
  PUBLIC SECTION.
    METHODS M1 RETURNING VALUE(R) TYPE I.
ENDCLASS.

DATA: F TYPE I,
      O1 TYPE REF TO C1.

CREATE OBJECT O1.

O1->M1( RECEIVING R = F ).

CLASS C1 IMPLEMENTATION.
  METHOD M1.
    ...
  ENDMETHOD.
ENDCLASS. 

You call method M1 using variant 1b, while omitting the CALL METHOD statement.

Addition 5

... EXCEPTIONS except1 = rc1 ... exceptn = rcn 

Effect

Using the optional EXCEPTIONS addition, the caller can handle exceptional situations in a method meth. Exceptions are triggered by the statements ,RAISE except, and MESSAGE RAISING in the method. 

The caller handles an exception except by including it in the EXCEPTIONS list and by thus creating a link with a return value rc. If the exception is triggered, the system terminates method processing, returns to the caller, and there assigns the return value rc to the system variable SY-SUBRC.

For output parameters of the method that are defined for value passing (EXPORTINGCHANGING and RETURNINGparameters), no values are passed to the actual parameters when an exception occurs. For output parameters defined for reference passing (default setting), the formal parameters and actual parameters have the same value at any one time. 

If the caller does not handle an exception triggered by RAISE except, the current program terminates.

If the caller does not handle an exception triggered by MESSAGE RAISING, the specified message is sent, and the system continues processing in accordance with the message type specified.

Notes

  1. As with function modules, you can catch the exception OTHERS predefined by the system to handle various user-defined exceptions simultaneously. Specifying the exception ERROR_MESSAGE is, however, not supported for method calls. 
  2. Note that, as of release 6.10, there are class-based exceptions that are caught with TRY ... CATCH ... ENDTRY, and replace the exceptions caught previously using EXCEPTIONS.

Example

CLASS C1 DEFINITION.
  PUBLIC SECTION.
    METHODS M1 EXCEPTIONS EX1
                          EX2.
ENDCLASS.

DATA O1 TYPE REF TO C1.

CREATE OBJECT O1.

O1->M1( EXCEPTIONS EX1 = 10
                   EX2 = 20 ).

CASE SY-SUBRC.
  WHEN 10.
    ...
  WHEN 20.
    ...
ENDCASE.

CLASS C1 IMPLEMENTATION.
  METHOD M1.
    ...
    RAISE EX1.
    ...
    MESSAGE E012(AT) RAISING EX2.
    ...
  ENDMETHOD.
ENDCLASS. 

The method M1 is called using variant 1b, while omitting the statement CALL METHOD

Variant 2

[CALL METHOD] meth( ).

Effect

This short form of variant 1b can be used for static method call if the method meth does not have any, or only optional, input parameters (IMPORTING-or CHANGING parameters). No values are passed. Possible EXPORTINGor RETURNING parameters are not accepted after completion of the method.

Example

See example for variant 4. 

Variant 3

[CALL METHOD] meth( f ).

Effect

This short form of variant 1b can be used for static method call in the following cases:

  • If the method meth has only one single non-optional input parameter (IMPORTING parameter), the system passes the actual parameter f with this variant of the method call to the non-optional input parameter.
  • If the method meth only has optional input parameters, of which one is declared as a preferred parameter using the addition PREFERRED PARAMETER, the actual parameter f can be passed to the preferred parameter using this variant of the method call. 

However, this method must not have any other interface parameters (EXPORTINGCHANGING, or RETURNINGparameters).

Example

See example for variant 4.

Variant 4

[CALL METHOD] meth( p1 = f1 ... pn = fn ).

Effect

This short form of variant 1b can be used for static method call if the method has several input parameters (IMPORTING parameters), whereby the actual parameters f1 ... fn are passed. The method must only have optional CHANGING parameters that are not filled during this call. Possible EXPORTING or RETURNING parameters are not accepted after completion of the method.

Example

class C1 definition.
  public section.
    methods: M0 importing P1 type I optional
                exporting P2 type I
                changing  P3 type I optional,
             M1 importing P1 type I,
             M2 importing P1 type I
                          P2 type I
                returning VALUE(P3) type I.
endclass.

class C1 implementation.
  method M0.
    ...
  endmethod.
  method M1.
    ...
  endmethod.
  method M2.
    ...
  endmethod.
endclass.

data: O1 type ref to C1,
      NUM1 type I,
      NUM2 type I.

start-of-selection.

  create object O1.

  O1->M0( ).

  O1->M1( NUM1 ).

  O1->M2( P1 = NUM1 P2 = NUM2 ).

This example shows short forms of variant 1b.

Note

If a method has an arbitrary number of IMPORTING parameters and a RETURNING parameter, it is a functional method, and then it can be called by CALL METHOD as well as by the following expressions: 

  • No IMPORTING parameters:

    meth( )
  • A non-optional IMPORTING parameter or several optional IMPORTING parameters with a preferred parameter:

    meth( f1 )
  • n IMPORTING parameters:

    meth( p1 = f1 ... pn = fn )

This notation style is currently possible 

  • For the source field of the MOVE statement. 
  • In arithmetic expressions of the COMPUTE statement. 
  • In logical expressions
  • In the CASE statement of the CASE control structure. 
  • In the WHEN statement of the CASE control structure. 
  • In the WHERE condition of the LOOP AT statement.

The functional method is entered instead of an operand. When the statement is executed, the system calls the method and the returned RETURNING parameter is used as an operand. 

Variant 5a

CALL METHOD ref->(f)   [additions].

Variant 5b

CALL METHOD class=>(f) [additions].

Variant 5c

CALL METHOD (c)=>meth  [additions].

Variant 5d

CALL METHOD (c)=>(f)   [additions].

Variant 5e

CALL METHOD [ME->](f)  [additions].

Extras:

Effect

Dynamic Method Call Call

The field f must contain the name of the called method at runtime. The object of an instance method is determined, as in the case of the static method call, via a reference variable. You can specify the class of a static method statically via class or dynamically as the content of the field c. Variant 5e is only possible for methods in your own class.

Additions 1 and 2 are used for dynamic parameter passing. Alternatively, you can also use additions 1 through 5 of the static method call, but in this case the interface of the called method must be statically known. If you use the dynamic method call, the statement CALL METHOD must not be omitted. 

Addition 1

... PARAMETER-TABLE itab 

Effect

This addition fills the interface of a dynamically called method with actual parameters. The addition PARAMETER-TABLE excludes simultaneous use of the static additions 1 thorugh 4 of variant 1. 

The parameter table itab must be a hashed table of the table type ABAP_PARMBIND_TAB or of the line type ABAP_PARMBIND. These types are defined in the ABAP type group in the ABAP dictionary. The table has three columns: 

  • NAME for the name of the formal parameter 
  • KIND for the type of parameter passing 
  • VALUE of the type REF TO DATA for the value of the actual parameter

The column NAME is the unique table key. Exactly one line of the internal table must be filled for each non-optional parameter, and one line CAN be filled for each optional parameter. 

The type of parameter passing is defined for each formal parameter in the declaration of the called method. The content of the column KIND can, therefore, be initial. If the type of parameter passing is to be checked at runtime, you can assign one of the following constants from the global class CL_ABAP_OBJECTDESCR to the column KIND. 

  • CL_ABAP_OBJECTDESCR=>EXPORTING for EXPORTING parameters 
  • CL_ABAP_OBJECTDESCR=>IMPORTING f¢r IMPORTING parameters 
  • CL_ABAP_OBJECTDESCR=>CHANGING f¢r CHANGING parameters 
  • CL_ABAP_OBJECTDESCR=>RECEIVING f¢r RECEIVING parameters

The descriptions depend on the caller's view. If the specified and actual parameter types do not match each other, the system generates the exception CX_SY_DYN_CALL_ILLEGAL_TYPE, which can be handled. As before, the entries in the column KIND can serve as an additional key, for example, to edit all the imported values after the method call. 

For the value of the actual parameter, the reference VALUE of the table line must point to a data object that contains the required value. For this purpose, you can use the command GET REFERENCEOF f INTO g.

Example

CLASS cl_abap_objectdescr DEFINITION LOAD .

CLASS c1 DEFINITION.
  PUBLIC SECTION.
  METHODS m1 IMPORTING p1 TYPE i.
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD m1.
    WRITE p1.
  ENDMETHOD.
ENDCLASS.

DATA r TYPE REF TO object.

DATA f(3) TYPE c VALUE 'M1'.

DATA number TYPE i VALUE 5.

DATA: ptab TYPE abap_parmbind_tab,
      ptab_line LIKE LINE OF ptab.

START-OF-SELECTION.

  ptab_line-name = 'P1'.
  ptab_line-kind = CL_ABAP_OBJECTDESCR=>EXPORTING.
  GET REFERENCE OF number INTO  ptab_line-value.
  INSERT ptab_line INTO TABLE ptab.
  IF sy-subrc ne 0.
    EXIT.
  ENDIF.

  CREATE OBJECT r TYPE c1.

  CALL METHOD r->(f) EXPORTING p1 = number.
  CALL METHOD r->(f) PARAMETER-TABLE ptab. 

Method m1 of the class c1 is called twice dynamically, whereby the parameter passing takes place once statically and once dynamically. The used reference variable is set for the type with reference to the general class OBJECT.

Addition 2

... EXCEPTION-TABLE itab 

Effect

With this addition, the exceptions of a dynamically called method are handled dynamically. The additionEXCEPTION-TABLE excludes simultaneous usage of the static addition 5, variant 1. 

The exception table itab must be a hashed table of the table type ABAP_EXCPBIND_TAB or of the line type ABAP_EXCPBIND. These types are defined in the ABAP type group in the ABAP dictionary. The table has two columns: 

  • NAME for the name of the exception 
  • VALUE of type I for the SY-SUBRC value to be assigned

The column NAME is the unique table key. For each exception, exactly one line of the internal table can be filled. Here the numeric value is assigned to the component VALUE, which should be in SY-SUBRC after the exception has been triggered.

Example

CLASS cl_abap_objectdescr DEFINITION LOAD.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
  METHODS m1 EXCEPTIONS exc.
ENDCLASS.

CLASS c1 IMPLEMENTATION.
  METHOD m1.
    RAISE exc.
  ENDMETHOD.
ENDCLASS.

DATA r TYPE REF TO object.

DATA f(3) TYPE c VALUE 'M1'.

DATA: etab TYPE abap_excpbind_tab,
      etab_line LIKE LINE OF etab.

START-OF-SELECTION.

  etab_line-name = 'EXC'.
  etab_line-value = 4.
  INSERT etab_line INTO TABLE etab.
  IF sy-subrc ne 0.
    EXIT.
  ENDIF.

  CREATE OBJECT r TYPE c1.

  CALL METHOD r->(f) EXCEPTIONS exc = 4.
  WRITE sy-subrc.
  CALL METHOD r->(f) EXCEPTION-TABLE etab.
  WRITE sy-subrc. 

The method m1 of the class c1 is called twice dynamically, whereby the exception handling takes place once statically and once dynamically. The user reference variable is set to the type with reference to the general classOBJECT

Exceptions

Catchable Exceptions

CX_SY_DYN_CALL_EXCP_NOT_FOUND

  • Cause: Exception does not exist
    Runtime Error: DYN_CALL_METH_EXCP_NOT_FOUND (catchable) 

CX_SY_DYN_CALL_ILLEGAL_CLASS

  • Cause: The specified class is abstract.
    Runtime Error: DYN_CALL_METH_CLASS_ABSTRACT (catchable) 
  • Cause: The specified class does not exist
    Runtime Error: DYN_CALL_METH_CLASS_NOT_FOUND (catchable) 

CX_SY_DYN_CALL_ILLEGAL_METHOD

  • Cause: The method cannot be accessed.
    Runtime Error: CALL_METHOD_NOT_ACCESSIBLE 
  • Cause: The called method is not yet implemented.
    Runtime Error: CALL_METHOD_NOT_IMPLEMENTED 
  • Cause: Call of static constructor
    Runtime Error: DYN_CALL_METH_CLASSCONSTRUCTOR (catchable) 
  • Cause: Call of instance constructor
    Runtime Error: DYN_CALL_METH_CONSTRUCTOR (catchable) 
  • Cause: Method does not exist
    Runtime Error: DYN_CALL_METH_NOT_FOUND (catchable) 
  • Cause: Method is not static
    Runtime Error: DYN_CALL_METH_NO_CLASS_METHOD (catchable) 
  • Cause: Call of a method that is not visible
    Runtime Error: DYN_CALL_METH_PRIVATE (catchable) 
  • Cause: Call of a method that is not visible
    Runtime Error: DYN_CALL_METH_PROTECTED (catchable) 

CX_SY_DYN_CALL_ILLEGAL_TYPE

  • Cause: Type conflict calling the method.
    Runtime Error: CALL_METHOD_CONFLICT_GEN_TYPE 
  • Cause: Type conflict calling the method.
    Runtime Error: CALL_METHOD_CONFLICT_TAB_TYPE 
  • Cause: Type conflict calling the method.
    Runtime Error: CALL_METHOD_CONFLICT_TYPE 
  • Cause: Incorrect type of a parameter
    Runtime Error: DYN_CALL_METH_PARAM_KIND (catchable) 
  • Cause: Actual parameter cannot be filled
    Runtime Error: DYN_CALL_METH_PARAM_LITL_MOVE (catchable) 
  • Cause: Incorrect table type of a parameter
    Runtime Error: DYN_CALL_METH_PARAM_TAB_TYPE (catchable) 
  • Cause: Incorrect type of a parameter
    Runtime Error: DYN_CALL_METH_PARAM_TYPE (catchable) 

CX_SY_DYN_CALL_PARAM_MISSING

  • Cause: Missing actual parameter
    Runtime Error: DYN_CALL_METH_PARAM_MISSING (catchable) 
  • Cause: Parameter reference is empty
    Runtime Error: DYN_CALL_METH_PARREF_INITIAL (catchable) 

CX_SY_DYN_CALL_PARAM_NOT_FOUND

  • Cause: Incorrect name of a parameter
    Runtime Error: DYN_CALL_METH_PARAM_NOT_FOUND (catchable) 

CX_SY_REF_IS_INITIAL

  • Cause: Reference variable is empty
    Runtime Error: DYN_CALL_METH_REF_IS_INITIAL (catchable)

Non-Catchable Exceptions

  • Cause: Non-allowed parameter during dynamic method call.
    Relevant for instance constructors during dynamic instantiation.
    Runtime Error: CALL_METHOD_PARMS_ILLEGAL

Related

ALIASESDeclaration of an alias name
CALL METHODCall of a method
CLASS ... ENDCLASSDefinition of a class
CLASS-DATADeclaration of a static attribute
CLASS-EVENTSDeclaration of a static event
CLASS-METHODSDeclaration of a static method
CREATE OBJECTCreation of an object
EVENTSDeclaration of an instance event
INTERFACE ... ENDINTERFACEDefinition of an interface
INTERFACESIncluding an interface
METHOD ... ENDMETHODDefinition of a method
METHODSDeclaration of an Instance method
PRIVATE SECTIONStart of private visibility section
PROTECTED SECTIONStart of a protected visibility section
PUBLIC SECTIONStart of the public visibility section
RAISE EVENTTriggering an event
SET HANDLERRegistering an event

ABAP creating table type


To define something like a[] as an class attribute is so trivial in other languages. In ABAP:


TYPES: city type spfli-cityfrom,
       spfli_type TYPE STANDARD TABLE OF spfli WITH DEFAULT KEY.

DATA: wa_city  TYPE city,
      wa_spfli TYPE spfli_type.

...
SELECT SINGLE cityfrom FROM spfli
                       INTO wa_city
                       WHERE carrid = 'LH' AND connid = '400'.

...
SELECT * FROM spfli INTO TABLE wa_spfli.

To create something like a[] where a is a class,

in "Local Types",

TYPES:  a_type type ref to class_a,
              a_list_type type STANDARD TABLE OF a_type.

Monday, August 27, 2012

Singleton Pattern in ABAP


Object Oriented Programming has been a boon to the programmers without which development of huge systems is almost impossible. ABAP is no exception to that which is why Object Oriented Programming was added to ABAP.

Without the use of Design Patterns, Object Oriented Programming is never going to give fruitful results. There are so many patterns that are proposed and being proposed. If you are not learning simple and common the Design Patterns, one day you will hit the dead end or you will spend time reinventing the wheel. To have a good knowledge in Design Patterns, I would suggest you to go with the Design Patterns: Elements of Reusable Object-Oriented Software by Gang of four. Here I would like to give an implementation of one such very common pattern.

Sometimes, we want some only one instance of an object to be present in the entire lifetime of the system. A security or authentication system, logging system or a database connection should be having more the one instance. In such cases, the Singleton Pattern comes to the rescue. Singleton Pattern does not mean to produce a single instance always; it can produce n number of instances where the n is constant.

Now I would like to share you an example of Singleton Pattern implemented in ABAP. Here a counter is made as a singleton object so that the counter can be incremented from anywhere and also making sure that only one counter exists.

A class which implements Singleton Pattern should have the following things other than the class’s own data members and methods,
            1. Private constructor(s)
            2. A private static member of the same type of the class.
            3. A static method which returns the only instance.

Counter class’s definition and implementation is as follows,

REPORT  ZFAR_SINGLETON.

class counter definition create private. "Rule 1

   public section.

     class-methods:
      get_counter returning value(obj) type ref to counter.  "Rule 3

     methods:
      increment,
      get_count returning value(cnt) type i.

   private section.
     class-data instance type ref to counter. "Rule 2
     data count type i.

endclass.

class counter implementation.

   method get_counter.
     if instance is initial.
       create object instance.
     endif.
     obj = instance.
   endmethod.

   method increment.
     add to count.
   endmethod.

   method get_count.
     cnt = count.
   endmethod.


endclass.

start-of-selection.

data: ctr1 type ref to counter,
       ctr2 type ref to counter,
       num1 type i,
       num2 type i.

ctr1 = counter=>get_counter( ).
ctr1->increment( ).
ctr2 = counter=>get_counter( ).
ctr2->increment( ).

num1 = ctr1->get_count( ).
num2 = ctr2->get_count( ).

write: num1, num2.

Since there is only one instance exists, both the references point to the same object and operates on the same object. Use Singleton Pattern whenever possible to ensure good design of the system.
[Author] Fareez Ahamed K.N.

Thursday, August 16, 2012

宅宅宅

宅宅宅主页 http://zhaizhaizhai.net

宅宅宅论坛 http://zhaizhaizhai.net/bbs

宅男,宅女,腐女,萝莉控,正太控,胖熊控.