Monday, April 24, 2006

Some common OO bad codes - II


The God Class Problem

Distribute system intelligence horizontally as uniformly as possible, that is, the top-level classes in a design should share the work uniformly.


Do not create god classes/objects in your system. Be very suspicious of a class whose name contains Driver, Manager, System, or Subsystem


Beware of classes that have too much noncommunicating behavior, that is, methods that operate on a subset of the data members of a class. God classes often exhibit much noncommunicating behavior.

Cure:

Divide noncommunicating behavior into separate classes

Did you ever wonder why we see this piece of code?

if(debug is enabled)
{

logDebug("xxxx.....");
}

I was wondering for a long time why it is being done?
I can control the log level at production using configuration files.
I can turn off debug level logging in the log4j or any decent loggers config files.
But still, the conditional check if(debug is enabled) is performed in any many places, which I thought absurd and redundant.

But the reason is even though the logger does not physically log; the logDebug("xxxx.....") call is actually made which checks whether to log Debug level or not. Though we also check the same what the API checks, the thing we save here is the parameter construction. If the parameters are more or built by concatenating strings, it can be costly at runtime for constructing these. Though the time to log is saved, the time for constructing these parameters is a cost to the system. Hence this check if(debug is enabled) is made to save some time.

Sunday, April 23, 2006

When Would I Not Use Stored Procedures?

When Would I Not Use Stored Procedures?
Whole discussion boards have been devoted to the pro/con debate on stored procedures. But when it comes down to it, you have only a few occasions when it might not be possible or prudent to use them.

  • You don't have the database permissions to create them. Or a cooperative DBA.
  • You're only using a few SELECT statements in your application and can't really benefit from the performance and organizational boosts offered by stored procedures (though you might still profit from the other gifts of the stored procedure).
  • Your organization is undergoing a major code migration and wants to avoid encapsulating your source in external procedures. However, this is debatable as well since you may actually benefit from the stability of SQL syntax.
ref :
http://www.devx.com/IBMDB2/Article/27818

When Do I Use Stored Procedures?

When Do I Use Stored Procedures?
Coders might argue that you never really need a stored procedure. All of your database calls can be done programmatically. That's true, but somewhat limiting. Stored procedures can do a lot of things for you that even the most elegant code cannot.

Chief among these, stored procedures save processor time by allowing you to offload database calls to the database server itself. Most databases load the compiled procedures into memory the first time they're called, or even before, dramatically reducing overhead when you're doing the same essential process multiple times (such looping operations are very common in database manipulation).

Stored procedures offer you many other benefits, as well.

  • They allow you to encapsulate code. In other words, the database operation appears once, in the stored procedure, not multiple times throughout your application source. This improves debugging as well as maintainability.
  • Changes to the database schema affect your source code in only one place, the stored procedure. Any schema changes then become a DBA task rather than a wholesale code revision.
  • Since the stored procedures reside on the server, you can set tighter security restrictions on the client space, saving more trusted database permissions for the well-protected stored procedures themselves.
  • Since stored procedures are compiled and stored outside the application, they can use more sensitive variables within the SQL syntax, such as passwords or personal data, that you would avoid using in scripts or remote calls.
  • Using stored procedures greatly reduces network traffic.

As a further illustration of this last point, suppose you want to update a customer record but you're not sure if the record even exists. One way is (a) to SELECT the record to see if the customer exists, (b) to UPDATE the record if it does, and (c) to INSERT a new record if it does not.

If you just put a series of SQL statements in your client code, each line is executed by sending a message over the network to the server, usually getting a response in return. But a stored procedure resides on the server. When called from the client application, it executes on the server and only has to respond when returning the final result set to the client, saving lots of back-and-forth traffic.

One other benefit you'll find with DB2 stored procedures in particular, the distinction of which will be explained in but a moment, is the Development Tooling support. The Enterprise edition of DB2 UDB (Universal Database) ships with a set of developer tools that allow for fast, reliable creation of stored procedures in both SQL and Java. Using the Wizards and Query Builders, you can create complex procedures without typing a word of code.

ref :
http://www.devx.com/IBMDB2/Article/27818

Sunday, April 02, 2006

Designing for Change - I

Designing for Change


All the patterns are required when we need our design to be flexible enough to face a change with out major impact. The Object orientation itself is just another style of programming that came up to solve many issues of the software engineering especially in the post implementation phase. Some of the fundamental principles / benefits on which the OO paradigm rode on are Reusability, Scalability, Maintainability etc. These were the goals for which the OO priciples and concepts stand for. If a system developed with a programming language that provides OO constructs does not provide the above said benefits, then it is not to be called a OO system.

The fact that you find programmers abundant in that language and you get the tools for that platform could have made it convenient to use it to build a system. But make sure if you really want to build a OO system or not before designing.

Some common design problems with design patterns that address the problem

  • Creating an object by specifying a class explicitly

    Abstract factory, Factory Method, Prototype

  • Dependance on specific operations

    Chain of Responsibility, Command

  • Dependence on hardware and software platforms

    Abstract factory, Bridge

  • Dependence on object representations or implementations

    Abstract factory, Bridge, Memento, Proxy

  • Algorithmic dependencies

    Builder, Iterator, Strategy, Template Method, Visitor

  • Tight Coupling

    Abstract factory, Bridge, Chain of Responsibility, Command, Facade, Mediator, Observer

  • Extending functionality by subclassing

    Bridge, Chain of Responsibility, Composite, Decorator, Observer, Strategy

  • Inability to alter classes conveniently

    Adapter, Decorator, Visitor
In this series we will take each problem one day and analyse how these patterns help solving them.

[ref : http://www.eli.sdsu.edu/courses/spring98/cs635/notes/patternIntro/patternIntro.html]

Some common OO bad codes - I

Heuristics Continued

Beware of classes that have many accessor methods defined in their public interface. Having many implies that related data and behavior is not being kept in one place.
class test
{
private int thisData;
private int thatData;
private float moreData;

public void setThisData( int data ) { thisData = data; }
public void setThatData( int data ) { thatData= data; }
public void setMoreData( int data ) { moreData= data; }
public void getThisData( ) { return thisData; }
public void getThatData( ) { return thatData; }
public void getMoreData( ) { return moreData; }
public String toString() { // code deleted }
}

No work is being done in this class.

Other classes are getting the data in class test and performing some operation on it.

Why is this class not doing the work on the data!

Who is doing the work?

Java and the Singleton


There is a major problem using the Singleton in java

Classes in java can be garbage collected!

A class can be garbage collected when there are no objects of the class and there are no variable references to the class of the class

If the Logger class is garbage collected then the value of the Singleton will be lost

The next time you reference the Singleton you will get the default value for the Singleton

Solution
Insure that there will be a reference to the class or an instance of the class

Place an instance of the class in a global reference

private static void preventClassGarbageCollection()
{
Properties systemTable = System.getProperties();
systemTable.put( "_$sdsu.logging.Logger.instance",
new Logger());
}
[ref : http://www.eli.sdsu.edu/courses/spring98/cs635/notes/logger/logger.html]

Saturday, April 01, 2006

builder pattern :

director
builder
product

requires a builder who builds a product from its parts
an abstract builder builds an abstract product with some abstract processes

The director is the one who determines the parts and the sequence in which the build processes are called to build a particular type of product.
ex:
class WorkShop {
//force the order of building process
public void construct(HouseBuilder hb) {
hb.buildFoundation();
hb.buildFrame();
hb.buildExterior();
hb.buildInterior();
}
}
When a new product is to be built, a new builder is created from the existing builder and it is used to build the new product. The advantage is as and when the new product emerges which changes only a specific part only the class / process which builds it can be modifiedand a new builder can be created so easily.

The client creates the Director object and configures it with the desired Builder object

Director notifies the builder whenever a part of the product should be built

Builder handles requests from the director and adds parts to the product

The client retrieves the product from the builder


ref:
http://www.javacamp.org/designPattern/
http://www.eli.sdsu.edu/courses/spring98/cs635/notes/builder/builder.html
http://unicoi.kennesaw.edu/~jbamford/csis4650/uml/GoF_Patterns/builder.htm