Design Pattern Groups

The numbers of design patterns are less than English alphabets. Twenty-three design patterns are featured in the GoF design patterns book, falling within one of three subgroups: Creational, Structural, or Behavioral.

Creational

Creational patterns deal with object construction and referencing. They abstract away the responsibility of instantiating instances of objects from the client, thus keeping code loosely coupled and the responsibility of creating complex objects in one place adhering to the Single Responsibility and Separation of Concerns principles.

Following are the patterns in the Creational group:

➤➤ Abstract Factory: Provides an interface to create families of related objects.

➤➤ Factory: Enables a class to delegate the responsibility of creating a valid object.

➤➤ Builder: Enables various versions of an object to be constructed by separating the construction for the object itself.

➤➤ Prototype: Allows classes to be copied or cloned from a prototype instance rather than creating new instances.

➤➤ Singleton: Enables a class to be instantiated once with a single global point of access to it.

Structural

Structural patterns deal with the composition and relationships of objects to fulfill the needs of Larger systems.

Following are the patterns in the Structural group:

➤➤ Adapter: Enables classes of incompatible interfaces to be used together.

➤➤ Bridge: Separates an abstraction from its implementation, allowing implementations andabstractions to vary independently of one another.

➤➤ Composite: Allows a group of objects representing hierarchies to be treated in the same way as a single instance of an object.

➤➤ Decorator: Can dynamically surround a class and extend its behavior.

➤➤ Facade: Provides a simple interface and controls access to a series of complicated interfaces and subsystems.

➤➤ Flyweight: Provides a way to share data among many small classes in an efficient manner.

➤➤ Proxy: Provides a placeholder to a more complex class that is costly to instantiate.

Behavioral

Behavioral patterns deal with the communication between objects in terms of responsibility and algorithms. The patterns in this group encapsulate complex behavior and abstract it away from the flow of control of a system, thus enabling complex systems to be easily understood and maintained.

Following are the patterns in the Behavioral group:

➤➤ Chain of Responsibility: Allows commands to be chained together dynamically to handle arequest.

➤➤ Command: Encapsulates a method as an object and separates the execution of a command from its invoker.

➤➤ Interpreter: Specifies how to evaluate sentences in a language.

➤➤ Iterator: Provides a way to navigate a collection in a formalized manner.

➤➤ Mediator: Defines an object that allows communication between two other objects without them knowing about one another.

➤➤ Memento: Allows you to restore an object to its previous state.

➤➤ Observer: Defines the way one or more classes can be alerted to a change in another class.

➤➤ State: Allows an object to alter its behavior by delegating to a separate and changeable state object.

➤➤ Strategy: Enables an algorithm to be encapsulated within a class and switched at run time to alter an object’s behavior.

➤➤ Template Method: Defines the control of flow of an algorithm but allows subclasses to override or implement execution steps.

➤➤ Visitor: Enables new functionality to be performed on a class without affecting its structure.

Guidelines for Choosing and Applying Design Pattern

There are so many design patterns to choose from, so how do you identify which one is appropriate for your problem? To know which design pattern to use and how to apply the solution template to your specific problem, it’s important to understand these guidelines.

➤➤ Patterns can’t be applied without knowing about them. The first important step is to expand your knowledge and study patterns and principles both in the abstract and concrete form. You can implement a pattern in many ways. The more you see different implementations of patterns, the more you will understand the intent of the pattern and how a single pattern can have varying implementations.

➤➤ Do you need to introduce the complexity of a design pattern? It’s common for developers to try to use a pattern to solve every problem. You always need to weigh the upfront time needed to implement a pattern for the benefit that it’s going to give. Remember the KISS principle: Keep It Simple, Stupid.

➤➤ Generalize your problem; identify the issues you’re facing in a more abstract manner. Remember that design patterns are high-level solutions; try to abstract your problem, and don’t focus too hard on the details of your specific issue. Try to keep a list of intent of each pattern and principle in your implementation for reference.

➤➤ Look at patterns of a similar nature and patterns in the same group. Just because you have used a pattern before doesn’t mean it will always be the correct pattern choice when solving a problem.

➤➤ Look at what will likely change with your application and encapsulate what varies. If you know that a special offer discount algorithm will change over time, look for a pattern that will help you change it without impacting the rest of your application.

➤➤ After you have chosen a design pattern, ensure that you use the language of your pattern along with the language of the domain when naming the participants in a solution. For example, if you are using the strategy pattern to provide a solution for costing various shipping couriers, name them accordingly, such as USPSCostStrategy. By using the pattern’s common vocabulary along with the language of your domain, you will immediately make your code more readable and understandable to other developers with patterns knowledge.
When it comes to design patterns, there is no substitute for studying.  A great learning exercise is to try to identify patterns in the .NET Framework. For example, the ASP.NET Cache uses the Singleton pattern; creating a new Guid uses the Factory pattern; the .NET 2 XML classes use the Factory pattern.

Loading and re-loading jQuery Datatble with Ajax

Here is a full example, which you can copy into a html file and run for yourself, if you wish. It uses data from a dummy JSON provider, just for testing.

The HTML, showing the table and a button. The button is how I tested the ability to call a new URL and pass new request parameters to that new URL:

<div style="margin: 20px;">
    <button id="button_one" type="button">Resubmit</button>
    <br><br>
    <table id="example" class="display" style="width:100%"></table>
</div>

Here is the related script containing the DataTable definition and a function which calls the new URL (with new request parameters):

<script>

$(document).ready(function() {

  // ajax for initial table creation:
  var requestUrl = "https://jsonplaceholder.typicode.com/posts";
  var requestData = { "name": "Abel", "location": "here" };

  var table = $('#example').DataTable( {
    ajax: {
      method: "GET",
      url: requestUrl,
      "data": function ( ) {
        return requestData;
      },
      dataSrc: "",  
    },
    "columns": [
      { "title": "User ID", "data": "userId" },
      { "title": "ID", "data": "id" },
      { "title": "Title", "data": "title" }
    ]
            
  } );
  
  $("#button_one").click(function() {
    // subsequent ajax call, with button click:
    requestUrl = "https://jsonplaceholder.typicode.com/todos";
    requestData = { "name": "Charlie", "location": "there" };
    table.ajax.url( requestUrl ).load();
  });
  
} );

</script>

The key points in this example are:

  1. There are 2 different URLs. The first one is used when DataTables is created. The second one is used when the button is clicked.
  2. There are 2 different sets of request data, for the two URLs.

Using this approach, you can repeatedly call table.ajax.url( requestUrl ).load() with different URLs and different sets of request data, without needing to destroy the DataTable.

Handling Form Data

Here is a simple HTML form:

<form id="filter-form">
    City:<input type="text" id="city" name="city">
    Country:<input type="text" id="country" name="country">
    <input type="submit" value="Submit">
</form> 

For testing, I have the following JavaScript which captures the contents of the form into an array:

var form_data = [];

$( "#filter-form" ).submit(function( event ) {
  event.preventDefault();
  form_data = $( this ).serializeArray();
  table.ajax.url( url ).load();
});

The end result is data like this in the form_data variable:

[
  {
    "name": "city",
    "value": "Berlin"
  },
  {
    "name": "country",
    "value": "Germany"
  }
]

Now I can merge that data into the automatically created server-side request data. This is where I can choose to use the $.extend() function I mentioned above:

$('#example').DataTable( {
    serverSide: true,
    ajax: { 
      method: "POST",
      url: url, // from a variable
      data: function( d ) {
        return $.extend( {}, d, { "my_extra_data": form_data } );
      }
    },
    ... //whatever else is in your DataTable definition...
  });

This function results in request data like the following:

{
    "draw": "2",
    "columns[0][data]": "id",
    "columns[0][name]": "",
      ...
    "start": "0",
    "length": "10",
    "search[value]": "",
    "search[regex]": "false",
    "my_extra_data[0][name]": "city",
    "my_extra_data[0][value]": "Berlin",
    "my_extra_data[1][name]": "country",
    "my_extra_data[1][value]": "Germany"
}

You can see your my_extra_data values are included along with the server-side auto-generated request data. And all of this gets sent to the server as part of your request.

If you are using POST then it’s in the request body.

If you are using GET, then it’s the same data – but added to the URL as a query string.

In both cases, it’s converted to the standard string representation used by form data.

It’s then up to the server-side code to access this data in the usual way.

NOTE: You may have expected your URL-encoded form data to be provided as this:

...&city=Berlin&country=Germany

But instead it is provided as arrays of name/value pairs:

&my_extra_data%5B0%5D%5Bvalue%5D=Berlin&my_extra_data%5B1%5D%5Bname%5D=country&my_extra_data%5B1%5D%5Bvalue%5D=Germany

So, there is extra server-side work needed to parse this data.

If you want to convert your form data directly into a JavaScript object like this:

{ "city": "Berlin", "country", "Germany" }

then use this;

serializeArray already does exactly that. You just need to massage the data into your required format:

function objectifyForm(formArray) {
    //serialize data function
    var returnArray = {};
    for (var i = 0; i < formArray.length; i++){
        returnArray[formArray[i]['name']] = formArray[i]['value'];
    }
    return returnArray;
}

Watch out for hidden fields which have the same name as real inputs as they will get overwritten. For more info, take a look at the answers to this question:

Convert form data to JavaScript object with jQuery

Reference

https://stackoverflow.com/questions/66243388/how-to-reload-datatable-by-using-new-url-and-some-parameters-without-reinitializ

https://datatables.net/forums/discussion/61124/transfer-table-data-to-the-server-side

Javascript setTimeout

Sometimes you might want to delay the execution of your code.

You may need certain lines of code to execute at a point in the future, when you explicitly specify, rather than all the code executing synchronously.

Something like that is possible with JavaScript. The general syntax for the setTimeout() method looks like this:

setTimeout(function_name, time);

Let’s break it down:

  • setTimeout() is a method used for creating timing events. It accepts two required parameters.
  • function_name is the first required parameter. It is the name of a callback function that contains the code you want to execute. The name of the function acts as a reference and pointer to the function definition that contains the actual block of code.
  • time is the second required parameter, and it is defined in milliseconds (for reference, 1 second = 1000 milliseconds). It represents the specified amount of time the program has to wait for the function to be executed.

Here is an example;

function TranStatusCheck() { alert ('hi') }
$(function(){
    //run above method once after 1ms
    window.setTimeout(TranStatusCheck, 100);    //100ms (1000 ms = 1 sec)
});

Remember, not to write method this way;

window.setTimeout(TranStatusCheck(), 100);

Reference

https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

https://javascript.info/settimeout-setinterval

https://www.freecodecamp.org/news/javascript-wait-how-to-sleep-n-seconds-in-js-with-settimeout/

jQuery DataTable Column Selector

The best approach is to get the counts first and then try to get specific column;

var table = $('#example').DataTable();
 
var data = table
    .rows()
    .data();
 
alert( 'The table has '+data.length+' records' );

The DataTables columns() and column() (also optionally cells() and cell()) methods provide the ability to select columns from the table. Which columns are selected and how the selector actually operates is controlled by this column-selector data type.

var table = $('#example').DataTable( {
    columns: [
        { name: 'first-name' },
        { name: 'last-name' },
        { name: 'position' },
        { name: 'location' },
        { name: 'salary' }
    ]
} );
 
// Get salary column data
table.column( 'salary:name' ).data();

Reference

https://datatables.net/reference/type/column-selector

https://stackoverflow.com/questions/32598279/how-to-get-name-of-datatable-column

https://datatables.net/reference/api/columns().every()

https://datatables.net/reference/api/rows().data()