design, development, java, technology

ten commandments for Java programmers

There are many standards and best practices for Java Developers out there. The article 10 Commandments for Java Developers outlines ten most basic rules that every developer must adhere to and the disastrous outcomes that can follow if these rules are not followed. Briefly summarizing the 10 commandments:

    1. Add comments to your code. – It is true comments do not literally contribute to the functionality of a program. But time and time again you return to the code that you wrote two weeks ago and, for the life of you, you cannot remember what it does!
    2. Do not complicate things. – Developers tend to come up with complicated solutions for the simplest problems. We introduce EJBs into applications that have five users. We implement frameworks that an application just does not need. We add property files, object-oriented solutions, and threads to the application that do not require such things. For those who do not know any better, I recommend reaching out to the more experienced programmers for advice.
    3. Keep in Mind – “Less is more” is not always better. – Code efficiency is a great thing, but in many situations writing fewer lines of code does not improve the efficiency of that code.
    4. No hard coding, please. – Developers often forget or omit this rule on purpose because we are, as usual, crunched for time. But maybe if we had followed this rule, we would not have ended up in the situation that we are in. How long does it take to write one extra line of code that defines a static final variable?
    5. Do not invent your own frameworks. – There are literally thousands of frameworks out there and most of them are open-source. Many of these frameworks are superb solutions that have been used in thousands of applications. We need to keep up to date with the new frameworks, at least superficially. One of the best and most obvious examples of a superb widely used framework is Struts. This open source web framework is a perfect candidate to be used in web-based applications.
    6. Say no to Print lines and String Concatenations. – I know that for debugging purposes, developers like to add System.out.println everywhere we see fit. And we say to ourselves that we will delete these later. But we often forget to delete these lines of code or we do not want to delete them.
    7. Pay attention to the GUI. – No matter how absurd it sounds; I repeatedly observe that GUI is as important to the business clients as functionality and performance. The GUI is an essential part of a successful application. Very often IT management tends to overlook the importance of GUI. Many organizations save money by not hiring web designers who have experience in design of “user-friendly” applications. Java developers have to rely on their own HTML skills and their limited knowledge in this area.
    8. Always Prepare Document Requirements. – Every business requirement must be documented. This could be true in some fairy tale, but it is far from that in the real world. No matter how time-pressed your development is, no matter how tight the deadlines, you must always make sure that every business requirement is documented.
    9. Unit-test. Unit-test. Unit-test. – I am not going to go into any details as to what is the best way to unit-test your code. I am just going to say that that it must be done. This is the most basic rule of programming. This is one rule that, above all, cannot be omitted. It would be great if your fellow developer could create and execute a test plan for your code, but if that is not possible, you must do it yourself. When creating a unit test plan, follow these basic rules:
      1. Write the unit test before writing code for the class it tests.
      2. Capture code comments in unit tests.
      3. Test all the public methods that perform an “interesting” function (that is, not getters and setters, unless they do their getting and setting in some unique way).
    10. Remember – quality, not quantity. – Do not stay late (when you do not have to). I understand that sometimes production problems, urgent deadlines, and unexpected events might prevent us from leaving work on time. But, managers do not appreciate and reward their employees because they stay late on regular basis, they appreciate them because they do quality work. If you follow the rules that I outline above, you will find yourself producing less buggy and more maintainable code. That is the most important part of your job.

 

Standard
apis, development, JavaScript

Build powerful Web interfaces with a free JavaScript framework

Scriptaculous allows you to easily add powerful AJAX-based user interface features to Web 2.0 applications. Web developer Tony Patton explains why you should use it and describes how to use it.

Scriptaculous is a framework for building dynamic Web 2.0 interfaces. It utilizes another freely available framework called prototype. Scriptaculous simplifies the ins and outs of implementing an AJAX-based Web interface. It allows you to easily add animation and custom data controls, as well as utilities for working with the DOM and JavaScript testing.

Why use it?
AJAX is a great marriage of technologies, but it can be confusing and time-consuming to build AJAX-powered applications from scratch. The scriptaculous framework makes it easy to include AJAX-based features in your applications, plus all of the development and testing has been done, so you can devote your time to more important tasks.

Getting started

The first step in utilizing the scriptaculous framework is downloading and installation. The download is basically a zip file with JavaScript files along with various HTML files for testing and demonstration. The JavaScript source files are the most important. The following list contains an overview:

Keep your developer skills sharp by signing up for TechRepublic’s free Web Development Zone newsletter, delivered each Tuesday.

  • lib\prototype.js: The source for the prototype JavaScript framework.
  • scr\builder.js: Allows you to easily create DOM elements dynamically.
  • src\controls.js; Includes the core components for working with the custom data controls.
  • src\dragdrop.js: Provides the code for utilizing the custom data controls for drag-and-drop related functions.
  • src\effects.js: The Visual Effects library includes all you need to add advanced JavaScript animation to your Web application.
  • src\scriptaculous.js: The base code library for utilizing the scriptaculous framework.
  • src\slider.js: Provides the code for utilizing the slider data control.

The previous list includes the default directory where each file is installed. You can place these JavaScript files anywhere on the Web server, but using the default directories makes it easier to work with the examples.

You may be wondering about the overhead of including these files in a Web page. The complete library (all files in the list) consumes approximately 150KB. The two core files—prototype.js and scriptaculous.js—add up to 50KB. So, all other combinations will be between 50 and 150KB depending on the files used.

By default, scriptaculous.js loads all of the other JavaScript files necessary for effects, drag-and-drop, sliders, and all of the other scriptaculous features. You can limit the additional scripts that get loaded by specifying them in a comma-separated list (via the load command) when loading the scriptaculous JavaScript file.

Once you have downloaded and installed the framework, it is easy to use it within a Web page. The first step is linking to the JavaScript source files within the head portion of the Web page. See Listing A.

The various functions available are accessed via HTML script tags. You can gain a better understanding by examining one of the test files installed with the framework (or an online example). As an example, I loaded the slider_test.html file located in the test\functional directory of a default installation. The complete contents of the file are too much to list here, but I can examine one portion that loads the first slider control on the page—a standard horizontal slider:

<script type="text/javascript">
// <![CDATA[
new Control.Slider('handle1','track1',{
sliderValue:0.5,

onSlide:function(v){$('debug1').innerHTML='slide: '+v},

onChange:function(v){$('debug1').innerHTML='changed! '+v}});

// ]]>

</script>

Using the CDATA section sidesteps issues encountered when using characters like < and > in your JavaScript. The code creates a new Slider control (via the Control class) and sets its initial position to the middle of the control (0.5) and adds handlers for the slide and change events. Also, framework functionality is easily used via onClick events.

A drawback of many freely available (and some commercial) tools is a lack of documentation and examples. The scriptaculous framework includes extensive example code and basic documentation via its Wiki. In addition, a quick Google search yields more help. A good example is the various cheat sheets available that provide a quick reference sheet for using the framework.

The framework includes an extensive set of examples that are included in the functional subdirectory of the test directory. You can dive into the test files to get a good idea of how to use framework functions within your application. In addition, the demos section of the scriptaculous Web site provides great examples.

Standard
development

Ant – an introduction

Ant is a Java based build tool developed as part of the Apache Jakarta project. You can get it from the Ant home site: ant.apache.org. At first the usefulness of Ant may not be readily apparent, but after using it for awhile on even small projects you may be surprised at how much you come to rely on it. For example, the ability to build files into specific directories, generate JavaDoc and package classes into JAR files for deployment all in one keystroke is extremely powerful. Here is a non-exhaustive list of what Ant can do:

  • Extract source from a version control system
  • Create directories
  • Delete directories
  • Compile code
  • Generate JavaDoc
  • Jar files
  • Copy files
  • Generate e-mail
  • FTP files
  • Execute SQL statements
  • Run unit tests

After downloading and unzipping the download contents, copy the Ant directory to the root of your C:\ drive, so the path is “C:\Ant”. You can install it anywhere you want, but this is most convenient. We also have to set up some environment variables so that the system can find Ant when we need it. You need to add System Variable called ANT_HOME, set this to the directory where you put Ant, in this case “C: \Ant”. Make sure there is also a System Variable called JAVA_HOME that point to your Java SDK directory.

We’re almost done. Now all you have to do is add the above variables to your path. Look for the “PATH” environment variable under System Variables and click “Edit”. Add this to the end of the path:

;%JAVA_HOME%\bin;%ANT_HOME%\bin

Notice that entries in the path on Windows are delimited by “;”. Now restart your machine to make sure the environment variables stick. We’re almost ready to test our installation. Open up a command window and type: ant. If the above steps went well, then you should see your first Ant error message:

D:\>ant

Buildfile: build.xml does not exist!
Build failed

This means that the installation worked. If you got anything other than this, then more than likely one of the above installation steps weren’t performed.

Ant requires a couple of things to run: Java source files (obviously), and a build file. First we’re going to create a really simple Java program for Ant to build.

public class AntTest{
public AntTest(){
System.out.println(“Isn’t Ant cool?”);
}

public static void main(String[] args){
new AntTest();
}
}

Don’t try to compile it yet, we’re gonna let Ant do that. The next thing we need is the build file.

<project name=”AntExamplel” default=”dist” basedir=”.”>
<!– set global properties for this build –>
<property name=”src” value=”.”/>
<property name=”build” value=”build”/>
<property name=”dist” value=”dist”/>

<target name=”init”>
<!– Create the time stamp –>
<tstamp/>

<!– Create the build directory structure used by compile –>
<mkdir dir=”${build}”/>
</target>

<target name=”compile” depends=”init”>
<!– Compile the java code from ${src} into ${build} –>
<javac srcdir=”${src}” destdir=”${build}”/>
</target>

<target name=”dist” depends=”compile”>
<!– Create the ${dist}/lib directory –>
<mkdir dir=”${dist}/lib”/>

<!– Put everything in ${build} into the AntTutorial-${DSTAMP}.jar file –>
<jar jarfile=”${dist}/lib/AntExample-${DSTAMP}.jar” basedir=”${build}”/>
</target>

<target name=”clean”>
<!– Delete the ${build} and ${dist} directory trees –>
<delete dir=”${build}”/>

<delete dir=”${dist}”/>
</target>
</project>

Make sure that you saved the build.xml file in the same directory as the Java source file. We’re not going to get into what the build file is actually doing yet, so just trust me…

Now, in your command window, cd to the directory where the Java source and the build file are saved (a lot of tutorials leave this step out, strangely enough) and type “ant“. Hopefully you will see the BUILD SUCCESSFUL message at the bottom. Now check out the directory. You’ll notice that there are two new directories: “build“, and “dist“. These directories were built by Ant. The “build” directory will include the compiled Java class file(s) and the “dist” directory will contain a .jar file with our project name and a timestamp.

Reference: http://ant.apache.org/manual/index.html

Tags: , ,

Standard
design, development

The Singleton Pattern

A design pattern is a general solution for a common problem in software design. The idea is that the solution gets translated into code and applied in different situations where the problem occurs.

One of the commonly used creational patterns is the Singleton pattern. It describes a technique for ensuring that only a single instance of a class is ever created. The technique takes the following approach: don’t let anyone outside the class create the instance of the class. Typically, singletons are created to reduce the memory requirements. You can implement this approach in many different ways.

One of the ways is to make the constructor of the class private or protected and providing a static method which returns an object of the class. By this you can guarantee that only one instance is shared among all. Also, if you know the one instance being created will be the subclass, make the parent class abstract and provide a method to get the current instance. Similar ways of restricting class creation can be found throughout the J2SE standard libraries.

At this point you might think that restricting access to a constructor automatically makes it a Singleton. It doesn’t. An example for that is the Calendar class. The Calendar class constructor is protected, and the class offers a getInstance () method to get an instance of the class. However, each call to getInstance () method gets a new instance of the class. So that is not singleton.

When you create your own Singleton class, make sure that only one instance is ever created:


public class MySingleton{
    private static final MySingleton INSTANCE = new MySingleton ();
    private MySingleton () { }
    public static final MySingleton getInstance() {
        return INSTANCE;
    }
}

The static method, getInstance (), returns the single instance of the class. Note that even if the single instance needs to be a subclass, you don’t have to change the API.

Theoretically, you don’t need the getInstance () method because the INSTANCE variable could be public. However, the getInstance () method provides the flexibility in case of future system changes.

The Singleton pattern is useful if you know you only have a single resource, and need to share access to the state information of that single instance. Identifying the need for the Singleton pattern at design time can simplify development. However, some times you are not aware of the need until a performance problem leads you to refactor code and use the pattern at a later time. For example, you might discover that system performance is degrading because your program is creating instances of the same class to pass the state information. By changing to the Singleton pattern, you avoid recreating the same object. This frees up time the system uses to recreate the object, and saves the time the garbage collector needs to free those instances.

In short, use the Singleton pattern when you want to ensure that one, and only one, instance of the class is ever created. If your constructor doesn’t require any operations, provide an empty private constructor (or a protected constructor if you need to subclass). Otherwise, by default, the system will provide a public constructor, something you don’t want when working with a Singleton pattern.

Standard
development, technology

Software development process

A software development process is a structure imposed on the development of a software product. Synonyms include software life cycle and software process. There are several models for such processes, each describing approaches to a variety of tasks or activities that take place during the process.

All methods undertake the seven steps listed to different degrees:

Domain Analysis
Often the first step in attempting to design a new piece of software, whether it is an addition to existing software, a new application, a new subsystem or a whole new system, is what is generally referred to as “Domain Analysis”. Assuming that the developers (including the analysts) are not sufficiently knowledgeable in the subject area of the new software, the first task is to investigate the so-called “domain” of the software. The more knowledgeable they are about the domain already, the less the work required. Another objective of this work is to make the analysts who will later try to elicit and gather the requirements from the area experts or professionals, speak with them in the domain’s own terminology and to better understand what is being said by these people. Otherwise they will not be taken seriously. So, this phase is an important prelude to extracting and gathering the requirements. The following quote captures the kind of situation an analyst who hasn’t done his homework well may face in speaking with a professional from the domain: “I know you believe you understood what you think I said, but I am not sure you realize what you heard is not what I meant.

Software Elements Analysis
The most important task in creating a software product is extracting the requirements. Customers typically know what they want, but not what software should do, while incomplete, ambiguous or contradictory requirements are recognized by skilled and experienced software engineers. Frequently demonstrating live code may help reduce the risk that the requirements are incorrect.

Scope Analysis
Once the general requirements are gleaned from the client, an analysis of the scope of the development should be determined and clearly stated. This is often called a scope document. Certain functionality may be out of scope of the development project as function of cost, others as a result of unclear requirements at the time the development has begun. If the development is done externally, this document can be considered a legal document so that if ever there are disputes, any ambiguity of what was promised to the client can be clarified.

Specification
Specification is the task of precisely describing the software to be written, possibly in a rigorous way. In practice, most successful specifications are written to understand and fine-tune applications that were already well-developed, although safety-critical software systems are often carefully specified prior to application development. Specifications are most important for external interfaces that must remain stable. A good way to determine whether the specifications are sufficiently precise is to have a third party review the documents making sure that the requirements are logically sound.

Software architecture
The architecture of a software system refers to an abstract representation of that system. Architecture is concerned with making sure the software system will meet the requirements of the product, as well as ensuring that future requirements can be addressed. The architecture step also addresses interfaces between the software system and other software products, as well as the underlying hardware or the host operating system.

Coding
Reducing a design to code may be the most obvious part of the software engineering job, but it is not necessarily the largest portion.

Testing
Testing of parts of software, especially where code by two different engineers must work together, falls to the software engineer.

Implementation
After the code is appropriately tested and approved, it is moved into production environment i.e. is made available for business use.

Documentation
An important (and often overlooked) task is documenting the internal design of software for the purpose of future maintenance and enhancement. Documentation is most important for external interfaces.

References:

Computer World, 2002, Retrieved on June 22, 2006 from the World Wide Web: http://www.computerworld.com/developmenttopics/development/story/0,10801,71151,00.html

Software Development Process Advice and Strategies

Software development life cycle (SDLC) [visual image], software development life cycle

Standard