Tech Rocks

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... contact@tech-rocks.org

Monday, June 19, 2017

JavaScript more than meets the eye

JavaScript can seem like a very easy language to learn at first. Perhaps it’s because of its flexible syntax. Or perhaps it’s because of its similarity to other well known languages like Java. Or perhaps it’s because it has so few data types in comparison to languages like Java, Ruby, or .NET.

But in truth, JavaScript is much less simplistic and more nuanced than most developers initially realize. Even for developers with more experience, some of JavaScript’s most salient features continue to be misunderstood and lead to confusion. One such feature is the way that data (property and variable) lookups are performed and the JavaScript performance ramifications to be aware of.

In JavaScript, data lookups are governed by two things: prototypal inheritance and scope chain. As a developer, clearly understanding these two mechanisms is essential, since doing so can improve the structure, and often the performance, of your code.

  • Property lookups through the prototype chain 
  • Variable lookups through the scope chain 
  • JavaScript Performance Ramifications

Read more

Buggy JavaScript Code

Today, JavaScript is at the core of virtually all modern web applications. The past several years in particular have witnessed the proliferation of a wide array of powerful JavaScript-based libraries and frameworks for single page application (SPA) development, graphics and animation, and even server-side JavaScript platforms. JavaScript has truly become ubiquitous in the world of web app development and is therefore an increasingly important skill to master.

At first blush, JavaScript may seem quite simple. And indeed, to build basic JavaScript functionality into a web page is a fairly straightforward task for any experienced software developer, even if they’re new to JavaScript. Yet the language is significantly more nuanced, powerful, and complex than one would initially be lead to believe. Indeed, many of JavaScript’s subtleties lead to a number of common problems that keep it from working – 10 of which we discuss here – that are important to be aware of and avoid in one’s quest to become a master JavaScript developer.


  • Common Mistake #1: Incorrect references to this
  • Common Mistake #2: Thinking there is block-level scope
  • Common Mistake #3: Creating memory leaks
  • Common Mistake #4: Confusion about equality
  • Common Mistake #5: Inefficient DOM manipulation
  • Common Mistake #6: Incorrect use of function definitions inside for loops
  • Common Mistake #7: Failure to properly leverage prototypal inheritance
  • Common Mistake #8: Creating incorrect references to instance methods
  • Common Mistake #9: Providing a string as the first argument to setTimeout or setInterval
  • Common Mistake #10: Failure to use “strict mode”


Read more

Thursday, June 8, 2017

Writing Testable Code in JavaScript



Whether we’re using Node paired with a test framework like Mocha or Jasmine, or spinning up DOM-dependent tests in a headless browser like PhantomJS, our options for unit testing JavaScript are better now than ever.

However, this doesn’t mean the code we’re testing is as easy on us as our tools are! Organizing and writing code that is easily testable takes some effort and planning, but there are a few patterns, inspired by functional programming concepts, that we can use to avoid getting into a tough spot when it comes time to test our code. In this article, we will go through some useful tips and patterns for writing testable code in JavaScript.

Keep Business Logic and Display Logic Separate
One of the primary jobs of a JavaScript-based browser application is listening to DOM events triggered by the end user, and then responding to them by running some business logic and displaying the results on the page. It’s tempting to write an anonymous function that does the bulk of the work right where you’re setting up your DOM event listeners. The problem this creates is that you now have to simulate DOM events to test your anonymous function. This can create overhead both in lines of code and the time it takes for tests to run.

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