Jeetu Alex - IT Software Professional specialized in developing high-end, customized business solutions using Coldfusion and Java.

Developer's blog
web knowledge base

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more...

Wednesday, May 3, 2017

Make Your CSS Dynamic

If you have been writing CSS for a while, you must have at some point in time felt the need for variables. CSS custom properties are somewhat like CSS’s own implementation of variables. However, when used properly, they can be so much more than just variables.

CSS custom properties allow you to:
  • Assign arbitrary values to a property with a name of your choice
  • Use the var() function to use these values in other properties

Although support for CSS custom properties is a bit of a rocky path at the moment, and some browsers support them under flags that need to be activated or set to true beforehand, their support is expected to increase dramatically moving forward, so it’s important to understand how to use and leverage them.

Fully-fledged CSS Variables

One of the main advantages of using CSS pre/postprocessors are is that they allow for values to be stored in a keyword and have them scoped to a certain selector if necessary.

After long being requested by developers, a draft for an interpretation of native variables for CSS was written. These are formally referred to as CSS custom properties, but are also sometimes referred to as CSS variables.

The current specification for native CSS custom properties covers all the same behaviors as pre/postprocessor variables. This enables you to store color codes, sizes with all of the known units, or just integers if needed (e.g., when a you need to use the same divisor or multiplier).

The syntax for CSS custom properties is a bit weird compared to other languages, but it makes a whole lot of sense if you compare their syntax with other features in the same CSS ecosystem:

:root { --color-black: #2e2e2e; }
.element { background: var(--color-black); }

Read more

Saturday, April 15, 2017

JavaScript Automation with Gulp

As web developers, we sometimes find ourselves repeating the same tedious tasks again and again. If you consider how much time is wasted by running a build command or hitting refresh on your browser, you will realize that you can be saving a lot of time. Additionally, by automating your processes, you can stay focused on the task at hand instead of temporarily leaving “the zone” (your state of productivity).

In this JavaScript automation tutorial, you will learn how to automate your design and development process with Gulp. If you are more design-oriented, I encourage you to overcome any fears you have and to read on. On the other hand, if you are a developer you will be able to sweep right through this once you understand the logic behind it.

Gulp is a build system that employs Node.js’s streams to implement an asynchronous source-destination approach to automation. Everything is written in JavaScript, so it is easy for anyone with intermediate coding knowledge to get started. A Gulp build process consists of a collection of watchers and tasks. Additionally, the community behind Gulp maintains a huge plugin directory within npm which helps accomplish any task from concatenating JavaScript to creating icon fonts from SVGs.

Alternatives to Gulp

There are plenty of alternatives out there, most of which have spawned in the past couple of years - the most notable one being Grunt. The contest between Gulp and Grunt will never have a clear winner, since they both have their pros and cons, hence I will avoid delving deep into that. In a nutshell, Grunt’s heavy reliance on config is what steers people towards Gulp’s JavaScript approach. In the meantime, native GUI implementations such as Koala have gained some ground, mostly from people that withhold getting into coding. However, with the bundled applications it’s impossible to reach the level of customizability and extendability that Gulp offers.

Process Automation Fundamentals

Plugins are the means through which gulp accomplishes each process. Plugins are installed through npm and initiated using “require”.

Tasks

For Gulp, tasks always have a source and a destination. In between them lie the pipes that call each plugin and output the transmuted results to the next pipe.

Globs

Globs are wildcard patterns that refer to files. Globs or arrays of globs are used as inputs in task source.

Watchers

The watchers watch the source files for changes and call tasks whenever a change is detected.

gulpfile.js

This is the JavaScript file that the “gulp” command points at. It contains everything from the tasks to the watchers or other pieces of code used by tasks.

Read more

Thursday, April 6, 2017

Slim PHP MVC Frameworks with a Layered Structure

Fat controllers and models: an inevitable problem for most large-scale projects based on MVC frameworks such as Yii and Laravel. The primary thing that fattens controllers and models is the Active Record, a powerful and essential component of such frameworks.


The Problem: Active Records and Its Violation of the SRP

The Active Record is an architectural pattern, an approach to accessing data in a database. It was named by Martin Fowler in his 2003 book Patterns of Enterprise Application Architecture and is widely used in PHP Frameworks.

Despite the fact that it is a very necessary approach, the Active Record (AR) pattern violates the Single Responsibility Principle (SRP) because AR models:

Deal with querying and data saving.

Know too much about the other models in the system (through relationships).
Are often directly involved in the application’s business logic (because the implementation of data storage is closely linked to said business logic).

This violation of the SRP is a good tradeoff for rapid development when you need to create an application prototype as soon as possible, but it is quite harmful when the application grows into a middle or a large-scale project. “God” models and fat controllers are difficult to test and maintain, and freely using models everywhere in controllers leads to tremendous difficulties when you inevitably have to change the database structure.

The solution is simple: divide the Active Record’s responsibility into several layers and inject cross-layer dependencies. This approach will also simplify testing because it allows you to mock those layers not currently being tested.

The Solution: A Layered Structure for PHP MVC Frameworks

There are five primary layers that we’ll cover:
  • The controller layer
  • The service layer
  • DTOs, a subset of the service layer
  • View decorators, a subset of the service layer
  • The repository layer

The Controller Layer

Modern MVC frameworks like Laravel and Yii take on many of the traditional controller challenges for you: Input validation and pre-filters are moved to another part of the application (In Laravel, it’s in what’s called middleware whereas, in Yii, it’s called behavior) while routing and HTTP verb rules are handled by the framework. This leaves a very narrow functionality for the programmer to code into a controller.

The essence of a controller is to get a request and deliver the results. A controller shouldn’t contain any application business logic; otherwise, it’s difficult to reuse code or change how the application communicates. If you need to create an API instead of rendering views, for example, and your controller doesn’t contain any logic, you just change the way you return your data and you’re good to go.

Tuesday, March 28, 2017

PHP Frameworks

Laravel

When speaking about Laravel, we are referring to Laravel version 4 and beyond. Laravel 4 was released in 2013 and represented a complete rewrite of the framework. The functionality of the framework was decoupled into separate components, which were managed with Composer, instead of everything being in one single huge code repository.

Laravel declares itself as a framework for rapid development with a simple and beautiful syntax which is easy to learn, read, and maintain. It is the most popular framework in 2016. According to Google trends, it is three times more popular than other frameworks, and on GitHub, it has two times more stars than competitors.

Symfony

Symfony 2 was released in 2011, but it must not be confused with Symfony 1, which was a totally different framework with different underlying principles. Fabien Potencier created Symfony 2, and the current version is 3.2, which is an incremental version of Symfony 2. Therefore, they are often called simply Symfony2/3.

Like Laravel 4, Symfony 2 is designed as a set of decoupled components. There are two benefits here: We can replace any component in a Symfony project, and we can take and use any Symfony component in a non-Symfony project. Symfony components can serve as great code examples and they are used in a lot of open source projects such as Drupal, phpBB, and Codeception. In fact, Laravel itself uses no less than 14 Symfony components. Understanding Symfony thus gives you many benefits when working with other projects.

See detailed comparisons in

  • Installation
  • Configurations
  • Routing and Controller
  • Template Engine
  • Dependency Injection
  • Object Relational Mapping (ORM)
  • REST API

And picking the Winner: Symfony or Laravel?

Friday, March 10, 2017

React, Redux and Immutable.js

React, Redux and Immutable.js are currently among the most popular JavaScript libraries and are rapidly becoming developers’ first choice when it comes to front-end development. In the few React/Redux projects that I have worked on, I realised that a lot of developers getting started with React do not fully understand React and how to write efficient code to utilise its full potential.
Some of the most common misuses of React and ways to avoid them.

Data Reference Problem
Any React app should mostly consist of small simple (or stateless function) components. They are simple to reason about and most of them can have shouldComponentUpdate function returning false.

shouldComponentUpdate(nextProps, nextState) { return false; }

Performance wise, the most important component lifecycle function is shouldComponentUpdate and if possible it should always return false. This ensures that this component will never re-render (except the initial render) effectively making the React app feel extremely fast.

Equality check for primitive data types like boolean, string and integer is very simple since they are always compared by their actual value:

1 === 1
’string’ === ’string’
true === true

On the other hand, equality check for complex types like objects, arrays and_functions_ is completely different. Two objects are the same if they have the same reference (pointing to the same object in memory).

const obj1 = { prop: ’someValue’ };
const obj2 = { prop: ’someValue’ };
console.log(obj1 === obj2);   // false

Even though obj1 and obj2 appear to be the same, their reference is different. Since they are different, comparing them naively within the shouldComponentUpdate function will cause our component re-render needlessly.

Handling References
This is not an easy task if we want to do it in a nice, clean, and performance optimised way. Facebook realised this problem a long time ago and called Immutable.js to the rescue.

import { Map } from ‘immutable’;

//  transform object into immutable map
let obj1 = Map({ prop: ’someValue’ });  
const obj2 = obj1;
console.log(obj1 === obj2);  // true

obj1 = obj1.set(‘prop’, ’someValue’);  // set same old value
console.log(obj1 === obj2);  // true | does not break reference because nothing has changed 

obj1 = obj1.set(‘prop’, ’someNewValue’);   // set new value
console.log(obj1 === obj2);  // false | breaks reference 
obj1 = obj1.set(...);.
See the full article here

How to get all possible combinations of elements in an array including order and lengths

Below is a recursive function which gives all possible unique combinations of elements in a array in all order and lengths.

Alternate 1

function getAllCombinations(arr) {
  var inputArray = arr;
  var resultArray = [];
  var combine = function() {
    var args = arguments;
    var temp = [];
    for (var i in args) {
      temp.push(inputArray[args[i]]);
    }
    if (temp.length > 0) {
      resultArray.push(temp);
    }
    for (i in inputArray) {
      temp = [];
      for (var j in args) {
        if (args[j] == i) {
          temp = false;
          break;
        } else {
          temp.push(args[j]);
        }
      }
      if (temp) {
        temp.push(i);
        combine.apply(null, temp);
      }
    }
    return resultArray;
  };
  return combine();
}
Alternate 2

function getAllCombinations(arr) {
  var inputArray = arr;
  var resultArray = [];
  var conditionNext = true;
  var combine = function() {
    var args = arguments;
    var temp = [];
    for (var i in args) {
      temp.push(inputArray[args[i]]);
    }
    if (temp.length > 0) {
      resultArray.push(temp);
    }
    for (i in inputArray) {
      conditionNext = true;
      if (args.length !== 0) {
        for (var j in args) {
          if (args[j] == i) {
            conditionNext = false;
          }
        }
      }
      if (conditionNext) {
        temp = [];
        for (j in args) {
          temp.push(args[j]);
        }
        temp.push(i);
        if (temp.length > 0) {
          combine.apply(null, temp);
        }
      }
    }
    return resultArray
  };
  return combine();
}

Alternate 3

function getAllCombinations(arr) {
  var inputArray = arr;
  var resultArray = [];

  var checkCondition = function(args, nextIndex) {
    if (args.length === 0) {
      return true;
    }
    for (var i = 0; i < args.length; i++) {
      if (args[i] == nextIndex) {
        return false;
      }
    }
    return true;
  };

  var applyFunc = function(args, index) {
    var temp = [];
    for (var i = 0; i < args.length; i++) {
      temp.push(args[i]);
    }
    temp.push(index);

    if (temp.length > 0) {
      v.apply(null, temp);
    }
  };

  var populateResult = function(args) {
    var temp = [];
    for (var i = 0; i < args.length; i++) {
      temp.push(inputArray[args[i]]);
    }
    if (temp.length > 0) {
      resultArray.push(temp);
    }
  };

  var v = function() {
    var args = arguments;
    populateResult(args);
    for (var i = 0; i < inputArray.length; i++) {
      if (checkCondition(args, i)) {
        applyFunc(args, i);
      }
    }
  };
  v();
  return resultArray;
}
See the complete solution discussion here

Friday, March 3, 2017

The Top 10 Most Common Mistakes That Java Developers Make

Java is a programming language that was initially developed for interactive television, but over time it has become widespread over everywhere software can be used. Designed with the notion of object-oriented programming, abolishing the complexities of other languages such as C or C++, garbage collection, and an architecturally agnostic virtual machine, Java created a new way of programming. Moreover, it has a gentle learning curve and appears to successfully adhere to its own moto - “Write once, run everywhere”, which is almost always true; but Java problems are still present. I’ll be addressing ten Java problems that I think are the most common mistakes.

Common Mistake #1: 

Neglecting Existing Libraries It's definitely a mistake for Java Developers to ignore the innumerable amount of libraries written in Java. Before reinventing the wheel, try to search for available libraries - many of them have been polished over the years of their existence and are free to use. These could be logging libraries, like log back and Log4j, or network related libraries,...

Common Mistake #2:

Missing the ‘break’ Keyword in a Switch-Case Block
These Java issues can be very embarrassing, and sometimes remain undiscovered until run in production. Fall-through behavior in switch statements is often useful; however, missing a “break” keyword when such behavior is not desired can lead to disastrous results. If you have forgotten to put a “break” in “case 0” in the code example below, the program will write “Zero” followed by “One”, since the control flow inside here will go through the entire “switch” statement until it reaches a “break”.

Common Mistake #3: Forgetting to Free Resources

Common Mistake #4: Memory Leaks

Common Mistake #5: Excessive Garbage Allocation

Common Mistake #6: Using Null References without Need

Common Mistake #7: Ignoring Exceptions

Common Mistake #9: Breaking Contracts

Common Mistake #10: Using Raw Type Instead of a Parameterized One

Tuesday, July 5, 2016

Collections & Threads in Java

package com.jeetu.app.util;

import java.util.*;

public class test {
    public static void main(String[] args) {

        List linkedList = new LinkedList();
        executeLogic(addContents(linkedList, "LinkedList"), displayContents(linkedList, "LinkedList")).start();

        List arrayList = new ArrayList();
        executeLogic(addContents(arrayList, "ArrayList"), displayContents(arrayList, "ArrayList")).start();

        Set hashSet = new HashSet();
        executeLogic(addContents(hashSet, "HashSet"), displayContents(hashSet, "HashSet")).start();

        Set treeSet = new TreeSet();
        executeLogic(addContents(treeSet, "TreeSet"), displayContents(treeSet, "TreeSet")).start();

    }

    static Thread executeLogic(final Thread t1, final Thread t2) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        t1.start();
                        t1.join();
                        t2.start();
                        break;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        return t;
    }

    static Thread addContents(final Collection e, final String type) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                long end;
                long start = System.currentTimeMillis();
                long limit = 5000000;
                for (int index = 1; index <= limit; index++) {
                    e.add(index);
                }
                end = System.currentTimeMillis();
                System.out.println("Write[" + type + "]: " + (end - start) + "  ms.");
            }
        });
        return t;
    }

    static Thread displayContents(final Collection e, final String type) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                long end;
                long start = System.currentTimeMillis();
                int total = 0;
                Iterator i = e.iterator();
                while (i.hasNext()) {
                    total = total + (Integer) i.next();
                }
                end = System.currentTimeMillis();
                System.out.println("Read[" + type + "]: " + (end - start) + " ms ,Total = " + total + ".");
            }
        });
        return t;
    }
}

Result:
Write[ArrayList]: 12997  ms.

Write[LinkedList]: 13144  ms.

Read[ArrayList]: 185 ms ,Total = 1647668640.

Read[LinkedList]: 69 ms ,Total = 1647668640.

Write[HashSet]: 29986  ms.

Read[HashSet]: 69 ms ,Total = 1647668640.

Write[TreeSet]: 38823  ms.

Read[TreeSet]: 67 ms ,Total = 1647668640.



Process finished with exit code 0

Saturday, June 18, 2016

JavaScript: Understanding the Weird Parts



Examples:

var p = {name: 'a', getName: function(){ return this.name;}}

function greet(p) {
    console.log(p.lastname);
}

console.log(p.getName());
greet(p);
greet({lastname:'mary'});



/*var a;

//a = 0;

if(a || a === 0) {
        console.log(a);
}*/


/*var b;
if((b = 2) * 2 === 4) {
    console.log(b);
}*/



/*function wait3mins() {
    var date = new Date().getTime() + 30000;
    while(new Date() < date) {
        
    }
    console.log("finished");
}

function clickHandler() {
    console.log("clicked");
}

document.addEventListener("click", clickHandler);

wait3mins();
console.log("final finished");*/




/*function a() {
    
    function b() {
        //var i;
        console.log(i);
    }
    
    var i = 10;
    console.log(i);
    b();
}

var i = 20;
console.log(i);
a();*/


/*function b() {
    //var i;
    console.log(i);
}

function a() {
    var i = 10;
    console.log(i);
    b();
}

var i = 20;
console.log(i);
a();*/

/*
var a = "hello";
function b() {
    
    console.log('hello jeetu');
    
}

b();
console.log(a);
*/

/*var a;

if (a === undefined) {
     console.log(a);
} else {
    console.log("defined");
}*/