Archive for July 27, 2011

Events in Object Oriented ABAP (OO ABAP)

What are Events in OO ABAP?

Events allow objects to publish status or some information about itself. Other object can respond to that change using this.

Event thus serve as an action items using which object of different types can interact with each other on specific occasions/ actions.

What are different types of Event?

There are two types of events

1. Static: Static events can be raised without need of creating object instance and can be raised stand alone without any instance. Static instance could be raised only from Static method.

2. Instance Dependent: Instance dependent events are always specific to an object instance. Therefore they need an object instance to raise them.

How to trigger Events?                                                  

Events in SAP follow a typical “Broadcast” scenario similar to a news station.

“An Entity publishes events in its newsletter for everyone and anyone who wants to read it then needs to subscribe for a copy of that newsletter.”

Similarly, Event are published in the class definition and different objects then subscribe to those events depending on needs.

For e.g. Class CL_GUI_ALV_GRID for ALV Grid has published event like USER_COMMAND, DOUBLE_CLICK and ONDRAG etc which could be used by other objects (programs to subscribe and use).

Any method of class can raise its events.

Steps Followed in Event Mechanism

1. Define Event: Event would be defined at the time of class declaration. When using standard SAP class, this is need not required generally. However for custom classes you can define events.       

2. Raise Event: Events can be raised by any method of class. This is to be done using ABAP statement

 Method EventRaisingMethod.
     RAISE event.
 ENDMETHOD.

3. Define Handler Class: Handler class is the one which is responsible for taking action on the events subscribed by other object. It could include events of different object types (classes). Handler class can group handler methods of different events from one/ many classes  

 CLASS handler_class DEFINITION.
  PUBLIC SECTION.
  METHODS: handler_method
           FOR EVENT raised_event
           OF raising_class.
 ENDCLASS.

4. Define Handler Method: Handler Methods are the one which describe the action to be performed when the event is raised.

 CLASS handler_class IMPLEMENTATION.
  METHOD handler_method.
    "… some logics here
  ENDMETHOD.
 ENDCLASS.

5. Register Event Handler: This would mean subscribing to the event of a particular class.

 SET HANDLER handler_instance-handler_method
        FOR ALL INSTANCES.
 SET HANDLER handler_instance-handler_method
         FOR handled_instance.

How events works in SAP?

When an event is fired then the event handlers that have registered themselves with SET HANDLER statement are executed by runtime.

The 5 steps are implemented uniformly across different usages of Object oriented programming in sap. The best example could be CL_GUI_ALV_GRID and its associated events which are commonly used.

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

Factory Method design pattern in Java

The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The creation of an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

Factory pattern comes into creational design pattern category, the main objective of the creational pattern is to instantiate an object and in Factory Pattern an interface is responsible for creating the object but the sub classes decides which class to instantiate. It is like the interface instantiate the appropriate sub-class depending upon the data passed. Here in this article we will understand how we can create an Factory Pattern in Java

The essence of the Factory method Pattern is to “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses

Use the factory pattern when:

  • The creation of the object precludes reuse without significantly duplicating code.
  • The creation of the object requires access to information or resources not appropriate to contain within the composing object.
  • The lifetime management of created objects needs to be centralised to ensure consistent behavior.

printSomething.java

1
2
3
4
5
6
package techartifact.pattern.factory;
public abstract class printSomething {
public abstract void printTech();
}

Now we will have the concrete implementations of the printSomething class, JavaTech and J2eeTech, each providing a much simplified implementation for the printTech() method.

JavaTech.java

 
1
2
3
4
5
6
7
8
package techartifact.pattern.factory;
public class JavaTech extends printSomething {
@Override
 public void printTech()
 {
 System.out.println("this is java technology");
 }

We will having one more class for j2eeTech for j2ee technology.

J2eeTech.java


1
2
3
4
5
6
7
8
package techartifact.pattern.factory;
public class J2eeTech extends printSomething {
 public void printTech()
 {
     System.out.println("this is j2ee technology");
 }
}

Now let us come to the core implementation, the Factory class itself. The PrintFactory class has one static method called showPrint() which the clients can invoke to get the printSomething object. Note the return type of the method, it is neither JavaTech nor J2eeTech, but the super type of the both, i.e, printSomething. Whether the return type of method is JavaTech or J2eeTech is decided based on the input operating system.

PrintFactory.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package techartifact.pattern.factory;
public class PrintFactory {
public static Button showPrint(String os){
   if (os.equals("Java"))
  {
        return new JavaTech();
  }
   else if (os.equals("J2ee"))
  {
    return new J2eeTech();
  }
return null
 }
}

In this we can makes use of the above PrintFactory class. The client is un-aware of the fact there is multiple implementations of the printSomething class. It accesses the printTech() operation through a single unified type printSomething.

FactoryClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package techartifact.pattern.factory;
public class FactoryClient {
  public static void main(String[] args) {
             printSomething psJava =PrintFactory.showPrint("Java");
             psJava.printTech();
             printSomething psJ2ee = PrintFactory.showPrint("j2ee");
             psJ2ee.printTech();
   }

Pin it

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

Some SQL tips/(interview) questions

Below are some of the tips for SQL query optimizations in the form of question/answers.

1. Which of the following query is the most optimized?
a. SELECT column_name FROM table_name WHERE LOWER(column_name) = ‘name’.
b. SELECT column_name FROM table_name WHERE column_name = ‘NAME’ or column_name = ‘name’.
c. SELECT * FROM table_name WHERE LOWER(column_name) = ‘name’
d. SELECT * FROM table_name WHERE column_name = ‘NAME’ or column_name = ‘name’.

Answer: B.
Reason: We should specify the columns in the Select queries and avoid functions like UPPER, LOWER etc as far as possible.

2. Which of the following query generally prevents (but not always) the query optimizer from using an index to perform a search?
a. SELECT member_number, first_name, last_name FROM members WHERE firstname like ‘m%’
b. SELECT member_number, first_name, last_name FROM members WHERE dateofbirth < DATEADD(yy,-21,GETDATE())
c. SELECT member_number, first_name, last_name FROM members WHERE DATEDIFF(yy,datofbirth,GETDATE()) > 21
d. All of these

Answer: C
Reason: Column name is mixed within a function. Hence index cannot be used by optimizer.

3. When we use “NOT IN” our SQL queries, the query optimizer uses which technique to perform the activity?
a. Indexing
b. Clustered Indexed scan
c. Nested table scan
d. None of these

Answer: C

4. Which of the following is the best way of inserting a binary image into database?
a. Use Insert statement
b. Use Stored procedure
c. Both give same performance
d. None of these

Answer: B
Reason: The reason for this is because the application must first convert the binary value into a character string (which doubles its size, thus increasing network traffic and taking more time) before it can be sent to the server. And when the server receives the character string, it then has to convert it back to the binary format (taking even more time).

5. SELECT INTO option locks the system tables. True or false?
Answer: True

6. Using which among “Derived table” and “Temporary table” can we reduce I/O and boost our application’s performance?
Answer: Derived table
Reason: A derived table is the result of using a SELECT statement in the FROM clause of an existing SELECT statement. By using derived tables instead of temporary tables, we can reduce I/O and boost our application’s performance.

7. Which of the following query is the best one in performance to verify the existence of a record in a table:
a. SELECT COUNT(*) FROM table_name WHERE column_name = ‘xxx’
b. IF EXISTS (SELECT * FROM table_name WHERE column_name = ‘xxx’)
c. Both give same performance

Answer: B
Reason: don’t use SELECT COUNT(*) in your Transact-SQL code to identify it, which is very inefficient and wastes server resources.

8. Which of the following is NOT recommended for UPDATE queries in order to reduce the amount of resources required to perform the query:
a. Try not to change the value of a column that is also the primary key.
b. Try to update a column that has a reference in the WHERE clause to the column being updated whenever possible
c. Try to avoid updating heavily indexed columns.
d. When updating VARCHAR columns, try to replace the contents with contents of the same length.

Answer: B
Reason: All points except “B” are recommended points for UPDATE queries. Instead we should try not to update a column that has a reference in the WHERE clause to the column being updated.

9. Omitting of which clause (if possible) can decrease the possibility that a sort operation will occur:
a. DISTINCT
b. ORDER BY
c. LIKE
d. Both A and B

Answer: D

10. Which of the following query will be better in performance?
a. SELECT * FROM Orders WHERE OrderID*3 = 33000
b. SELECT * FROM Orders WHERE OrderID = 33000/3
c. Both are same in terms of performance as well.

Answer: B
Reason: We should avoid computation on columns as far as possible and hence we will get an index scan instead of a seek.

Also read Microsoft dotnet interview questions

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

Introduction to JSON (Javascript Object Notation)

What is JSON?
JSON (Javascript Object Notation) is a light weight data interchange format. JSON is a subset of the literal object notation in JavaScript. It can be compared to XML but parsing of JSON is very much easier than XML data. It is a text format of data and is programming language independent. In fact it very much looks like unnamed array.

Example of data in JSON
Shown below is a object declared in JSON format.

var individual = {
     "firstName": "Anky",
     "lastName": "Singh",
     "address": {
                       "streetAddress": "4th Avenue",
                       "city": "Moorpark",
                       "state": "CA",
                       "postalCode": 34523
                    },
     "phoneNumbers": [
                                 "212 555-1234",
                                 "646 555-4567"
                             ]
 };

alert("The name of Individual is " + individual.firstName + " " +  individual.lastName);
alert("The Street Address is " + individual.address.streetAddress);
alert("The Postal code is " + individual.address.postalCode);
alert("First Phone Number  is " + individual.phoneNumbers[0]);
alert("Second Phone Number  is " + individual.phoneNumbers[1]);

<em>Output would be alert windows with following messages</em>:
The name of Individual is Anky Singh
The Street Address is 4th Avenue
The Postal code is 34523
First Phone Number  is 212 555-1234
Second Phone Number  is 646 555-4567

Above code shows how an Individual object is declared using JSON. Alert statements provide an example how the properties of the object can be accessed in the same way as we do in C# or Java.

Being subset of literal notation JSON standard has got stricter rules. See www.json.org or RFC 4627 for a more formal description of the standard.

But all said simplicity of JSON data is the specialty of the standard.

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare

What is MVVM pattern in WPF

The Model View ViewModel (MVVM) is an architectural pattern used in software engineering that originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler. Largely based on the Model-view-controller pattern (MVC), MVVM is targeted at modern UI development platforms (Windows Presentation Foundation and Silverlight) in which there is a UX developer who has different requirements than a more “traditional” developer (i.e. oriented toward business logic and back end development).

Model
The Model is defined as in MVC; it is the data or business logic, completely UI independent, that stores the state and does the processing of the problem domain. The Model is written in code or is represented by pure data encoded in relational tables or XML.

View
A View is defined in XAML and should not have any logic in the code-behind. It binds to the view-model by only using data binding.
In simple examples, the View is data bound directly to the Model. Parts of the Model are simply displayed in the view by one-way data binding. Other parts of the model can be edited by directly binding controls two-way to the data.

ViewModel
The term means “Model of a View”, and can be thought of as abstraction of the view, but it also provides a specialization of the Model that the View can use for data-binding. In this latter role the ViewModel contains data-transformers that convert Model types into View types, and it contains Commands the View can use to interact with the Model.
The ViewModel exposes public properties, commands, and abstractions. The ViewModel has been likened to a conceptual state of the data as opposed to the real state of the data in the Model.

References
Wikepedia
Tales from the Smart Client
Model-View-ViewModel Pattern

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare