In this article, we are going to explore the classic specification pattern and implement it in order to compose the LINQ queries, and also non-LINQ queries. This article will also help beginners in understanding the specification pattern and how to implement it in practice. Major benefits of the specification patterns include reusability, maintainability, loose coupling of business rules from the business objects, readability and easy testing.

Specification Pattern

Specification pattern as per the definition from Wikipedia, is a particular software design pattern, wherebybusiness rules can be recombined by chaining the business rules together using boolean logic. To put it simply, business rules are segregated based on the Single responsibility principle (SRP) and chained or composed using boolean operands (AND, OR or NOT) to achieve the desired result. Each segregated business rule is called Specification.

Each specification inherits the abstract CompositeSpecification class which defines one abstractmethod called IsSatisfiedBy. This method is the engine of specification pattern. The responsibility of this method is to apply the business rule (specification) on the object in question and return a boolean result. The primary goal of the specification pattern is to select the subset of objects that satisfy a set of specifications chained together.


More infor:



Using SALV (object oriented model) has many advantages:

  • Simplified design: This Model uses a highly integrated object oriented design which provides the simplicity to programmers to develop the ALV.
  • Unified Object models: This model has only one main class which will get and set the parameters of entire layout.

All Classes has static method FACTORY which will get back the instance of the ALV. Like for the simple table dispaly we must call the method CL_SALV_TABLE=>FACTORY to get the instance of the ALV.

SALV class

SALV class


Simple case to display table:

DATA lo_salv TYPE REF TO cl_salv_table.
r_salv_table = lo_salv
t_table = lt_sflight ).
CATCH cx_salv_msg INTO lx_msg.

lo_salv->display( ).

Add standard PF Status

DATA: lo_functions TYPE REF TO cl_salv_functions_list.
lo_functions = co_salv->get_functions( ).
lo_functions->set_default( abap_true ).


A table is where data is stored. You always start with tables first, and then your usage pattern dictates whether you need views or materialized views.

A view is like a stored query for future use, if you’re frequently joining or filtering the same tables the same way in multiple places.

A materialized view is like a combination of both: it’s a table that is automatically populated and refreshed via a view. You’d use this if you were using views, and want to pre-join or pre-aggregate the rows to speed up queries.

materialized view

Figure below shows an example of using the Materialized View pattern. Data in the Order, OrderItem, and Customer tables in separate partitions in a Microsoft Azure storage account are combined to generate a view containing the total sales value for each product in the Electronics category, together with a count of the number of customers who made purchases of each item.

materialized view2

Materialised View:Materialized views are schema objects that can be used to summarize, precompute, replicate, and distribute data.It  provides indirect access to table data by storing the results of a query in a separate schema object. Unlike an ordinary view, which does not take up any storage space or contain any data.

Senario:While creating a dataware house we need to go for staging part at that time this is useful.


We have 2 types

1)Read only


An updatable view lets you insert, update, and delete rows in the view and propagate the changes to the target master table.


In order to be updatable, a view cannot contain any of the following constructs:

SET or DISTINCT operators, an aggregate or analytic function, a GROUP BY, ORDER BY, CONNECT BY, or START WITH clause, a subquery (or collection expression) in a SELECT list

or finally (with some exceptions) a JOIN


Views that are not updatable can be modified using an INSTEAD OF trigger.






Visitor Design Pattern


  • Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
  • The classic technique for recovering lost type information.
  • Do the right thing based on the type of two objects.
  • Double dispatch


Many distinct and unrelated operations need to be performed on node objects in a heterogeneous aggregate structure. You want to avoid “polluting” the node classes with these operations. And, you don’t want to have to query the type of each node and cast the pointer to the correct type before performing the desired operation.


Visitor’s primary purpose is to abstract functionality that can be applied to an aggregate hierarchy of “element” objects. The approach encourages designing lightweight Element classes – because processing functionality is removed from their list of responsibilities. New functionality can easily be added to the original inheritance hierarchy by creating a new Visitor subclass.

Visitor implements “double dispatch”. OO messages routinely manifest “single dispatch” – the operation that is executed depends on: the name of the request, and the type of the receiver. In “double dispatch”, the operation executed depends on: the name of the request, and the type of TWO receivers (the type of the Visitor and the type of the element it visits).

The implementation proceeds as follows. Create a Visitor class hierarchy that defines a pure virtualvisit() method in the abstract base class for each concrete derived class in the aggregate node hierarchy. Each visit() method accepts a single argument – a pointer or reference to an original Element derived class.

Each operation to be supported is modelled with a concrete derived class of the Visitor hierarchy. Thevisit() methods declared in the Visitor base class are now defined in each derived subclass by allocating the “type query and cast” code in the original implementation to the appropriate overloadedvisit() method.

Add a single pure virtual accept() method to the base class of the Element hierarchy. accept() is defined to receive a single argument – a pointer or reference to the abstract base class of the Visitor hierarchy.

Each concrete derived class of the Element hierarchy implements the accept() method by simply calling the visit() method on the concrete derived instance of the Visitor hierarchy that it was passed, passing its “this” pointer as the sole argument.

Everything for “elements” and “visitors” is now set-up. When the client needs an operation to be performed, (s)he creates an instance of the Vistor object, calls the accept() method on each Element object, and passes the Visitor object.

The accept() method causes flow of control to find the correct Element subclass. Then when thevisit() method is invoked, flow of control is vectored to the correct Visitor subclass. accept()dispatch plus visit() dispatch equals double dispatch.

The Visitor pattern makes adding new operations (or utilities) easy – simply add a new Visitor derived class. But, if the subclasses in the aggregate node hierarchy are not stable, keeping the Visitor subclasses in sync requires a prohibitive amount of effort.

An acknowledged objection to the Visitor pattern is that is represents a regression to functional decomposition – separate the algorithms from the data structures. While this is a legitimate interpretation, perhaps a better perspective/rationale is the goal of promoting non-traditional behavior to full object status.


The Element hierarchy is instrumented with a “universal method adapter”. The implementation ofaccept() in each Element derived class is always the same. But – it cannot be moved to the Element base class and inherited by all derived classes because a reference to this in the Element class always maps to the base type Element.

Visitor scheme

When the polymorphic firstDispatch() method is called on an abstract First object, the concrete type of that object is “recovered”. When the polymorphic secondDispatch() method is called on an abstract Second object, its concrete type is “recovered”. The application functionality appropriate for this pair of types can now be exercised.

Visitor scheme


The Visitor pattern represents an operation to be performed on the elements of an object structure without changing the classes on which it operates. This pattern can be observed in the operation of a taxi company. When a person calls a taxi company (accepting a visitor), the company dispatches a cab to the customer. Upon entering the taxi the customer, or Visitor, is no longer in control of his or her own transportation, the taxi (driver) is.

Visitor example

Check list

  1. Confirm that the current hierarchy (known as the Element hierarchy) will be fairly stable and that the public interface of these classes is sufficient for the access the Visitor classes will require. If these conditions are not met, then the Visitor pattern is not a good match.
  2. Create a Visitor base class with a visit(ElementXxx) method for each Element derived type.
  3. Add an accept(Visitor) method to the Element hierarchy. The implementation in each Element derived class is always the same – accept( Visitor v ) { v.visit( this ); }. Because of cyclic dependencies, the declaration of the Element and Visitor classes will need to be interleaved.
  4. The Element hierarchy is coupled only to the Visitor base class, but the Visitor hierarchy is coupled to each Element derived class. If the stability of the Element hierarchy is low, and the stability of the Visitor hierarchy is high; consider swapping the ‘roles’ of the two hierarchies.
  5. Create a Visitor derived class for each “operation” to be performed on Element objects. visit()implementations will rely on the Element’s public interface.
  6. The client creates Visitor objects and passes each to Element objects by calling accept().

Rules of thumb

  • The abstract syntax tree of Interpreter is a Composite (therefore Iterator and Visitor are also applicable).
  • Iterator can traverse a Composite. Visitor can apply an operation over a Composite.
  • The Visitor pattern is like a more powerful Command pattern because the visitor may initiate whatever is appropriate for the kind of object it encounters.
  • The Visitor pattern is the classic technique for recovering lost type information without resorting to dynamic casts.


The November 2000 issue of JavaPro has an article by James Cooper (author of a Java companion to the GoF) on the Visitor design pattern. He suggests it “turns the tables on our object-oriented model and creates an external class to act on data in other classes … while this may seem unclean … there are good reasons for doing it.”

His primary example. Suppose you have a hierarchy of Employee-Engineer-Boss. They all enjoy a normal vacation day accrual policy, but, Bosses also participate in a “bonus” vacation day program. As a result, the interface of class Boss is different than that of class Engineer. We cannot polymorphically traverse a Composite-like organization and compute a total of the organization’s remaining vacation days. “The Visitor becomes more useful when there are several classes with different interfaces and we want to encapsulate how we get data from these classes.”

His benefits for Visitor include:

  • Add functions to class libraries for which you either do not have the source or cannot change the source
  • Obtain data from a disparate collection of unrelated classes and use it to present the results of a global calculation to the user program
  • Gather related operations into a single class rather than force you to change or derive classes to add these operations
  • Collaborate with the Composite pattern

Visitor is not good for the situation where “visited” classes are not stable. Every time a new Composite hierarchy derived class is added, every Visitor derived class must be amended.

Shortcut What it does
Ctrl + D Duplicate any line.
Ctrl + U Selected text converted into uppercase..
Ctrl + L Selected text converted into lowercase..
Ctrl + J Selected text will become capitalize.
Ctrl + O Goto a particular line in the program.
Ctrl+Alt+T Swaps current line with the Upper Line.
Ctrl+Shift+L Deletes the whole line

Otherway, we can created a new shortcut for selected command via using Keyboard option as the following picture

KeyBoard Options

KeyBoard Options

If you want to save your keyboard and import into new PC, you can do the following steps.

Checking SAP folder “C:\Users\XXXX\AppData\Roaming\SAP\SAP GUI\ABAP Editor”, you will found a folder named SAP GUI and in this folder, select find keymap.xml this is Keyboard mapping file, you can use this to import when having new computer.

Hope that help!

D3.js is a javascript library for manipulating DOM objects  based on data. we can create rich visualizations of data.

D3 provides a number of modules for helping us code many of thing that we need to create interactive data. Such as: Shapes, Scales, Layouts, Behaviors, Data-processing(JSON, CSV)

Simple case:"body").selectAll("p")
.data([4, 8])
.text(function(d) { return d + " squared is " + d*d + "!"; });

var jsonCircles = [
    "x_axis": 30,
    "y_axis": 30,
    "radius": 20,
    "color" : "green"
   }, {
    "x_axis": 70,
    "y_axis": 70,
   "radius": 20,
   "color" : "purple"
var svgContainer ="body").append("svg")
                                    .attr("width", 200)
                                    .attr("height", 200);

var circles = svgContainer.selectAll("circle")
Loading data from JSON file and using D3.js to visualization data

Loading data from JSON file and using D3.js to visualization data






Grouping Form Data with <fieldset>

The <fieldset> element groups related data in a form.

The <legend> element defines a caption for the <fieldset> element.


<form action=”action_page.php”>
<legend>Personal information:</legend>
First name:<br>
<input type=”text” name=”firstname” value=”Mickey”><br>
Last name:<br>
<input type=”text” name=”lastname” value=”Mouse”><br><br>
<input type=”submit” value=”Submit”>


Attribute Description
accept-charset Specifies the charset used in the submitted form (default: the page charset).
action Specifies an address (url) where to submit the form (default: the submitting page).
autocomplete Specifies if the browser should autocomplete the form (default: on).
enctype Specifies the encoding of the submitted data (default: is url-encoded).
method Specifies the HTTP method used when submitting the form (default: GET).
name Specifies a name used to identify the form (for DOM usage:
novalidate Specifies that the browser should not validate the form.
target Specifies the target of the address in the action attribute (default: _self).


Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Method Description
element.innerHTML =  new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element = new style Change the style of an HTML element

Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream

Adding Events Handlers

Method Description
document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event


<p id=”p1″>Hello World!</p>

document.getElementById(“p1”).innerHTML = “New text!”;



jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to “query (or find)” HTML elements
  • A jQuery action() to be performed on the element(s)


$(this).hide() – hides the current element.

$(“p”).hide() – hides all <p> elements.

$(“.test”).hide() – hides all elements with class=”test”.

$(“#test”).hide() – hides the element with id=”test”.

Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload

JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, arrays, objects and more:

var length = 16;                               // Number
var lastName = “Johnson”;                      // String
var cars = [“Saab”, “Volvo”, “BMW”];           // Array

// var cars = new Array(“Saab”, “Volvo”, “BMW”);
var x = {firstName:”John”, lastName:”Doe”};    // Object

function name(parameter1, parameter2, parameter3) {
code to be executed

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
document.getElementById(“demo”).innerHTML = toCelsius(77);









Object Properties Methods

Auto object

Auto object = Fiatcar.model = 500

car.weight = 850kg

car.color = white





var person = {

fullName : function() {

return this.firstName + ” ” + this.lastName;



Common HTML Events

Here is a list of some common HTML events:

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

<button onclick=”this.innerHTML=Date()”>The time is?</button>


Array Properties

Property Description
constructor Returns the function that created the Array object’s prototype
length Sets or returns the number of elements in an array
prototype Allows you to add properties and methods to an Array object

Array Methods

Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
copyWithin() Copies array elements within the array, to and from specified positions
every() Checks if every element in an array pass a test
fill() Fill the elements in an array with a static value
filter() Creates a new array with every element in an array that pass a test
find() Returns the value of the first element in an array that pass a test
findIndex() Returns the index of the first element in an array that pass a test
forEach() Calls a function for each array element
indexOf() Search the array for an element and returns its position
isArray() Checks whether an object is an array
join() Joins all elements of an array into a string
lastIndexOf() Search the array for an element, starting at the end, and returns its position
map() Creates a new array with the result of calling a function for each array element
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reduce() Reduce the values of an array to a single value (going left-to-right)
reduceRight() Reduce the values of an array to a single value (going right-to-left)
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
some() Checks if any of the elements in an array pass a test
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the new length
valueOf() Returns the primitive value of an array



JavaScript Performance

Reduce Activity in Loops

Loops are often used in programming.

Each statement in a loop, including the for statement, is executed for each iteration of the loop.

Search for statements or assignments that can be placed outside the loop.

Bad Code:

for (i = 0; i < arr.length; i++) {

Better Code:

l = arr.length;
for (i = 0; i < l; i++)


Avoid Unnecessary Variables

Don’t create new variables if you don’t plan to save values.

Often you can replace code like this:

var fullName = firstName + ” ” + lastName;
document.getElementById(“demo”).innerHTML = fullName;

With this:

document.getElementById(“demo”).innerHTML = firstName + ” ” + lastName


Key-range locks protect a range of rows implicitly included in a record set being read by a Transact-SQL statement while using the serializable transaction isolation level. The serializable isolation level requires that any query executed during a transaction must obtain the same set of rows every time it is executed during the transaction. A key range lock protects this requirement by preventing other transactions from inserting new rows whose keys would fall in the range of keys read by the serializable transaction.

Key-range locking prevents phantom reads. By protecting the ranges of keys between rows, it also prevents phantom insertions into a set of records accessed by a transaction.

A key-range lock is placed on an index, specifying a beginning and ending key value. This lock blocks any attempt to insert, update, or delete any row with a key value that falls in the range because those operations would first have to acquire a lock on the index. For example, a serializable transaction could issue a SELECT statement that reads all rows whose key values are between AAA and CZZ. A key-range lock on the key values in the range from AAA to CZZ prevents other transactions from inserting rows with key values anywhere in that range, such as ADG, BBD, or CAL.


Xây dựng event store với chỉ duy nhất một bảng mà vẫn đảm bảo giải quyết vấn đề concurrency ok 😡

Phatom row là hiện tượng khi bạn select dữ liệu ra, thì trong lúc đó có row mới được insert vào database. Có nhiều chế độ lock khác nhau, nhưng hầu hết các chế độ lock đó sẽ không lock việc tranh chấp việc insert. Nếu bạn lock cả table thì hiệu năng sẽ rất kém. Key Range Locking cho phép bạn lock một nhóm các row có cùng id. Mà không lock các khoảng key range khác.

Trong việc build event store, thì việc sử dụng lock key range sẽ vô cùng hiệu quả. Vì cá event của một object sẽ cùng một key. Do đó chỉ việc lock nhóm key đó là có thể giải quyết vấn đề concurrency ngon lành.

Reference: fb nghia

57 engineers to serve 1 billion users, amazing!!!. Startup life is always crazy and full of surprises, still so much things to learn!

A Fulfillment Service is a third party warehouse that prepares and ships orders on behalf of the store owner. Fulfillment services charge a fee to package and ship items and update product inventory levels. Some well known fulfillment services with Shopify integrations include: Amazon, Shipwire, and Webgistix

Full source: link