Showing posts with label Coding Standards. Show all posts

A Look Into Java Annotations & A Real World Spring Example





An "annotation" is a type of programming language definition and used as a “marker”. They can be thought as comment lines which programming language engine can understand. They don’t directly affect program execution but affect indirecly if wanted.

Definition

An annotation is defined with @interface keyword and is similar with an interface. It has attributes which are defined like interface methods. Attributes can have default values. Let’s define an annotation named “Page”, which defines UI pages of an application:

public @interface Page {
    int    id();
    String url();
    String icon() default "[none]";
    String name(); default "[none]";
}

Usage

Annotations are widely used to inform compiler or compile-time/runtime/deployment-time processing.
Usage of an annotation is simpler:

@Page(id=1, url=”studentView”, icon=“icons/student.png”, name=”Students”)
public class StudentWindow extends Window { … }

Annotations can also be defined for methods and attributes:

@AnAnnotation
public String getElementName() {…}

@AnAnnotation(type=”manager”, score=3)
public int income;

Examples

1)    Reflection/code generation:

Methods having a specific annotation can be processed at runtime:

public @interface MyAnnotation { ... }
public class TestClass {
    @MyAnnotation
    public static method1() { ... }
    @MyAnnotation
    public static method2() { ... }
    @MyAnnotation
    public static method3() { ... }
}

public static void main(String[] args) {
    for (Method method : Class.forName("TestClass").getMethods()) {
        if (method.isAnnotationPresent(MyAnnotation.class)) {
            // do what you want
        }
    }
}

2)    Spring bean configuration (this section requires Spring bean configuration knowledge):

Let’s use our “Page” annotation again:

package com.cmp.annotation;
public @interface Page {
    int    id();
    String url();
    String icon() default "[none]";
    String name(); default "[none]";
}

Say that we have a few classes having @Page annotation in a package:

@Page(id=1, url=”studentView”, icon=“icons/student.png”, name=”Students”)
public class StudentWindow extends Window { … }

If we define a bean configuration as below in a Spring application-context.xml file, Spring will create class instances “which has @Page annotation” placed in “given package”.

<context:component-scan base-package="com.cmp.ui" annotation-config="true">
<context:include-filter type="annotation" expression="com.cmp.annotation.Page"/>
context:component-scan>

So, we have been enforced Spring to instantiate only a selection of classes at runtime.


For more detailed info about annotations, please refer to:

Posted in , | Leave a comment

A Selection of Successful Software Engineering Posts (2011)





This selection contains 25 blog posts selected by CodeBalance which were placed on DZone in 2011.

Java
Producer and Consumer Pattern in Java
Quick Tip for Improving Java Apps Performance
JUnit Tutorial 2
Clientside Improvements in Java 6 & 7
Java Productivity Report 2011 (India vs Rest of the World)
Be a Better Java Programmer - A Reading List
Method Size Limits in Java
Why I Choose Java?
Best Practices List in Java
Lessons in Software Reliability
Music Components in Java Effects
WWW: World Wide Wait - A Performance Comparison

Software Engineering & Practices
The Principles of Good Programming
A Detailed Study on Understanding Code
Making Better Software - Forget New Features
Making Code Easy to Understand What Developers Want
Things to Remember When Doing Code Review
The Seven Phases of Introducing Continuous Integration

General
The Most Important Man in Tech Dies Last Week…It wasn't Steve Jobs.
The Top 10 Attributes of a Great Programmer
Build Facebook Bot in 2 Easy Hours
30 Free Programming E-Books
Signs That You're a Bad Programmer
A Complete List of All Major Algorithms (300)
10 Android Articles/Tutorials






Posted in , , | 1 Comment

Software Architecture Antipatterns : Swiss Army Knife Interface




Swiss Army Knife Interface is an interface class which has excessive number of method definitions. Architect/designer may design this interface to use for every need of the software, but this is a wrong approach and an antipattern. More than one interface must be designed using some design approaches.
Of course, "excessive number of methods" is a too general statement. Although most developer think that a handful number of methods (e.g. 8-10)  and some studies show that some magic numbers (7 plus/minus 2) are mostly enough, we can't say the maximum number of methods precisely. 

First of all, you must think that this interface will be implemented by a class and if the number of methods is excessive, there will be plenty of empty method bodies in implementor class. But this situation still can't determine the number of interfaces and number of methods in an interface.

The answer is hidden in the OOP SOLID rules. Single Responsibility ("S") rule of SOLID says that "every object should have a single responsibility", and Interface Segregation ("I") rule of SOLID says that "different types of functionalities should be placed in different interfaces". If an interface have more than one types of functionalities or defines more than one responsibilities, implemening that interface is meaningless because implementer class will not suit SOLID rules by implementing that interface. 

More than one Swiss Army Knife Interface may also exist in a software. This means more than one problem exist and must be solved. 

For another viewpoint, you can take a look at our another post about interface segregation principle:


Posted in , , , | 6 Comments

20 Software Development Best Practices




Below are a compilation of 20 software development best practices:

  1. Always use source control system even if the project has only one developer. By doing that, you don't lose some or whole code immediately, can share same source file by multiple person and can take the whole advantage of coding histories. 
  2. Follow coding standards and check that standard with automized tools.
  3. Be consistent. If you do operations in a specific way, do that kind of operations in the same way (e.g. defining variable/method/class names, paranthesis usage etc.).
  4. More code does not mean better code. Keep it simple and reduce complexity.
  5. Don't use magic numbers and strings directly in the code. Use constants. This method provides more modularity and understandability.
  6. Don't use comment lines to delete code, just delete. Version controling system will help you if deleted code is required.
  7. Delete unused methods and classes. Version controling system will help you if deleted code is required.
  8. Catch specific exceptions instead of highest level class 'Exception'. This will provide understandability and more performance.
  9. Use understandable and long names for variables. Loop variable names can be i, j, k, index etc., local variable names must be longer than loop variables, parameter names must be longer than local variables and static variable names must be longer than parameters;  proportional with scope size.
  10. Package related classes (that changed together and/or used together) together.
  11. Use understandable comments. Bad comment is worse than no comment.
  12. Use positive conditionals. Readability of positive conditionals are better than negative ones.
  13. Use dependency injection to manage too many singletons.
  14. Use exceptions only for catching exceptions, not for control flow. Think as required and perform control flow with control statements/conditionals.
  15. Don't use so many arguments with methods. Keep the number at most 8-10. If more is required, review your design.
  16. Don't use method alternatives with boolean flag variables (public void someMethod(bool flag)). Write more than one method for each flag condition.  
  17. Method names must include "what is done by this method" information.
  18. Think twice before defining a method as static and be sure if you really need to. Static methods are harder to manage.
  19. Avoid using methods with reference parameters. Use multi attributed object parameters instead.
  20. Number of interface methods must be minimized to decrease coupling/dependency.

Posted in | 50 Comments