Relocation of CodeBalance



CodeBalance blog has been renamed as CodeBuild on 12th January 2012, by the author.
You can reach the new site via codebuild.blogspot.com.
Blog postings about software development will continue on CodeBuild exactly as before.


Thanks for your concern.

Leave a comment

Java Dynamic Web Project to Maven 3 Project - Migration Steps





If you start a java project in eclipse as "maven project" at the beginning, all you need is downloading maven distribution or maven plug-in and add dependencies to the pom.xml file when required. But some issues exist while migrating from java dynamic web project to maven project. In this post, required configuration steps will be told. Maven introduction, installation, "repository" concept and maven commands are out of scope for this post.

  • Source codes for a maven project must be located in src/main/java folder. Also test and resources must be located in src/test/java and src/main/resources folders respectively. For this conversion, you can create required folders manually and copy old source codes in it, but more preferred and stable way is defining source paths in Project Properties --> Java Build Path section:

Source folder configuration

  • /WEB_INF folder is not used in maven projects. There is "webapp" folder instead. You can move WEB_INF files into webapp folder as the given structure  and delete old WEB_INF folder. You don't even need lib folder because maven will create required jars:
webapp folder


  • target/classes folder must be the output (deploy) path instead of build/classes. Again in Project Properties --> Java Build Path section:

Output folder



  • org.eclipse.wst.common.component file needs some changes. Open it using ctrl+shift+R and edit deploy path and output path as below:
org.eclipse.wst.common.component file
  • Create pom.xml file on project root folder and configure required sections with your project details. Then add required dependencies one-by-one between tags (This will be the most time consuming issue if there are tens or hundreds of JARs). If maven global repository has required jar, it will be downloaded automatically, otherwise you must find required jar and run "mvn install" command to install that jar to maven repository:
pom.xml file
  • Run mvn-install or mvn-package commands for the project. Created JARS, web.xml, other resources and class files will be located under /target folder automatically. Also a WAR file for the project will be created. You can copy WAR file to server (e.g. apache tomcat) and run the application, or you can run the application using the server defined in eclipse. 
target directory

  • Depending on the running style of mvn-install command (by plug-in, command etc.) , created JARs under the /target folder may not be copied to src/main/webapp/WEB-INF folder. If you will run the application using the server of the ide, you may be needed to copy created libs into src/main/webapp/WEB-INF/lib folder and add those libs to project using Project Properties --> Java Build Path --> Libraries --> Add JARs section for once.
Adding required jars under webapp/WEB-INF/lib

Posted in , | Leave a comment

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

Improve Software Quality with Tools and Processes





As most of the software developers know, software engineering is not just "coding". It's a complex process which requires engineering vision, analytical thinking, designing and software process management supported with tools. This article contains some important approaches, techniques and tools to improve software production quality.

Software quality depends on time and cost of course. But you can be sure that spent money and time will return as so much more. Quality standards will also be used for upcoming projects and increase company growth speed on midterm.




  • Choose a suitable process model and apply it correctly
As you know there are software process models like agile, scrum, iterative and incremental etc. Choose one of these according to the project type. You don't have to perform all rules strictly, you can modify most of them. The point is "using a process" here, for a systematic and ordered development.


  • Control the version of each required source
Using a version controlling system is a must. Even if only one developer exist, it must be used. Historical data, versioning, merging, ... is very important for increasing productivity. Otherwise developers will wait each other, can not detect performers and lines of previous changes, can not perform versioning systematically etc. SVN, CVS and TFS are used for this purpose.

  • Track issues with easy-to-use tools
Parallel with using a process model, issue tracking tool usage is essential. JIRA-like tools are useful and easy-to-use. By tracking issues, you can track productivity and software growth and get production reports easily. Besides, those tools can be used to monitor developer work-hour productivity.

  • Perform and manage documentation
Perform documentation as required (e.g. %10 of total production time). No documentation is never a good solution as much as excessive documentation. It may include code documentation, requirement specifications, design documents, test documents, user manuals etc. Those documents are needed to be managed and shared also, by using version controlling tools or web based platforms (like Confluence). 

  • Use dependency management tools
Managing dependency libraries (library projects, jars, DLLs etc.) are a big problem especially for big projects. Configuring libraries to run the application after each release or after each project check-out is a hell. Use a dependency managing tool like Maven or at least auto build/copy script tools like Ant.

  • Use continuous integration
Building, deploying and versioning software is a big problem. Its time consuming and reduces productivity. Because of these, use a continuous integration tool (Hudson for example) and integrate it with dependency management or build tools (like Maven, Ant, ..). The tool may be configured to perform a build on each commit, on clicking a button manually or on predefined periodic times...

  • Perform testing and integration testing constantly
Testing is very important for software quality. Test documentation which may consist test scenarios, results and relations with issues is required.  Also, testing (UI testing, integration testing, ...) must be performed constantly and periodically. Even if changing a single line of code may crush the whole system or crash a hidden functionality. for example, JUnit is very popular for Java applications.

  • Perform unit testing and automatize it
Unit testing is as important as the other testing methods. Unit tests provide pre-detection of most of the problems. By performing qualitative unit testing, time consumption for other testing methods also descreases. Automatizing these tests using continuous integration tools or at least command line tools (Hudson with Maven for example) are important to keep software consistency and reliability.

  • Collect metrics from production and use results
Coding metrics (e.g. line of code, abstraction ratio, cyclomatic complexity, ...) gives us some good viewpoints about software. For example, by using line of code maybe we can't (or we mustn't) determine the productivity of a developer; but we can determine the growth speed of software monthly. Complexity-like metrics tells us design errors before deployment. These metrics can be collected by tools or plug-ins (e.g. CodePro Eclipse plug-in). 

  • Follow best practices of coding and control with tools
There is no "golden rule" suitable with all software projects, but there are best practices for project management, architecture, designing, coding, testing for most situations. Performing those rules will increase the quality. For example, you can define rules for code production (about indentation, commenting, magic numbering, paranthesis etc.) and monitor convenience automatically and periodically with external tools or plug-ins like Maven Surefire Report plug-in.

4 Comments

Hibernate 3 Installation & Configuration





Short Description:
Hibernate is an ORM framework for Java applications, which maps application objects into relational database tables. It is important because:
  • Developers don't write SQL expressions into code. This saves time and increases maintainability.
  • It is database independent. DBMS can be changed without changing the code. Only configuration XML is modified for this.
  • It supports transaction methods and auto-creation of tables, constraints, relations (1-N,1-1, N-N, etc.).
Installation:
Requires two steps:

  1. Copying required JARs into /lib directory:
  2. Creating and configuring persistence.xml configuration file.
Required JARs are: 
Hibernate installation JARs
Hibernate requires only hibernate3.jar. But hibernate-jpa jar is also used generally for additional JPA properties. A database connector jar is also reqiured for connection handling. mysql-connector jar is used here for this reason. Other jars are required because of dependencies. These jars can be found on most Java developer download site with exact version numberings.

persistence.xml file is also required to map application into database. Database configuration is done in this file. It is put into /src/main/config/META-INF folder as default. Content should be as below:


Hibernate persistence.xml configuration

  • persistence-unit name: Defines the configuration id. More than one persistence unit can be defined at once.
  • hibernate.connection.driver_class & hibernate.dialect: Defines the database type. MySQL is used in this example.
  • hibernate.connection.username & hibernate.connection.password: Defines database connection parameters.
  • hibernate.connection.url: Defines database server name, port and schema. "test" is used here for schema name.
These two steps are required and enough for starting Hibernate usage. Hibernate entity definition and API usage will be explained in upcoming posts.

Posted in , , | 3 Comments

A Quick Reference to the Spring 3 DI Bean Configuration





Spring 3 DI (dependency injection) functionality which placed in "Spring Core" is very important for managing objects (or "beans") in enterprise applications.


Here is a quick reference for bean configuration of Spring DI:

Spring Bean Configurations 





You can get a bean in application by

manual:
ApplicationContext context = new ClassPathApplicationContext(new String[] {“application-context.xml”})
ViewManager viewManager = (ViewManager)context.getBean(“viewManager”);

annotation:
@Autowired
ViewManager viewManager;




Posted in , , | 1 Comment

10 SCRUM Methodology Best Practices




Here is a list of some best practices about scrum:

  • Burn down charts can be used to monitor sprint status. Graphical representations are better than tabular list views in planning.
  • Planning poker is a useful way to determine sprint item finish durations. And using Fibonacci numbers is a good practice for planning poker numbers.
  • ROI (Return on Investment) values are useful to determine item priorities in a sprint. Planning poker can be used to determine ROI values.
  • Using a board and simple planning/reporting tools (e.g. excel, sprintometer, projectsimple) are important and enough as process quality equipments.
  • Scrum methodology does not offer documenting everything, but this does not mean "no documentation". Really needed documentation can be done as required.
  • Daily meetings must not be longer than 15 minutes. Scrum is an agile methodology and no one needs to listen other members' problem details. These details may be discussed after daily meeting with scrum master with only required subset of team members.
  • Stand up meeting style is better for daily meetings, to keep meeting short. Also meeting location and time are recommended to be the same for each day.
  • Product backlog may contain items which will not be developed. According to ROI values, some items may not be developed and this is normal. Product backlog should contain all possible items anyway. Give backlog items ID numbers, to manage simply.
  • Sprint length (in weeks) changes are not recommended. But according to the sprint retrospective meeting results, sprint week lengths may be changed if there are really important reasons.
  • 6 hours per a day is a realistic planning input. Total sprint hour capacity can be calculated as: (number of team members) * (number of sprint days) * 6 hours

Posted in | Leave a 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

SCRUM Software Development Methodology : Nuts & Bolts




Scrum is an agile software development methodology. It is useful for relatively small (5-9 developers) development teams and limited project calendars. This post will give brief definitions and useful suggestions about this methodology.
Team Members
  • Product Owner: Behaves as real customer and criticizes product. Attends meetings and can determine work priorities. Adds items to product backlog (will be told later). Only one person can be product owner in a scrum team.
  • Scrum Master: Enforcer of the rules. Generally most experienced team member. Works like team leader. Solves the problems of the team, if team/team member couldn't. Only one person can be scrum master in a scrum team.
  • Team: A scrum team member is responsible of analysing, design, development, test and the other required processes. So, specialization is rare. Self-organization is a plus. There is no hierarchy in members. Scrum master is also a team member.
Document Types:
  • Product Backlog: This list contains items that the project must have and may have. Item size can increase every time.
  • Sprint Backlog: Sprint is a time interval (generally 2-4 weeks) that a group of items must be completed (similar with "iteration" in unified process and some other processes). Sprint backlog contains items that must be completed in that sprint.
Meeting Types: 
  • Daily Scrum/Standup Meeting: Max. time is 15 minutes. Performed at the start of the day and generally in stand-up style. Every member should answer 3 questions: 
    • What did you do yesterday? 
    • What will you do today? 
    • Is there a problem about your work item(s)?
  • Sprint Planning Meeting: Performed at the start of each sprint. Sprint backlog is created using product backlog items and priority opinions of all team members.
  • Sprint Review: Performed at the end of each sprint. Status of sprint backlog items are discussed and results are recorded.
  • Sprint Retrospective: Performed at the end of each sprint. Sprint process issues are discussed to improve process quality.
Process:
Scrum Process
  • From product owner opinions and other internal/external sources, product backlog is created.
  • Sprint planning meeting is performed at the start of each sprint. Previous sprint's unfinished items (if exists) and product backlog are sources of sprint backlog. Backlog is created according to item priority opinions of all team members. Sprint length (in weeks) may also be defined here for once.
  • In sprint time, daily meetings are performed. Team members take responsibility of items from item pool of sprint backlog continiously when an item is finished. By the way scrum master solve possible problems and product owner criticizes results.
  • Sprint review and retrospective meetings are performed at the end of each sprint. Results are discussed in these meetings. Results are recorded to be applied for next sprints.

Posted in | 4 Comments

20 Database Design Best Practices





  1. Use well defined and consistent names for tables and columns (e.g. School, StudentCourse, CourseID ...).
  2. Use singular for table names (i.e. use StudentCourse instead of StudentCourses). Table represents a collection of entities, there is no need for plural names.
  3. Don’t use spaces for table names. Otherwise you will have to use ‘{‘, ‘[‘, ‘“’ etc. characters to define tables (i.e. for accesing table Student Course you'll write “Student Course”. StudentCourse is much better).
  4. Don’t use unnecessary prefixes or suffixes for table names (i.e. use School instead of TblSchool, SchoolTable etc.).
  5. Keep passwords as encrypted for security. Decrypt them in application when required.
  6. Use integer id fields for all tables. If id is not required for the time being, it may be required in the future (for association tables, indexing ...).
  7. Choose columns with the integer data type (or its variants) for indexing. varchar column indexing will cause performance problems.
  8. Use bit fields for boolean values. Using integer or varchar is unnecessarily storage consuming. Also start those column names with “Is”.
  9. Provide authentication for database access. Don’t give admin role to each user.
  10. Avoid “select *” queries until it is really needed. Use "select [required_columns_list]" for better performance.
  11. Use an ORM (object relational mapping) framework (i.e. hibernate, iBatis ...) if application code is big enough. Performance issues of ORM frameworks can be handled by detailed configuration parameters.
  12. Partition big and unused/rarely used tables/table parts to different physical storages for better query performance.
  13. For big, sensitive and mission critic database systems, use disaster recovery and security services like failover clustering, auto backups, replication etc.
  14. Use constraints (foreign key, check, not null ...) for data integrity. Don’t give whole control to application code.
  15. Lack of database documentation is evil. Document your database design with ER schemas and instructions. Also write comment lines for your triggers, stored procedures and other scripts.
  16. Use indexes for frequently used queries on big tables. Analyser tools can be used to determine where indexes will be defined. For queries retrieving a range of rows, clustered indexes are usually better. For point queries, non-clustered indexes are usually better.
  17. Database server and the web server must be placed in different machines. This will provide more security (attackers can’t access data directly) and server CPU and memory performance will be better because of reduced request number and process usage.
  18. Image and blob data columns must not be defined in frequently queried tables because of performance issues. These data must be placed in separate tables and their pointer can be used in queried tables.
  19. Normalization must be used as required, to optimize the performance. Under-normalization will cause excessive repetition of data, over-normalization will cause excessive joins across too many tables. Both of them will get worse performance.
  20. Spend time for database modeling and design as much as required. Otherwise saved(!) design time will cause (saved(!) design time) * 10/100/1000 maintenance and re-design time.

Posted in | 37 Comments