Skip to content

Agile: Definition, Pillars and Adoption

What is Agile Software Dev (ASD)?

First let’s start with the basics: Dictionary definition of agile:

Something that is agile is “Characterized by quickness, lightness, and ease of movement; nimble.” i.e. able to change quickly and easily.

In software application development; ASD means to have processes in place that will allow software teams to react to changing requirements in a rapid way. A practitioner of agile can use different methodologies within several frameworks to “be” agile.

Agile Software Development’s guiding principle focuses on keeping code simple, testing often, and delivering bits of functionalities soon as they’re ready. The goal of ASD is to build upon small client-approved parts as the project progresses; that is as opposed to delivering one large application at the end of the project.

There are various methodologies that are collectively known as agile. They all promote the values of the agile manifesto and they are consistent with the above principles.

Some of the more known methodologies are:

  • Adaptive Software Development
  • Agile Data Methods
  • Agile Modelling
  • Agile Unified Process (UP)
  • Crystal
  • Dynamic Systems Development Method (DSDM)
  • eXtreme Programming
  • Feature-Driven Development (FDD)
  • Lean Development
  • Microsoft Solution Framework for Agile
  • Six Sigma
  • Scrum
  • Test-Driven Development

Why Agile?

“— accept that the project’s goal is a moving target —“

There are many reasons to why software teams should consider agile processes for their development but the one reason that stands out the most for me is that writing formal project specs is hard, time consuming + never complete. There is a trail of thought which says …“software cannot be completely specified through documentation or a model” and I agree with this especially for large projects.

–          …people don’t know and cannot completely visualize what the software should be like till they actually play with it

–          … a document can have plenty of information, but real knowledge is hard to put on paper; complete, rigid specifications are never complete

–          …communication is never perfect and correction through feedback loop is essential

–          … accept that most project will have changing requirements that evolve over the project life span

Moreover agile development can be exciting and invigorating for software teams whereby they are not just working of specs. Collaboration with end users is generally one of the things I find most rewarding about the job.

Pillars of Agile:

–      Early collaboration between all stakeholders

–      Active user involvement throughout the project

–      Clear vision of needs, solutions and value

–      Capture requirements at a high level; user stories is beneficial + low cost.

–      Focus on simple solutions rather than complex solutions with features that may or may not be used

–      Don’t try to predict future features

–      Develop small, incremental releases frequently

–      Early delivery of “good enough” features better than “perfectly” with later on.

–      Testing should be done continuously in parallel to development (test automation imperative) – test early and often

Migration to agile:

Over the years increasing development teams have started to adopt agile methods and there have been many success stores…

In reality, though, agile is not a magic bullet that will solve all software development issues in your projects.

Adoption of agile is a big decision that mustn’t be taken lightly regardless of the methodologies or techniques to be employed. Understand the dynamics and pillars of agile techniques is vital.  (Cherry picking won’t cut-it).

Whichever technique chosen; time MUST be given to map out the correct infrastructure/procedures to be used before jumping into the agile bandwagon.

One last thing to point; getting management buy-in is very important as often that could the major stumbling block.

Advertisements

Inheritance or Composition

One of the fundamental activities of any software system design is establishing relationships between classes. The two fundamental ways to relate classes are inheritance and composition.

Quite often the most common approach to gain access to class members and methods of a class is to extend the class. This is mainly due to the fact when we are introduced OO programming one of the main themes that most people get very excited about is inheritance. But using extends without careful consideration could be costly. Quite often the relationship between your classes is more suited for composition (i.e. a “has-a” relationship).

I remember when I was creating a cards game application; I needed access to players object in the canvas and mechanically just extended the players. Composition in that instance would have the correct approach to choose.

Inheritance: advantages Inheritance: disadvantages
+ Dynamic binding (i.e. allowing the JVM to decide at runtime which method implementation to invoke). When used in the right place the prime benefit of dynamic binding is that the code becomes much easier to change.

+ Polymorphism (capability of holding superclass or any of its subclasses)

– Superclasses are considered to be “fragile”; incorrect use of extends and one little change to a superclass can ripple down and require changes in many other places in the application’s code.
Composition: advantages Composition: disadvantages
+ Provides stronger encapsulation because a change to a back-end class needn’t break any code that relies only on the front-end class. – The explicit method-invocation forwarding (or delegation) MIGHT have a performance cost as compared to inheritance’s single invocation.

– The bigger downside is that is that it is not as light-weight in Java.

To Summarize:

One thing to consider is that if your goal is code reuse think composition as it provides a better approach that yields easier-to-change code. Don’t use inheritance just to get code reuse. An important question to ask yourself when you think you have a “is-a” relationship is whether that “is-a” relationship will be constant throughout the lifetime of the application and, with luck, the lifecycle of the code.

In general, over the years I become to favour composition over inheritance. I’ve seen too many projects; some of my own; get incredibly and unnecessarily confusing due to complicated inheritance hierarchies so deep that will make your eyes water. However, there are some cases where inheritance simply makes more sense logically and programmatically. These are typically the cases where an object has been broken into so many subcomponents that it doesn’t make sense any more as an object itself.

Joshua Bloch Nugget: Design and document for inheritance or else prohibit it. When designing for inheritance you are committing FOREVER to the self-use patterns.

 

Modal dialogs

JavaScript dialogs (usual suspects)

You’ve undoubtedly seen them, used them, and most likely gotten annoyed by them but nevertheless dialogs are fundamental part of websites. They enable interactivity with the end user and so forth …

The usual suspects

alert(), confirm(), prompt()

To certain extent the built in standard JS dialogs can achieve a certain level of interactivity but they only go so far. For example if you want to give the end user a list of choices before a “confirm” such a task cannot be done with ordinary confirm() or even the prompt dialog.

Enter modal dialogs

Definition of a modal dialog as taken from Wikipedia

“A modal window is a child window that requires users to interact with it before they can return to operating the parent application, thus preventing the workflow on the application main window.”

What that means to me is a div or any other container element superimposed on the window using css z-index.

The z-index property gives HTML pages (normally two-dimensional) a third dimension; it was introduced in CSS 2.1 February 25, 2004 candidate recommendation. In addition to the horizontal and vertical positions, elements also have “z-axis” which allows them to lay on top of each other. An element with greater z-index will always appear in front of an element with a lower Z-index order.

The idea here is to “inactivate” all the elements in an html document and present a dialog which must be “processed” by the user before any other actions can be taken.

Creating modal dialog (easy guide)

The CSS

/* This is the holder element; any divs within this element will be superimpose in the page*/

#myElement

{
z-index: 100;

position: fixed;

left: 0;

top: 0;

width:100%;

height:100%;
}

Note: the positioning is required to ensure that this div covers the entire page.

The HTML

Step 1: Create the holder div


<div id="myElement "></div>

Step 2: Div that will contain the content

</pre>
<div id="myElement ">

<div>ANYTHING HERE HAS A GREATER INDEX </div>

</div>
<pre>

Example 1

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>JavaScript Modal Example 1</title>
<style type="text/css">
/* This is the hidden div*/
#confirmationOverlay
{
z-index: 1000;
background-color:    #DBDBDB;

position: fixed;
left: 0;
top: 0;
width:100%;
height:100%;
}

#confirmationOverlay div
{
width:400px;
margin: 100px auto;
border:1px solid #000;
padding:15px;
text-align:center;
background-color:#FFF;
}
</style>

<script>
function proceed()
{
var element = document.getElementById('confirmationOverlay');
if (element != null)
{
element.style.display = (element.style.display == "none") ? "block" : "none";
}
}
</script>

</head>
<body>

<h1>Examle 1</h1>

<blockquote>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
<p><a href="#" onClick="proceed()"><img src="images/proceed.png" style="border: none;" /></a></p>
</blockquote>

<!-- This is a hidden div that will be toggled; thanks to z-index it will superimpose itself -->
<div id="confirmationOverlay" style="display:none;">
<div>
<p>Are you ready to check in...?</p>
<p>
<a href="#" onClick="proceed();"><img src="images/OK.png" style="border: none; width:100px; hieght:70px;" /></a>
<a href="#" onClick="proceed();"><img src="images/Cancel.png" style="border: none; width:100px; hieght:70px;" /></a>
</p>

<p id="loadingImg" style="display:none;"><img src="images/loading.gif" style="border: none;" /></p>
</div>
</div>

</body>
</html>

Example 2

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>JavaScript Modal Example 2</title>
<link rel="stylesheet" href="css/general.css" />
<script type="text/javascript" src="js/script.js" ></script>

</head>
<body>

<h1>Examle 2</h1>

<blockquote>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
<p><a href="#" onClick="proceed('confirmationOverlay')"><img src="images/proceed.png" style="border: none;" /></a></p>
</blockquote>

<!-- This is a hidden div that will be toggled; thanks to z-index it will superimpose itself -->
<div id="confirmationOverlay" style="display:none;">
<div>
<p>Are you ready to check in...?</p>
<p>
<a href="#" onClick="checkIn('loadingImg');"><img src="images/OK.png" style="border: none; width:100px; hieght:70px;" /></a>
<a href="#" onClick="cancel('confirmationOverlay');"><img src="images/Cancel.png" style="border: none; width:100px; hieght:70px;" /></a>
</p>

<p id="loadingImg" style="display:none;"><img src="images/loading.gif" style="border: none;" /></p>
</div>
</div>

</body>
</html>

 

/* This is the hidden div*/
#confirmationOverlay
{
z-index: 1000;
position: fixed;
left: 0;
top: 0;
width:100%;
height:100%;
}

#confirmationOverlay div
{
width:400px;
margin: 100px auto;
border:1px solid #000;
padding:15px;
text-align:center;
}

/* Text styling */

.confrimTxt
{
font-weight:normal;
font-variant:small-caps;
color:#000000;
letter-spacing:4pt;
word-spacing:10pt;
font-size:10px;
font-family:arial, helvetica, sans-serif;
line-height:1;
}

blockquote
{
display: block;
padding: 0 60px;
width: 350px;
}

blockquote:before, blockquote:after
{
color: #4AA02C;
display: block;
font-size: 700%;
width: 50px;
}

blockquote:before
{
content: '\201C';
height: 0px;
margin-left: -0.55em;
}

blockquote:after
{
content: '\201D';
height: 50px;
margin-top: -80px;
margin-left: 3.10em;
}
function proceed(id)
{
toggleDiv(id);
hideProgressImg();
}

function checkIn(id)
{
toggleDiv(id);

// Do checks, make AJAX call etc.
}

function cancel(id)
{
toggleDiv(id);
hideProgressImg();
}

function toggleDiv(id)
{
var element = document.getElementById(id);
if (element != null)
{
element.style.display = (element.style.display == "none") ? "block" : "none";
}
else
{
alert("Cannot find element with id:"+id);
}
}

function hideProgressImg()
{
document.getElementById('loadingImg').style.display = "none";
}

You got to love jQuery

You got to love jQuery. If you familiar with jQuery you won’t be surprised to know that modal functionality is already implemented for you in that fun packed library. There are plenty of very good tutorials that you can try out. With jQuery I found that once you get the hang of the fundamentals its plain sailing from there onwards.

Oracle Security Seminar

This morning I was at a security seminar host by Oracle and I just wanted to talk about some of the interesting points raised.

To my surprise what I found that there are quite a few sites out there that haven’t even bothered to take basic steps to ensuring their site is secure. A lot of hackers still succeed with simple URL manipulation and directory traversal. Just goes to show RTFM of your server could save you a lot of headache.

Another common source of hacks was to use that hidden harmless backup files that nobody cares about. If you are used to UNIX systems you know that backed-up files end might end with ~. Well that’s another point of attack. Say for example you have a php file (user_account.php) with the frist few lines connects to the DB and the script goes on to return user information. Potentially the file could start with something like:


<?php

$dbhost = 'localhost';

$dbuser = 'root';

$dbpass = 'password';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die  ('Error connecting to mysql');


Calling the php file over the web server will return html and you won’t even know about the db connection but what happens if someone had left a backup of that file named user_account.php.bak? Or easily done if modified the file in VIM whereby it will create a backup called user_account.php~.  Well calling either user_account.php~ or user_account.php.bak your web server won’t know how to render such requests and will default to plain text…. and voila DB code right there. Proper version control and basic web server configuration could easily prevent this.

The more interesting hacks involved XSS (abbreviation for Cross Site Scripting) and what it comes down to is properly escaping all forms fields that is including files uploads. Even better use a framework that does this for you (i.e. Struts output mechanisms such as <bean:write … >, or in <c:out … > use the default JSTL escapeXML=”true” attribute). The problem with XSS is that some genuine tool use that technique to embed valid scripts on clients machines; Google Analytics is one of them if am not mistaken.

Concluding the relative easy which one was able to infect a site was truly amazing and the advent of social networks the spread of these attack serve only to inflame the situation. Developers need to be educated and trained to prevent hacker exploit these basic techniques.

The second part of the seminar was a sales pitch so the less about that the better ;).

Encapsulation; there is a reason

NEVER make instance fields public

One of the most important factors that distinguish a well designed module from poorly designed ones is the degree which the module hides its internal data and implementation details from other modules. This is one of the guiding principles for encapsulation

Minimize ripple effects by hiding information

As a general rule of thumb when creating new methods or members initially make them as inaccessible as possible. Later if required to change the access; take a step back and think closely at your design. IMHO it is always a good idea to declare instance fields as private unless there is a good reason for not doing so.

De-encapsulate pitfalls…

So let’s examine what are the potential pitfalls by not declaring instance fields as private.

To demonstrate we are going to employ a SolarSystem.class. This simple class contains a static list of planets and two methods; one to display the planets displayPlanet the other getDwarfPlanet to return the dwarf planet of ‘Pluto’.

public class SolarSystem
{
  // The instance variable is should NEVER be made.
  public static List<String> planets = new ArrayList<String>();

  static
  {
    planets.add("Mercury");
    planets.add("Venus");
    planets.add("Earth");
    planets.add("Mars");
    planets.add("Jupiter");
    planets.add("Saturn");
    planets.add("Uranus");
    planets.add("Neptune");
    planets.add("Pluto");
  }

  // IAU dropped 'Pluto' in August 2006 in favour of new classification of dwarf planets.
  public static String getDwarfPlanet()
  {
    return planets.get(9); // Admittedly bad way of doing this.
  }

  // Displays all planets.
  public static void displayPlanet()
  {
    for (String planet : planets)
    {
      System.out.println(planet);
    }
  }

  public SolarSystem()
  {

  }

}

With the code above it’s very possible for any class in the application to remove ‘Pluto’ from the list of planets.

Because the planets field is public you have just lost the ability to constrain the values in that field. The values of planets can be changed from any other class in your application; and with larger applications you are getting yourself into a whole new world of pain.

public class Application
{

  private Application()
  {

  }

  public static void main(String[] args)
  {
    SolarSystem.displayPlanet();
    removePlanet("Pluto"); // Wait 'Pluto' isn't a planet anymore; we to remove it.

    // do some other fancy stuff ...
    // and more fancy stuff ...

    //So far so good ... but the following method call breaks.
    SolarSystem.getDwarfPlanet();

   /*
   * An IndexOutOfBoundsException is thrown: Index: 9, Size: 8
   */
  }

  // Removes a planet with a given name.
  public static void removePlanet(String name)
  {
    SolarSystem.planets.remove(name);
  }
}

Running SolarSystem.getDwarfPlanet() in this instance would result in IndexOutOfBoundsException to be thrown.

Aha use Getter methods!!

public class SolarSystem
{
  // The instance variable is should NEVER be made.
  private static List<String> planets = new ArrayList<String>();

  ....

  public List<String> getPlanets()
  {
    return planets;
  }
}

Well, not quite. A common approach you might think is to user getter and setter methods. We could declare our planet list as private and have a getter method but this doesn’t exactly solve our problem.  The getter method only returns a reference to the private field hence we can still modify the reference.

Think Encapsulation

This is more about the design choice rather than coding. The planets list contains a list of planets that are part of the internal working of the Solar System class and hence it should be declared as private. Once we’ve declared the planets list as private we have effectively removed any possibility of a class other than our SolarSystem class to change the values in our list. Although the example used is very trivial you can easily imagine a more complex situation whereby other external modules are accessing and manipulating the list of planets at free will, debugging issues becomes very hard.

hashCode() method contract violation.

Proper object hashCode overriding

If you have ever overridden Object.equals() without overriding Object.hashCode() read on…

The Background

In this post I am going to explain why the Object.hashCode() method must be overridden for every class that overrides Object.equals.

One of the most common sources of bugs that I have seen is developers disobeying Object.hashCode() contract. Examples on the web aren’t much better so be careful you do not fall into this pitfall. The contract as taken from the Java SE 6 spec states the following:

  1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode() method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  3.     It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Failure to obey this can have dire effects that are not so easily spotted at start. Below is a simple address.java class; with the Object.equals() method overridden correctly so that two objects are the same if the ‘flat number‘, ‘street‘ and ‘postcode‘ are the same.

Address.class

public class Address
{
  private final int flatNumber;
  private final String street;
  private final String postcode;

  public Address(int flatNumber, String street, String postcode)
  {
    this.flatNumber = flatNumber;
    this.street = street;
    this.postcode = postcode;
  }

  @Override
  public boolean equals(Object obj)
  {
    if (obj == this)
    {
      return true;
    }

   if (obj instanceof Address)
   {
     // Compare of fields relevant to composing an address.
     // If all the fields are the same then these objects are the same.
     Address address = (Address) obj;

     if (address.flatNumber == flatNumber &&
        address.street.equals(street) &&
        address.postcode.equals(postcode))
     {
       return true;
     }
   }

   return false;
  }

  public static void main(String[] args)
  {
    Address address1 = new Address(10, "Lambeth High Street", "SE1 7JN");
    Address address2 = new Address(50, "Lime Street", "EC3A 1AA");
    Address address3 = new Address(10, "Lambeth High Street", "SE1 7JN");

    if (!address1.equals(address2))
    {
      System.out.println("address1 is NOT eqaul to address2");
    }

    if (address1.equals(address3))
    {
      System.out.println("address1 is eqaul to address3");
    }
  }
}

So far so good

So far so good; nothing seems out of the ordinary. Comparing objects of the same type is returning true as expected. But the problems start when we start collecting objects in a collection.

Say for example we have the following code to collect a bunch of address and we apply the get method.

Map<Address, String> map = new HashMap<Address, String>(); // Note the use of generics.
map.put(address1, "Tom");
map.put(address2, "Dick");

// Both addrress1 and address3 point to the same object in memory.
// Hence we should be able to get at object by either of these two variables.
String name = map.get(address3);

if (name == null)
{
  System.out.println("Why oh why is this null.....");
}
else
{
  System.out.println("Name:"+name);
}

Oh didn’t expect that !

REASON: Failure to override Object.hashCode() causes two equal object to have unequal hash code; and since the set.getMethod() requires this to be true we get a ‘null‘ (or in truth an indeterministic behaviour).

Solution

Proper overriding of the Object.hashCode() method as showen below:

@Override
  public int hashCode()
  {
    // OK so I could have though of more inventive ways of creating a hashcode for the above class but still you get the jist of it.
    return flatNumber * (street.hashCode() + postcode.hashCode());
  }

 

Hope you enjoyed this post … any questions/corrections feel free.

Java get cookie method

Java has an abundance of methods for handling cookies. Given a HttpServletRequest one can use the useful getCookies() method.

This method returns an array of cookie objects.

The bare essentials:

public static String getCookieValue(HttpServletRequest request, String name)
{
  Cookie[] cookies = request.getCookies();
  for (Cookie cookie : cookies)
  {
    if (cookie.getName().equals(name))
      return cookie.getValue();
  }

  return "";
}

The below code shows this would work in a Utils method:

/**
* Gets cookie value based for a given cookie name.
*
* @param request the actual HttpServletRequest object which holds the request header information.
* @param name a string for the name of the cookie been requested.
* @return Either an empty string if no such cookie is found or the actual value of the cookie.
* @throws IllegalAccessException
*/
public static String getCookieValue(HttpServletRequest request, String name) throws IllegalAccessException
{
  // Be good check your parameters first.
  if (request != null && name != null && !name.equals(""))
  {
    // Here we return all cookie object. If no cookie was set then will be an empty array.
    Cookie[] cookies = request.getCookies();

   // Loop through each cookie.
   for (Cookie cookie : cookies)
   {
     if (cookie.getName().equals(name))
     {
       // Return value if the name is matched.
      return cookie.getValue();
     }
   }
 }
 else
 {
   // Incorrect parameter list.
   throw new IllegalArgumentException();
 }

 // I will be doing another post on Log4J logger; you can live without this just print to the console.
 logger.warn("No such cookie with name:"+name+" returned empty string by default.");

 return "";
}

One caveat is if you are using an IDE to test this code most IDEs (as Eclipse did) will ignore any system classpath, and rely on project-specific settings. You will need to add external JARs to your project path.