Category Archives: coding

Clean Code: Java

Summarizing clean code practices for Java

Naming Conventions: Use meaningful names conveying the intent of the object.

Constants: Use Constants to manage static values (Constants help improve memory as they are cached by the JVM. For values that are reused across multiple places, create a constant file that holds static values.) use ENUMs to group constants.

Clean Code: Remove Console print statements, Remove Unnecessary comments

Deprecate Methods: Use @deprecated on method/variable names that aren’t meant for future use

Strings: If you need to perform a lot of operations on a String, use StringBuilder or StringBuffer.

Switch statement: Rather than using multiple if-else conditions, use the cleaner and more readable switch-case.

Exception Handling: https://kamalmeet.com/java/exception-handling-basic-principles/

Code Structure: Follow the Separation of Concerns strategy – controller, service, model, utility

Memory Leaks: Unclosed resources, e.g. unclosed URL connections can cause memory leaks. https://rollbar.com/blog/how-to-detect-memory-leaks-in-java-causes-types-tools/

Concurrent code: Avoid unnecessary synchronization, and at the same time identify areas to be synchronized where multiple threads can cause problems.

Lambdas and Streams: If you’re using Java 8+, replacing loops and extremely verbose methods with streams and lambdas makes the code look cleaner. Lambdas and streams allow you to write functional code in Java. The following snippet filters odd numbers in the traditional imperative way:

List<Integer> oddNumbers = new ArrayList<>();
for (Integer number : Arrays.asList(1, 2, 3, 4, 5, 6)) {
    if (number % 2 != 0) {
      oddNumbers.add(number);
  }
}

This is the functional way of filtering odd numbers:

List<Integer> oddNumbers = Stream.of(1, 2, 3, 4, 5, 6)
  .filter(number -> number % 2 != 0)
  .collect(Collectors.toList());

NullPointerException: When writing new methods, try to avoid returning nulls if possible. It could lead to null pointer exceptions.

Use final: When you want to make sure a method should not be overridden

Avoid static: Static can cause issues if not used properly as it shares variables at class level 

Data Structures: Java collections provide ArrayListLinkedListVectorStackHashSetHashMapHashtable. It’s important to understand the pros and cons of each to use them in the correct context. A few hints to help you make the right choice

Least visibility: Use of Public, private, and protected

Stay SOLID: https://kamalmeet.com/design/solid-principles-for-object-oriented-design/

DRY: Don’t Repeat Yourself, common code should be part of utilities and libraries

YAGNI: You Are not Going to Need It, code only what is needed

Static Code Review: SonarQube in Eclipse

Size of Class and Functions: Class and Function should be small – 400 / 40

Input checks: Inputs into methods should be checked for valid data size and range

Database Access: Use best practices like Connection Pool, JPA, Prepared statements, etc.

Clean Code: Error Handling, Testing, and Classes

In the clean code series, I will cover Error Jandling, Testing and Clean classes in this post.

Error Handling

  • Catch only Exceptions meant to be caught, for example, checked exceptions in Java
  • Log as much information as possible when an error or exception occurs for analysis
  • Null objects should not be returned, instead, return empty objects

Testing

  • Code Coverage targets should be set and achieved
  • TDD helps write testable code and reduce the number of issues
  • Use the F.I.R.S.T rule for testing:
    • The test is fast-running.
    • The tests are independent of others.
    • The test is repeatable in various environments.
    • The test is self-validating.
    • The test is timely.

Clean Class

  • Single Responsibility
  • Open for extension and closed for Modifications
  • Readability: self-documenting class names, function names, and variable names

Clean Code: Comments, Formatting, and Objects

In continuation with the clean code series, here I am covering Comments, Formatting, and Objects and data structures.

Comments

  • Code should be self-explanatory, the purpose of the code is that humans should be able to understand and not that computer is able to execute it
  • Comment only where logic is complex
  • Private API should not have comments
  • Use comments when you want to caution other developers, for example, why List instead of Queue was chosen and should not be modified
  • Comments should answer why (was a decision made) and not how the code works

Formatting

  • Formatting is a way to communicate with fellow developers
  • Readability = Maintainability = Extensibility
  • Verticle Alignment: Keep connected functions together for better readability
  • Horizontal Alignment: one should never need to scroll right
  • Team Formatting Rules: everyone should follow the same rules, braces, ident size, spaces/tabs

Objects and Data Structures

  • Follow OOPS Principles, e.g. parameters and behavior should be encapsulated
  • Law of Demeter:  M method of an object O can only consume services of the following types of objects:
    • The object itself, O.
    • The M parameters.
    • Any object created or instantiated by M.
    • Direct components of O.
  • Avoid Static methods wherever possible

Clean Code: Naming and Functions

Inspired by Clean Code by Robert C Martin, trying to summarize coding best practices. Starting with Naming and Functions best practices in this post.

Naming

  • Names should encode the intent, for example, studentBirthYear.
  • Use Good distinction: Do not use list1, list2, etc
  • Use Pronounceable name: dobmmyy vs dateOfBirthInMonthAndYear
  • use searchable names: int i, j, when you will try to search you will find a lot of them in code
  • Do not add type: phoneString, name String, name and phone should be sufficient
  • Avoid unclear prefixes: m_name vs manager_name
  • nouns for names and verbs for functions: employee for class and paySalary for function
  • Use Consistent concept: controller vs manager
  • Don’t use the same name twice to mean 2 different things. paymentInfo at one place returns bank details and another place user payment
  • Use Domain specific names
  • Avoid too long or too short names: Long is fine if it conveys better information, but not too long that makes it difficult to pronounce

Functions

  • Write Small functions, functions larger than 20 lines should be avoided
  • Make sure the function does only one thing
  • Use minimum arguments: max 2, if the function takes too many arguments, it is doing too much
  • DRY, Do not Repeat yourself: IF you are doing the same thing in multiple functions, move it to commonplace
  • Don’t use flag element, parameters of the Boolean type as a parameter already clearly state that it does more than one thing.

Node vs Java Comparison

A good read on Node vs Java https://rclayton.silvrback.com/speaking-intelligently-about-java-vs-node-performance. Explains about the way Java and Node code will work to handle load.

My personal opinion is that programming language is just a tool to deliver the final solution. Only in specialized cases, where we know that a particular language has proven history of solving similar kind of problems, hence has sample code, libraries, knowledge base, forums to help, we should consider that as part of solution. Otherwise non-technical reasons like client preferences, team’e expertise will come into picture.

Branch predictor

Whenever in our code a conditional statement is executed, Branch Precitor tries to predict which way the flow will go and executes that even before conditional statement actually returns the output. This is done to stop wastage of time in waiting for conditional statement execution.


From wikipedia
– In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Here is a good example to see what Branch predictor can do

package Permissions.Permissions;

import java.util.Arrays;
import java.util.Random;

public class test {

public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];

Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c) data[c] = rnd.nextInt() % 256; // !!! With this, the next loop runs faster // Arrays.sort(data); // Test long start = System.nanoTime(); long sum = 0; for (int i = 0; i < 100000; ++i) { // Primary loop for (int c = 0; c < arraySize; ++c) { if (data[c] >= 128)
sum += data[c];
}
}

System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum = " + sum);
}

}

Try uncommenting the sort array part and see the difference.

Source- stackoverflow

Submitting Special characters in your Form

If you will try to submit special characters like chinese or spanish text, you will see some junk boxes being submitted to the server. We need to make sure proper encoding, say UTF-8 is being in place. In your HTML (JSP/PHP etc) page, you will need to let browser know that your page works with UTF-8.

<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>com.mysite.SessionFilter</filter-class>
<init-param>
<param-name>PARAMETER_ENCODING</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

In addition, you might want to enforce the settings onto your server to let it know that you are expecting UTF-8 content in request. For example in JBOSS, we will create a filter and enforce UTF-8 content type

And create the filter class like

public class SessionFilter implements Filter {
private String encoding="";

/**
* destroy method to clean up any activities
*/
public void destroy() {
}

/**
* Override the doFilter method to apply any action, in this case setting request encoding
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException
{
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}

/**
* Override init method to set parameter encoding as provided by web.xml
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
if (filterConfig.getInitParameter("PARAMETER_ENCODING") != null)
{
encoding= filterConfig.getInitParameter("PARAMETER_ENCODING");
System.out.println("encoding "+encoding);

}
}

}

Dust me- clean up unused CSS

Recently came accross a legacy code which had a lot of css code and files, which was written over years and most of it was obsolete. Dust-me, firefox plugin helped to figure out all the unused css code. Though I had to traverse all possible flows in the application, but end result was good as few files were identified which were not being used completely and were removed, saving page load time.

Prototype.js library

Some of my old notes from Prototype (3-4 yrs older so there might be changes)

Overview

Prototype is a JavaScript toolkit. This helps in generation of a application by providing commonly used functionality so that the developer does not have to spend time on them.

The Prototype JS has features provides some basic functions which work as short cuts to already existing functionalities e.g. $() can be used in place of document.getElementById(), there are other complex functions for dealing with XMLHttpRequest. A many other libraries are created by extending this library.

You can download the free prototype.js from http://www.prototypejs.org/download. Once downloaded this JavaScript file can be added to any HTML page just like any other JavaScript file <script type=”text/javascript” src=”prototype.js”></script>

Key Functionalities

Let us look at some of the major functionalities provided by Prototype which makes life of developer simple.

$():

This is equivalent to saying document.getElemetById()
e.g.
var name=$(‘name’);

is same as
var name=document.getElementByID(‘name’);

Where HTML has
<input type= “text” id= “name” value= “John”/>

$$():

This will return you an array of elements from HTML document
e.g.
var eleArray= $$(“#formName input”);

This would return an array of all input type fields inside the form formName. This can be further used like

for(var i=0; i<eleArray.length; i++)
{
valueArray=eleArray[i].value;
}

$F():

To get the value of an element in the page
$F(‘name’) is equivalent to document.getElementByID(‘name’).value;

$A():

$A() Creates an array
var arrayOfNodes= $A(xmldoc.getElementsByTagName(‘abc’));

$H():

$H() Creates a hash table
var employeeHash= $H({
name: “John”,
email: “John@company.com”,
employeeId: “12345”
});

Try.these() Function:

This is an interesting function which lets developer write multiple functions. The code keep trying executing functions until one of them is success. This can be helpful if we are writing code to be supported by multiple versions of JavaScript or multiple browsers

Try.these(
function() {//do something
alert (“first one worked”);
return;
},
function() { // do something
alert (“second one worked”);
return;
}

AJAX Object:

Prototype provides AJAX object to minimize the effort using any AJAX related methods. AJAX object further provides the following classes.

AJAX.Request:

Ajax.Request object encapsulates the commonly used Ajax code for setting up the XMLHttpRequest object, performing cross-browser checking for compatibility and callback handling.

function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
onSuccess: process,
onFailure: function() {
alert(“There was an error with the connection”);
}
});
}

AJAX.Updater:

This is similar to the AJAX.Rrquest method above, with an additional feature that it can also update the page with the information returned by server to AJAX call.
new Ajax.Updater(container, url[, options])
function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
‘placeholder’,
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
}
});
}

AJAX.Responders:

AJAX responders are more of global methods which we register and unregister at the start and end of execution of code. They monitor all the AJAX activity going on and show the processing activities (say some animation while the data is being fetched from the server).
Ajax.Responders.register(attributes)
Ajax.Responders.unregister(attributes)
Some of the most common callbacks which are used with responders is
Ajax.Responders.register({
onCreate: showProcessing,
onComplete: hideProcessing
});

Additional Links

http://www.prototypejs.org/
http://www.sergiopereira.com/articles/prototype.js.html
http://attic.scripteka.com/prototype_cheatsheet_1.6.0.2.pdf
http://particletree.com/features/quick-guide-to-prototype/

More on Dependency Injection

Sometime back I talked about dependency injection. Dependency injection is a design pattern that implements inversion of control principal. That is, you take out a dependency from within a class and inject it from outside.

So lets say there are 2 classes, Employee and Address, say Employee is dependent on Address

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

address=new Address(‘some values here’);

}

}

Here we are leaving the responsibility of creating the address with Employee class. Using DI (Dependency Injection) we will pull out this responsibility of creating the address object from Employee class and give it to calling/initializing class/container.

There are 2 ways to implement this DI concept

1. Through constructor:

class Employee{

public Address address;

Employee(Address address)

{

this.address=address;

}

}

2. Using a setter method:

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

}

public void setAddress(Address address)

{

this.address=address;

}

}

Lets make it a bit more interesting. Say we have a AddressFactory which can create either a LocalAddress or PermanentAddress. Both LocalAddress and PermanentAddress implement Address Interface.

In case of non DI scenario

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

//check if employee has local address

address=new AddressFactory.getAddress(“LocalAddress”);

//else case get permanent address

}

}

In this case DI becomes more useful as Employee class does not need to worry about the type of address which will be provided by calling class or container. No need to change the code given for DI implementation, it will work fine.