Tag Archives: code

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.

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.

Using Javadoc for documentation

What is Javadoc? Most of the times people confuse it with the actual HTML documentation for the Java code. This is somewhat true but not entirely. Javadoc, itself is not the documentation, it is a tool from SUN Microsystem that helps you generate the documents.

How does it work? Javadoc allows developers to add documentation for a code in the java file itself in some specially formatted comments. The tool will read these comments and create a HTML document file.

Why do we use Javadoc? Why can’t we just create documents on our own? Well That is possible. Javadoc is there to make your life simpler as a developer. It helps you keep your code and documentation information in the same file. Just imagine if you are keeping the documentation separately, everytime you make a change in code, you ill need to modify the documentation also. What if someone misses it? If it is in the same file it is easier to maintain and hard to miss.  Most importantly, you are not writing the whole documentation, but just adding some quick comments which will be interpreted by the Javadoc tool. Lot more easier and faster than actually writing the documentation.

How to implement it? Simple, just add some specially formatted comments in your code

Class Level comments

@author : Author of the class
@version : automatically provide accurate version and date updates.
@since :  Describes when this functionality has first existed.

Method Level

@param : method or constructor argument names and description
@return :  What does your method returns
@throws : Does this method throw an exception
@deprecated : 	Describes an outdated method.

General Commets

@see : Adds 'See also' entry
@link : Adds an inline link with a label for users of your API documentation

The final code will look something like

import java.util.ArrayList;

/**
 * This is a Java Class to find anagrams. Any class level description goes here
 *
 * @author kamal
 * @version 1.0
 * @since 21-Sep-2011
 */
public class test{

/**
 * This is the main method method
 *
 * use {@link #findAnagrams(String)}
 * @param str
 * 		Any param description goes here
 */
public static void main(String str[])
{
	try
	{
		 String finalString="TestString";
		 test t =new test();
		 t.findAnagrams(finalString);
	}
	catch(Exception e) {
	   e.printStackTrace();
	}
}

/**
 * This is another method and we will add the description here
 *
 * @param input
 * 		Any param description goes here
 * @return
 * @throws NullPointerException
 */
private ArrayList findAnagrams(String input) throws NullPointerException
{
	ArrayList retList=new ArrayList();
	if(input.equals("")) throw new NullPointerException();
	printAnagrams(retList, "",input);
	return retList;
}

/**
 * Yet another method description goes here
 *
 * @param retList
 * @param prefix
 * @param word
 */
public void printAnagrams( ArrayList retList, String prefix, String word) {

if(word.length() <= 1) {
	retList.add(prefix + word);
} else {
for(int i = 0; i < word.length(); i++) {
String cur = word.substring(i, i + 1);
String before = word.substring(0, i); // letters before cur
String after = word.substring(i + 1); // letters after cur
printAnagrams(retList,prefix + cur, before + after);
}
}
}
}

and your javadoc comments will look like

image link

testdoc

Java Inheritance- Method and Variable overriding

A very simple example to understand overriding concept in java

Parent Class-

public class parent {

int pval=10;
parent()
{
System.out.println(“creating parent”);
}

public void area()
{
System.out.print(“area of parent:”);
System.out.println(pval);
}
}

Child class-

public class child extends parent{
int cval=5;
int pval=15;
child()
{
System.out.println(“creating child”);
}

child(String str)
{
System.out.println(“hello:”+str);
}

public void area()
{
System.out.print(“area of child:”);
System.out.println(cval);
}

public static void main(String s[])
{
child c=new child();
c.area();
System.out.println(“c.pval:”+c.pval);
System.out.println(“—————————-“);
child c1=new child(“kamal”);
System.out.println(“—————————-“);
parent p=new parent();
p.area();
System.out.println(“p.pval:”+p.pval);
System.out.println(“—————————-“);
parent pc=new child();
pc.area();
System.out.println(“pc.pval:”+pc.pval);
System.out.println(“—————————–“);
}

}

output

creating parent
creating child
area of child:5
c.pval:15
—————————-
creating parent
hello:kamal
—————————-
creating parent
area of parent:10
p.pval:10
—————————-
creating parent
creating child
area of child:5
pc.pval:10
—————————–

Look closely at the last set of output, that is interesting. You can see when we refer to child object with parent class reference, the method being called is from child class as method was overridden, but the pval member variable was not overridden.

Now as member variables are not overridden, compiler uses static binding as it already know which variable is being referred to, whereas in case of parent class object calling a method which is overridden, compiler will not know beforehand which method should be called, so it will leave that decision to runtime, hence dynamic binding.

Why Markup Interfaces?

I wonder why java provides markup interfaces? like serializeable or Cloneable, they just tell the compiler that a particular class object can be serialized or cloned. In other words they mark the class with some special property. But then why are these interfaces, why not just keywords? Thoughts?