Sunday, 28 July 2013

Principles of Package Design

Agile Software Development is really an incredible book. After reading it, a lot had been talked about the Object-Oriented Principles on this blog . Today, I’ll be talking about another section of the book, which introduces principles used to maintain high package cohesion and a desirable package dependency, known as Principles of Package Design.
Packages are used to organize larger projects. More than this, they are containers of classes used to manage the development and distribution on software. Package’s goal is separate classes in an application according to some criteria. However, classes often have dependencies on other classes, creating package dependencies relationships. To help manage this situation, some principles were created to govern the creation, interrelationship and use of packages.
The three principles in sequence are related to package cohesion, useful in deciding how to partition classes into packages.
The Reuse-Release Equivalence Principle (REP): the granule of reuse if the granule of release
REP states that anything that we reuse must also be released and tracked. Reusability is not only the creation. It comes only after there is a track system in place that offers the guarantees of support that reusers will need. Since reusability is based on packages, if some software is going to be reused, then it must be partitioned in a convenient structure for this purpose, so all classes in a package become reusable by the same audience.
The Common-Reuse Principle (CRP): the classes in a package are reused together
CRP helps in deciding which classes should be placed into a package. This can be determined by reuse characteristics. Classes that tend to be reused together should be placed in the same package. Remember: if you reuse one class in a package, you reuse them all. Although the CRP tells us what classes put together, it also says what classes do not put in the same package. If a class depends on another class in a different package, it depends on the entire package. Every time the used package is released, the using package must be revalidated and rereleased, even the change was made in a different class that the using package depends on. Therefore, CRP also says that classes which are not tightly related to each other should not be in the same package, so every time I depend on a package, I depend on every class in that package.
The Common-Closed Principle (CCP): a change that affects a package affects all the classes in that package and no other packages.
This is the same as SRP, but applied for the packages context. Such as classes should have just one reason to change, CCP states that packages should not have multiple reasons to change. It’s preferable that changes occur in just one package rather than distributed along the whole system.
Now, we are going to take a look at principles related to package relationship and dependency.
The Acyclic-Dependencies Principle (ADP): allow no cycles in the package-dependency graph.
Package cycles create immediate problems, and the most obvious one is when you have to release a package that was modified. In order to release the package, it must be compatible with all other packages that it depends on. A cycle in your package-dependency graph makes release harder since you increase the number of packages that you have to be compatible with. For example, take the Figure 1 and Figure 2. To release package C in the first situation we must be compatible with package E and F. However, in the second case we also must be compatible with package A, B and D. Even worst, if you want to test package C, we must link and build all other packages in the system, instead of just two of them.
no-cycle
To break the cycle, two solutions are suggested:
  1. apply Dependecy-Inversion Principle.
  2. create a new package between C and A, and move the classes that they both depend on into that new package.
The Stable-Dependencies Principle (SDP): depend in the direction of stability.
Stability has nothing directly to do with frequency of change, but to the amount of work required to make the change. In software, package stability is measured in number of classes inside this package that depend on classes outside this package and number of classes outside this package that depend on classes within this package. Thus, a package is called instable if it is easy to change, in other words, just a few or none packages have dependency relationship with it. A package is called stable if it is hard to change, or a lot of classes outside this package depend on it. The book also brings a method to calculate stability metrics, but I’ll not be such detailed. Just have in mind that a good design contains some instable package and some stable package. Instable packages are on top and depend on stable packages at the bottom, just shown below.
figura1
The Stable-Abstractions Principle (SAP): a package should be as abstract as it is stable.
This principle states that a stable package should also be abstract so that its stability does not prevent it from being extended, and an instable package should be concrete since its instability allows the concrete code within it to be easily changed. Thus, stable packages consist of abstract classes and instable packages of implementations classes.
Conclusion
After some posts of OOP, we already know how to create a good class design. However, in big systems, classes are separate into packages which corresponds a very important part of the system’s release and deploy. So, a new concern is how to divide classes between packages and maintain the system’s consistency. In this post we introduced six principles explained in Robert Martin book which help us in solve a lot of package design problems. You can find a lot of more information in the book, which I strictly recommend.
See you,

Singleton (Anti-) Pattern

I’ve implemented my first design patterns at college, while creating a web system during the software engineer course. My classmates and I needed a facade class with a single instance of it throughout the system. So, because we’re really smart, we’ve applied the Facade and Singleton pattern. Actually, we’ve implemented the patterns without knowledge of the design patterns catalog. For us, it was just a way to get what we need.
This week, while doing my daily work, I realized how dangerous the Singleton pattern is. Well, I would have noticed it before, if I have used Test-First Programming. Even knowing the benefits of TDD, I decided to write some code in advance, since I don’t have much experience on the platform used and on its supported tests framework.
My task was to create a GPS abstraction and use it in a mobile Navigator module. My first thought was making my GPS abstraction a Singleton class. It looked very obvious for me: a mobile device has only one GPS and different GPS intances will provide the same data set. So, what I need is just a single GPS instance troughout the system.
After some minutes writing code, I’ve created abstractions similar to the Java sample below.
GPSProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.List;
 
public class GPSProvider implements LBSPositionObserver {
 
 private static GPSProvider INSTANCE = new GPSProvider();
 private Position lastCoordinate;
 private List<GPSListener> listeners;
 
 private GPSProvider() {
 this.listeners = new ArrayList<GPSListener>();
 }
 
 //retrive the class instance
 public static GPSProvider GetInstance() {
 return INSTANCE;
 }
 
 // perform GPS initialization
 public void initGPSService() {
 (...)
 }
 
 // add a new listener to the gps class
 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }
 
 // remove a listener from the class list
 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }
 
 @Override
 // set lastCoordinate and notify all listeners about the update
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }
 
 @Override
 // notify all listener about the update
 public void setStatus(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }
 
 // return the last known coordinate
 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }
 
}
GPSListener.java
1
2
3
4
5
6
7
public interface GPSListener {
 
 void positionUpdated(Position position);
 
 void statusUpdated(int status);
 
}
LBSPositionObserver.java – native GPS interface
1
2
3
4
5
6
7
public interface LBSPositionObserver {
 
 void positionUpdated(Position position);
 
 void setStatus(int status);
 
}
Navigator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Navigator implements GPSListener {
 
 private NavigatorObserver observer;
 
 public Navigator(NavigatorObserver observer) {
 this.observer = observer;
 }
 
 // start navigation by listening to gps updates
 public void navigate(Route route) {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.attach(this);
 }
 
 // pause navigation by not receiving gps updates
 public void pause() {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.dettach(this);
 }
 
 @Override
 // everytime the position is updated, the navigator gives directions if needed
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }
 
 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }
 
 // calculate if achieved destination
 private boolean achievedDestination() {
 (...)
 }
 
 // verify is have to change direction
 private int verifyStepUpdated() {
 (...)
 }
 
 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}
Now, since I’ve finished my Navigator module, I want to test it to make sure it’s working correctly. In order to test the Navigator module, I need a GPS data log and a route to walk through it, simulating a person walking and being navigated by the system. The route is not a problem because I pass it as a parameter of “navigate” method. However, there is no way to simulate a GPS log with the code above, unless I use some Dependency Injection Framework, which is not the case.
That’s the Singleton disadvantage. I can’t inject a GPS mock in my Navigator module because I always use the native gps implementation represented in my Singleton GPSProvider class. Everytime I need some GPS information, I use the GPSProvider.GetInstance() static method to retrieve the only GPS instance I have access to.
To solve this problem, I found a simple solution: not using Singleton. I removed  the Singleton pattern from GPSProvider and change every class that uses GPSProvider.GetInstance() to receive the current GPS intance. In the Navigator module, I passed the GPS instance through its class’ constructor.
GPSAbstractProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.ArrayList;
import java.util.List;
 
public abstract class GPSAbstractProvider {
 
 private List<GPSListener> listeners;
 
 public GPSAbstractProvider() {
 this.listeners = new ArrayList<GPSListener>();
 }
 
 public abstract void initGPSService();
 
 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }
 
 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }
 
 public void notifyPositionUpdated(Position position) {
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }
 
 public void notifyStatusUpdated(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }
 
}
GPSProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class GPSProvider extends GPSAbstractProvider implements LBSPositionObserver {
 private Position lastCoordinate;
 
 private GPSProvider() {
 super();
 }
 
 @Override
 // perform GPS initialization
 public void initGPSService() {
 (...)
 }
 
 @Override
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 this.notifyPositionUpdated(position);
 }
 
 @Override
 public void setStatus(int status) {
 this.notifyStatusUpdated(status);
 }
 
 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }
 
}
Navigator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Navigator implements GPSListener {
 
 private NavigatorObserver observer;
 private GPSAbstractProvider gps;
 
 public Navigator(NavigatorObserver observer, GPSAbstractProvider gps) {
 this.observer = observer;
 this.gps = gps;
 }
 
 public void navigate(Route route) {
 this.gps.attach(this);
 }
 
 public void pause() {
 this.gps.dettach(this);
 }
 
 @Override
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }
 
 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }
 
 private boolean achievedDestination() {
 (...)
 }
 
 private int verifyStepUpdated() {
 (...)
 }
 
 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}
Much better! Notice that I still have just one single instance of my GPS class. All I have to do is creating my GPS at the beginning of the program and pass it through classes that use it.
Doing this, testing my code became very simple. I inject my GPS mock to simulate GPS data in my tests,  just as below.
NavigatorTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.ArrayList;
import java.util.List;
 
import junit.framework.TestCase;
 
public class NavigatorTest extends TestCase implements NavigatorObserver {
 
 private Navigator navigator;
 private GPSAbstractProvider gps;
 
 public void testNavigate() throws Exception {
 List<Position> gpsPositions = new ArrayList<Position>();
 this.addPositions(gpsPositions);
 this.gps = new GPSTestProvider(gpsPositions);
 
 this.navigator = new Navigator(this, this.gps);
 this.navigator.navigate(this.createSimpleRoute());
 
 gps.initGPSService();
 
 assert(...);
 assert(...);
 }
 
 private Route createSimpleRoute() {
 (...)
 }
 
 private void addPositions(List<Position> gpsPositions) {
 (...)
 }
 
 @Override
 public void DestinationAchived(Position destination) {
 (...)
 }
 
 @Override
 public void StepUpdated(int step) {
 (...)
 }
 
}
As you can see, I can use any GPS provider in my tests, making them much more easy and flexible.
In addition to the disavantage presented, Alex Miller discuss some points why he hates Singleton pattern.
From here, trying avoiding this pattern in situations like that. Think twice before applying Singleton in your project.
See you

Internet through the sky


Hi,
it’s incredible how Internet is in everywhere. After Wi-Fi, WiMax and 3G make possible the internet access in shoppings and airports, it’s time to read your favority blog inside the airplane.
According to American Airlines, their passengers will be able to test in-flight Internet access. At the beginning, just two flights will provide this service: New York – Los Angeles and San Francisco – Miami, both in Boing 7676-200. However, the company have plans to enlarge the service in two weeks.
Passengers will be able to use e-mail, instant messaging, to download video and connect to secure networks on notebook computers or other wireless devices such as smart phones through three wireless access points on the plane. Unfortunately, this service will not be free of taxs. Facing record high fuel prices, American plans to charge $9.95 to $12.95 for Internet service, depending on flight length.
Well, it seems a good entertainment alternative for that long/boring flights and to help in some late job.

Even LINQ for JavaScript

LINQ is one of my favorite features in the C# language so far. There is no such a thing as filtering, ordering and grouping data using an easy and fluent API. In the last weeks I found myself writing lot of JavaScript code. More than just ajax calls, DOM manipulation and fancy animations, my team and I maintain a huge js model which includes entities, controllers and repositories. Because of that, many of the operations that we regularly implement in server-side are implemented in client-side as well such as finding, sorting and grouping elements in data collections. On the server we use LINQ to perform such operations, but how to implement them in JavaScript?
Luckly, there is a JavaScript library that provides all LINQ operations with a very similar sintaxe. Just as C#, LINQ for JavaScript operates under IEnumerable objects. Therefore, the first thing to do is create an IEnumarable object with the FROM function. To illustrate the library usage, I will start with an array of people. The code below includes the Person object definition and the creation of an enumerable of people from an array. Very straightforward.
init-person
Since the enumerable is created, we are free to perform all LINQ operation on it. Let’s start with a simple search: I want to find the person whose name is ‘Fernando’. The code below illustrates that. Notice the sintaxt used by the library. While in C# we write lambda expressions (x => x.Name), here we use the symbol $.
first
Next, we filter the collection with the people with age greater then 25 and select their names.
where
Next, we order the collection by age and select their names.
order
Finally, we group the collection by sex. In addition, each group is ordered by name.
groupBy
As you can see, there is no secret. The sintaxe is really really similiar. I could show others the operations here, but they are all avaible in the library’s documentation. So, if you got interested by LINQ for JavaScript, take a look in the project page on codeplex. It helped me a lot and hope it can bu useful for you as well.
See you,

Relational Persistence for Java and .NET

Historically, Hibernate facilitated the storage and retrieval of Java domain objects via Object/Relational Mapping.  Today, Hibernate is a collection of related projects enabling developers to utilize POJO-style domain models in their applications in ways extending well beyond Object/Relational Mapping.

Hibernate News

JBoss Community Recognition Awards: Voting ends tomorrow!
Jul 25, 2013 5:24 AM by Sanne Grinovero
The voting for the JBoss Community Recognition Awards 2013 ends tomorrow; if you haven't done it yet please vote for our contributors. Among other…
Hibernate ORM 4.2.3.Final Released
Jul 3, 2013 12:06 PM by Brett Meyer
Hibernate ORM 4.2.3.Final was just released. The full changelog can be viewed here HHH-8112 fully documented the OSGi capabilities and included mu…
View more hibernate news

Small Project on Bus Reservation 

Implement a bus reservation system asume bus' seats are as follows
HHHHHH
HHHHHH
HHHHHH
. . . . . . . .
you can assume 10 rows in bus.

Now if user enters 4 as required seat no then the prefrence order would be
4
3,1
2,2
2,1,1
1,1,1,1
and the function should return the seat number.

1. Bus.java


package com.cobra.entity;

import java.util.ArrayList;
import java.util.List;

public class Bus {

private List<Row> rowList = new ArrayList<Row>();
private static int seatAvailable;

public Bus() {
// TODO Auto-generated constructor stub
}

public List<Row> getRowList() {
return rowList;
}

public void setRowList(List<Row> rowList) {
this.rowList = rowList;
}

public int getSeatAvailable() {
return seatAvailable;
}

public void setSeatAvailable(int seatAvailable) {
Bus.seatAvailable = seatAvailable;
}

}

2. Row.java


package com.cobra.entity;
import java.util.ArrayList;
import java.util.List;
public class Row {
private List<Seat> seatList = new ArrayList<Seat>();
private int seatsAvailable;
public Row() {
this.seatsAvailable = 5;
}
public List<Seat> getSeatList() {
return seatList;
}
public void setSeatList(List<Seat> seatList) {
this.seatList = seatList;
}
public int getSeatsAvailable() {
return seatsAvailable;
}
public void setSeatsAvailable(int seatsAvailable) {
this.seatsAvailable = seatsAvailable;
}
}
3. Seat.java

package com.cobra.entity;
public class Seat {
private int seatNo;
private boolean isAvailable;
public Seat() {
// TODO Auto-generated constructor stub
}
public Seat(int seatNo) {
this.seatNo = seatNo;
this.isAvailable = true;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public boolean isAvailable() {
return isAvailable;
}
public void setAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
}
4. BusControl.java


package com.cobra.program;
import com.cobra.entity.Bus;
import com.cobra.entity.Row;
import com.cobra.entity.Seat;
public class BusControl {
public static Bus populate()
{
Bus bus = new Bus();
/*
*  create new row
*  add seats to that new row
*/
Row row = null;
for(int i=0 ;i <=9 ;i++)
{
row = new Row();
row.getSeatList().add(new Seat((1)+((i)*5)));
row.getSeatList().add(new Seat((2)+((i)*5)));
row.getSeatList().add(new Seat((3)+((i)*5)));
row.getSeatList().add(new Seat((4)+((i)*5)));
row.getSeatList().add(new Seat((5)+((i)*5)));
bus.getRowList().add(row);
bus.setSeatAvailable(bus.getSeatAvailable()+5);
}
return bus;
}
public static void allocate(Bus bus,int seatsRequired)
{
//if required seat is <= 0 return
if(seatsRequired <= 0)
return;
for(Row row:bus.getRowList())
{
//if the row has more seats than required seats then allocate
if(row.getSeatsAvailable()>=seatsRequired)
{
for(Seat seat:row.getSeatList())
{
if(seat.isAvailable()==true && seatsRequired >0)
{
System.out.print(seat.getSeatNo()+" ");
seat.setAvailable(false);
bus.setSeatAvailable(bus.getSeatAvailable()-1);
row.setSeatsAvailable(row.getSeatsAvailable()-1);
seatsRequired--;
}
if(seatsRequired==0)
return;
}
if(seatsRequired==0)
return;
}
}
//recursion process
allocate(bus,seatsRequired-1);
allocate(bus,1);
}
}
5. MainApp.java
package com.cobra.program;
import com.cobra.entity.Bus;
public class MainApp {
public static void main(String[] args) {
// populate bus seat numbers
Bus bus = BusControl.populate();
// First Allocating Three Seats
int seatRequired = 3;
// check for availability of seat in the bus;
if (bus.getSeatAvailable() < seatRequired) {
System.out.println("Seats are not Available");
} else {
BusControl.allocate(bus, seatRequired);
}
                System.out.println("");
// Second Allocation Four Seats
seatRequired = 4;
// check for availability of seat in the bus;
if (bus.getSeatAvailable() < seatRequired) {
System.out.println("Seats are not Available");
} else {
BusControl.allocate(bus, seatRequired);
}
                   System.out.println("");
// Third Allocating Two Seats
seatRequired = 2;
// check for availability of seat in the bus;
if (bus.getSeatAvailable() < seatRequired) {
System.out.println("Seats are not Available");
} else {
BusControl.allocate(bus, seatRequired);
}
}
}
Output:  1 2 3 
               6 7 8 9
               4 5

BINARY TREE TRAVERSING IN ZZ WAY

#include<stdio.h>
#include<conio.h>

struct node
{
struct node* left;
struct node* right;
int data;
};

struct snode
{
struct node *t;
struct snode *next;
};

// creation of new tree node
struct node* newnode(int value)
{
struct node* new_node;
new_node=(struct node*)malloc(sizeof(struct node));
new_node->data=value;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}

int isempty(struct snode* stacknode)
{
/* First run the code with outer while loop in the zigzag fn() get commented
* then modify the number 28482 accordingly */
return ((stacknode->t->data==28482))? 1 : 0;
}

// pushing the tree node into the stack
void push(struct snode** stknode,struct node* treenode)
{
struct snode* new_stknode=(struct snode*)malloc(sizeof(struct snode));

if(new_stknode==NULL)
{
printf("Stack Memory Allocation Error!!");
exit(0);
}

//allocation of value to new stack node
new_stknode->t = treenode;

//pushing the new tree node to the stack
if(*stknode == 0)
new_stknode->next=NULL;
else
new_stknode->next=(*stknode);


//moving the pointer to the beginning of the stack
(*stknode) = new_stknode;


}

// poping the node from the stack
struct node* pop(struct snode** stknode)
{
struct node* result;
struct snode* top;

//checking for emptyness of the stack
if(isempty(*stknode)
)
{
printf("\n Stack underflow error!");
exit(0);
return NULL;
}
else
{
top = (*stknode);
result=top->t;
*stknode = top->next;
free(top);
return result;
}
}

//prints the tree in zig-zag fashion

void zigzag(struct node* root)
{
struct snode *node1 = NULL;
struct snode *node2 = NULL;
struct node *temp=NULL;

if(root==NULL)
return;

// pushing root node to node1 stack
push(&node1,root);

isempty(node1->next);

printf("Value to be given in isemptylist() fn %d\n ",node1->next->t->data);

//loop has to run until both the stack becomes empty

/* First run the code with full outer while loop get commented
* then modify the number (here it is 28482) in the isemptylist fn() accordingly */

while(!isempty(node1) || !isempty(node2))
{
//traversing odd level left to right
while(!isempty(node1))
{
temp=pop(&node1);
printf("%d ",temp->data);
push(&node2,temp->left);
push(&node2,temp->right);
}

//traversing even level from right to left
while(!isempty(node2))
{
temp=pop(&node2);
printf("%d ",temp->data);
push(&node1,temp->right);
push(&node1,temp->left);
}
}
}


void main()
{

struct node* root=newnode(1);
clrscr();

root->left=newnode(2);
root->right=newnode(3);
root->left->left=newnode(4);
root->left->right=newnode(5);
root->right->left=newnode(6);
root->right->right=newnode(7);
zigzag(root);

getch();
}