msgbartop
Code that explodes conventions
msgbarbottom

31 May 11 Java Collection Framework : List

Java collection framework is very common to every java programmer, again for the beginner, I'm going to share my ideas about it.  It's really helpful to manage object easily. Java collection framework is more likely array, but difference is, Collections can  dynamically change their size. Today I'm going to write only about the List.

List:

The java.util.List interface is a subtype of the java.util.Collection interface. It represents an order list of objects. User can access the elements of list in a specific order or by and integer index. List allows to insert duplicate elements. Interestingly you can insert null object even in a list.
As it is an interface, there of course it has implementation. ArrayList, LinkedList, Vector, Stack are the implementation of List. All List types support basic operation like adding object, removing objects, accessing objects and iterating through the List.

There are also List implementation in java.util.concurrent package. Concurrency is the part of parallel programming, immutability, threads, executor frameworks etc. We better discuss this part later.

How to create list instance:

Creating list instance is too easy.

package org.codexplo.blog.list;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.Vector;

public class ListInstance {
 public static void main(String[] args) {
 List listA = new ArrayList();
 List listB = new LinkedList();
 List listC = new Vector();
 List listD = new Stack();
 }
}

Adding and accessing Elements
To add element, you need to call its add() methods. This method is inherited from java.util.Collection interface.
There are two overload method in list.

boolean add(E e);
void add(int index, E element);

The first one add elements t0 the end of the list and return true if the list is changed as a result of the call otherwise false.

and the second one add element at the specified position in the list. If any element is already in that position, it shifts the elements concurrently to the next.

package org.codexplo.blog.list;

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

public class AddingAndAccessingList {
 public static void main(String[] args) {
 List list = new ArrayList();

 list.add("a");
 list.add("b");
 list.add("c");

 list.add(0, "abcd");

 System.out.println(list.get(0));
 System.out.println(list.get(1));
 }
}

The first three add() calls add a string instance to the end of the list. The last  add() call adds the element at the beginning of the list and rest of elements are shifted.

you can access elements using get method. you need to specify the index of the element.

Again you can access elements via Iterator.

package org.codexplo.blog.list;

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

public class AddingAndAccessingList {
 public static void main(String[] args) {
 List list = new ArrayList();

 list.add("a");
 list.add("b");
 list.add("c");

 list.add(0, "abcd");

 // via get() method
 String a = (String) list.get(0);// need to type cast as I used generic
 // type List
 String b = (String) list.get(0);

 // via iterator
 Iterator iterator = list.iterator();
 while (iterator.hasNext()) {
 String string = (String) iterator.next();

 }
 }
}

Removing Elements

You can remove element in two ways.

boolean remove(Object o);
 E remove(int index);

The first method removes the first occurrence of the specified element from the list. If the list does not contain the element, it is unchanged. More precisely it removes the element with lowest index if the element exist. Returns true if the list contained the specified element.

The second method removes element at the specified position in the list. It shift any subsequent elements to the left concurrently and return the element that was removed from the list.

package org.codexplo.blog.list;

import java.util.*;

public class RemoveListObject {
 public static void main(String[] args) {
 List list = new ArrayList();

 list.add("a");
 list.add("b");
 list.add("c");
 list.add("d");

 list.remove("a");

 list.remove(2);
 }
}

These are the basic operation of the list. But there are some more methods available in List interface. Some of them are given shortly.

int size();

Returns the number of element in the list. int size(); If the list contains more than Integer.Max_Value elements, it returns Integer.Max_Value meaning if the list contain more than 2147483642, it will return 2147483647 because we know an int can can have, 2^31-1.

boolean isEmpty();

returns true if the list contains no element otherwise false.

boolean contains(Object o);

returns true the list contains the specified element.

Iterator<E> iterator();

Returns an iterator over the elements in the list in proper sequence.

Object[] toArray();

Returns an array containing all of the elements in the list in proper sequence (from first to last element).

void clear();

Removes all of the elements from this list (optional operation).

int indexOf(Object o);

Returns the index of the first occurrence of the specified element in the list, or -1 if this list does not contain the element.

int lastIndexOf(Object o);

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

List subList(int fromIndex, int toIndex);

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

if you want to remove a subset of elements from the list, you can use following way.

list.subList(from, to).clear();

it will remove elements of the range specified.

Optimized technique.

The performance of different implementation of List is different. The choice of using list implementation depends on specific operation. As I said earlier, all list type support all basic operation, so which one to choose since all the list implementation support these basic operation? Here choice depends on the performance and requirement options.

The requirement operation could be -
1. Thread safety
2. Size of collection
3. Type of operation (adding, removing , accessing or iterating)

If you want your collection to be thread safe then Vector or Stack must be used because both have synchronized methods. ArrayList and LinkedList are not thread safe. Stack is mean fo LIFO (last in, first out) operation. If thread safety is not your concern, you can use ArrayList or LinkedList. From the performance point of view the ArrayList gives better gives better performance when accessing and iterating object whereas LinkedList gives better performance when adding and removing objects.

The initial size for ArrayList and Vector is 10. ArrayList increase its capacity by half approximately whenever its capacity reaches maximum(10) but vector increase its capacity by double whenever its capacity reaches maximum.

LinkedList gives good performance when adding elements at the end and beginning but it is worse when adding objects at middle because it needs to scan the node whenever it needs to add an object.

Iterating collection using all three types of classes ,ArrayList ,Vector and LinkedList gives similar performance.

Key Points:
1. Use ArrayList with proper initialization if you don’t want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
2. Use Vector with proper initialization if you want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
3. Use LinkedList if you don’t want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
4. Use synchronized LinkedList if you want thread safe for the collection whenever you add/remove/access objects at beginning of collection.

31 May 11 Is My Class Too Big?

I've written a series of posts on designing a class hierarchy and an individual class in C#.  There's a larger question that encompasses all object-oriented languages "is my class too big?"  Every experience programmer knows the dangers of giant classes. They make code more tightly coupled and the degrade cohesion.  When is a class too big? There is no easy rule to determine when a class is too big, but I think that I provide some guide posts.

  1. If you start to have trouble finding what you need to change, then your class may be too big.  In C#, regions can be use to mask this issue a little bit, but eventually the problem will appear if a class gets big enough.
  2. If you can't provide short description of what your class does, then it may be too big.  Every class should have focused purpose.  If that purpose takes too long to describe accurately, then your class is too big.
  3. Robert Marin wrote, when describing the Single Responsibility Principle, that a responsibility is a reason for change.  If your class has more than a few reasons to change, then it is too big.  Ideally a class should only have one, but minimize reasons to change a class is passable.

There are probable more guideposts, but these are straightforward and easy to spot.  Admittedly, knowing when to take action and when to leave a class alone is more an art than a science.  If you're looking for guideposts like the ones described above, then your more likely to stamp out the problem of big classes than if you're oblivious to them.

Part of good design is spotting when refactoring is necessary.  Don't let your code get out of control.  If the problem gets bad enough, rewriting becomes easier than refactoring.  Rewritting takes more time. Time is money.  Get ahead of the problem.  Refactor large classes before they make your code unmaintainable.  Hopefully, those three guide posts will help you identify when to do it.

31 May 11 Designing A Class: Building The Class

It's time to build the class.  This where your vision comes to life.  I'll explain the process of how to achieve that.

The first step is dealing with your data.  Create your data elements and name.  These should always be declared private unless there's a good reason to otherwise.  What exactly constitutes data?

Any information for the outside world is considered data, which seems pretty obvious.  Let obvious are things like flags or state data.  Those are data as well.  I will say that data like flags and states can be added in later as they are often a mechanism for what the class wants to accomplish.  As a side note, enums, which are compiler enforced in C#, are nice way to list things like modes or states.  For more information on enums, grab C# book and look at some examples.  They're actually pretty straightforward once you see how they work.  What's next after data?

Constructors are the next thing to be done.  You know what your class does and what data it holds, generally, so now its time to determine how people can build your class.  Set up the constructors that you deem to be useful.  More constructors can be added as you work on your class and their actions can be modified as well.  For the most, the constructors you create should be primary ones that you use.  What's after constructors?

To provide access to public data, declare properties.  Only declare properties for data that you absolutely want the outside world to see.  Only give use access to internal state and flags if absolutely necessary and be cautious about giving them write access to those properties.   Your goal as a class designing is to make it difficult to misuse your class.  That completes the data section.  What's after that?

This may not be necessary for every class, but some classes require events.  If you need events, define them.  Remember to define the necessary delegates for each event as well.  As a note, the constructors may need to be updated to attach methods to events and properties may need to be created to allow handles to be to each event.  What your class does will determine how you deal with event handlers.  You have events, but what's next after that?

You've gotten to the part where you build what the class does:  the methods.  If you have events, you need to determine if you're going to build baked-in handlers or not.  That's something that the purpose of your class will determine.  Regardless, the first area of your focus with regard to methods should be on public methods.  Build them first.  This is what the outside world sees.  Those methods define, ostensibly, what your class does.

After you've built your public methods and, if necessary, your events handlers, carve the common into private functions.  After you've carved out the common functions, begin carving areas of code that logically fit together.  Make those areas private functions as well.  This will keep each respective function small.  One of the most common scourges of clean code is large functions.  Keep your functions small as best you can.

I know this doesn't really serve as a recipe as much a guide post.  I'll post some more stuff on C# specifics later.  Until then, good luck writing your C# stuff.  I think you'll learn to like the language.

30 May 11 Designing A Class: C# Specifics

C# is a typical object-oriented language like Java or C++, but it does have some unique features that distinguish it from the aforementioned languages.  I'll go over those here.  For more details on understanding C# at an implementation level, consult a book.  There are a lot good ones out there.  Anyway, let's get down to business.

Probably the most frequently used aspect of C# that distinguishes it from Java or C++  are properties.  What is a property?  Every object-oriented veteran knows that you have data and then you have the getters and setters.  Properties have the getters and setters rolled into them.

How is a property different from data.  Properties do not store any information.  They're merely an abstraction layer.  To put it simply, you would declare a data item as private and then declare a public property to get and set the value of the data item.  An external user of your class has no knowledge what your class does and this achieved by simply setting up a property.

C# also has events and delegates.  I'll refer to a C# book to give the details on what events and delegated are and how to use, but, for now, I'll give the concept behind them. Events provide a canned way to describe things that your class needs to respond.  The response is represent handlers which you attach the desire event.  Delegates represent a collection parameters that a given function must match.  You could create a delegate, for example, to handle an event.  Any event handler for a given event must create a delegate of a certain type with a function that takes the same parameters.

Admittedly, there is no strict enforcement that says that a specific delegate must match a specific event.  A programmer could easily use the wrong delegate and get the code to compile.  However, if the event and delegate are named properly identifying the proper delegate should be easy.

C# has some unique elements that make design a class a little different from what you may be used to.  Some of those aspects may be confusing.  Take a look at some code examples.  Once you see a typical C# class, you'll get the idea and begin to understand how to use C# to achieve what you want to do.

29 May 11 Designing A Class: Understanding The Parts

Before you can design a class, you must understand what that design encompasses.  Once you understand what those parts are and how they are relevant, the design process can begin.  Let's go over those parts.

Most classes, if they're in a hierarchy, inherit or implement something.  The first part of class design is understanding what a class must inherit or implement.  This will tell you what a class already has and what it must do.  There's no need to reinvent the wheel.  Bases classes can provide a fair amount of functionality already completed. Use them.

A classes ancestors is actually more complicated that than.  A class has two types of ancestors: a base class and interfaces.  They are similar but different.  A base class actually passes on implementations.  Interfaces only provide a contract that has to be fulfilled but no implementations.  Both, however, affect how the class appears to the outside world.  All public aspects are inherited and appear to code that utilizes the class.  Why the distinction?

Base classes supply inherited mechanisms and interfaces supply inherited policy.  As to why those are separated, please read my series of articles on designing a class hierarchy.  That series of articles will elucidate the reasons.

After you've determined what a class should inherit and implement, you have to determine what this class will do outside of its ancestors.  Every class has three parts: constructors, data, and methods.  The next step is determining what goes in those three areas.  What separates the three?

Constructors determine how users of your class can build it.  Many classes provide a variety of constructors to allow a use to build the class in a more convenient way.  That's the thinking behind constructors.

Data determines what information your class holds.  This could be user available information or it could be internal information. That is not the point.  You need to think about what your class should hold information wise.

Methods determine what your class does.  Methods are often what manipulate the data inside the class, but they do not have to.  Before you start building your class you need to think about what it needs to do.

29 May 11 Designing A Class Hierarchy: Building the Hierarchy

Your hierarchy will have three "layers."  The first will be for the interfaces, one for each type of object that you need.  The second layer contains the abstract classes, which implement the interfaces.  The third layer contains that classes that extend the abstract classes.

You may be thinking.  Why do I need the interfaces?  The interfaces abstract the mechanism from the policy.  A class can use an interface while having to worry very little about the mechanism changing.  The interface layer makes your code less tightly coupled.  Tight coupling makes changes difficult and painful

Building those three layers is not only step.  Interfaces and abstract classes have common properties and methods.  Those methods must be abstracted out into small interfaces.  All of the old classes and interfaces that had those properties and methods now inherit from the necessary interfaces.

Why go through the trouble?  Breaking you classes and interfaces into smaller interfaces not only makes your code more loosely coupled but more cohesive as well.  Admittedly, this may not gain you much for certain projects.  As the project grows larger, the bigger the issue coupling and cohesion becomes.  Design your hierarchy the correct way to avoid the pain as the project grows.

The process is not done.  Abstract classes can have common implementations.  These common implementation must be abstracted out into their abstract classes.  These abstract classes are the implementation of the interface from which the method or property comes.  They may also include implementation of common methods from interfaces that are common to the classes that use the base class. The abstract classes that implement the interfaces of you main objects should use the above abstract classes as their base classes.

This may seem like overkill.  Only a few classes share the implementation.  Why move it out?  What if classes of a similar type are created?  Are you going to copy the code?  What if that implementation has to change?  All of those questions present a problem.  Again, coupling and cohesion problems come back to bite with vengeance.  Avoid them even when the issue seems small at the time.

What about structs?  You mentioned the in the previous article but have not in this one.  Structs are not meant to the bricks of the even the mortar of C# code.  They are after thought.  When you to handle a function return but do not want to be bogged down by heavy classes, you use a struct.  That's what they are good for.  Structs are built as needed, so they are not a part of the design process.

Lastly, I'd like to give some words of wisdom.  Think out your design before you jump in, but do not be afraid to remodel as you build.  There is nothing wrong with moving things around.  The best way to achieve something is often more clear once your inside the process.  Do not be afraid to change things.

27 May 11 Designing A Class Hierarchy: C# Specifics

Before we get into the specifics of designing a class hierarchy, let's go over some of the specifics of C#.  There aren't many specifics but there are a few.  I'll quickly go over them.

C# classes can only have one base class.  This may or may not affect how you design you hierarchy, but suffice to say that cann0t build a class from multiple generics.  There is a way get around this limitation.  To put it simply, a sub-generic layer can be used to get around.  The generic classes are built on top of the sub-generic class.

C# classes may only get one base class, but they can implement multiple interfaces.  This allows classes to built from a select number of interfaces. Interfaces can function like building blocks for your code.

What if an two interfaces have the same contract?  Admittedly, I've never run into this.  However, you should not have the same contract element in multiple interfaces.  The same class should absolutely not be implement those interfaces even if you have them.  If you're running into this problem, then should redesign your code.  Well designed code should never have this problem.

C# also has structs like C and C++.  However, structs cannot have base classes. They can implement interlaces, though.  Structs are what C# uses to create "lightweight" classes. They're small and fast.

Overall, C# is like C++ and Java smashed together.  If you're familiar with those languages, then C# should easily be learn-able for you.  The elements above with the exception of the multiple interfaces if you're a Java programmer should seem quite familiar to you.

27 May 11 Java main method

Several times junior mates at IIT, who just started Java, asked me to explain the signature of the Java main method.

The signature:

public static void main(String[] cArgs);

I am trying to explain each word separately.

public:

public is one of the four (unlike C++, where it is three) access modifier. By declaring something public, you are telling that the code-block can be accessed from outside the class. Main is the point to start execution. So, it must be accessed by the compiler directly from outside. If you declare main something other than public the source will successfully compiled. But if you try to run, the compiler will reply:

Main method not public

static:

The big question I always had and I am asked several times. static methods or variables are those, which are instantiated before any objects are instantiated. On the other hand we can say, If anything is required to be instantiated before any objects have been instantiated, you need to declare it static.

Now, as main is the entering point of a program, it must be called before any thing else has happened. So, you have to make it static. Otherwise compiler will say,

Exception in thread "main" Java.lang.NoSuchMethodError: main

void:

This is the return type. Java main() does not return anything. So, the return type is void.

cArgs:

This is the command line argument. The type is array of String. Beginners, please note that cArgs is just a variable name. You can use anything you like. If you know C/C++, you may know that command line argument is optional there, but that is not true in case of Java.

If you need to learn about command line argument. You can consult here.

26 May 11 Designing A Class Hierarchy: Understanding the Components

C# is a typical object oriented language in that it has classes, abstract classes, and interfaces.  Before you can even start to design a class hierarchy, you must first understand what distinguishes interfaces, abstract classes, and classes.

Interfaces represent a contract.  Any class, interface, or abstract class that implements an interface agrees to that contract.  Meaning that anything in that interface must be publicly implemented.  Essentially, an interface represents a public facing contract.  An interface that implements another interface does not have implement that interface's contract.   The possibility exists that a long chain of interfaces could be created. Any class or abstract class that implements an interface in that chain must implement all of the contract elements in the interface chain starting at the point of implementation and moving backward to end of the chain.  Given a long enough chain, this could become confusing and perhaps frustrating, but that's another topic for another post. Anyway, an interface represents a contract, but what does that mean in grander scheme of a design?

An interface contract represents the policy of the system.  For every policy you should have interface.  This how you achieve a separation of policy and mechanism.  That separation allows for the mechanism to change while not having to change very much of those who interact with the policy.  What about abstract classes?  How are they different from interfaces?

Abstract classes can contain actual implementations.  Those implementations can do nothing if that's appropriate.  Why?  An abstract class is not a fully realized class.  It cannot be instantiated.  If an abstract class can contain implementations but cannot be instantiated, then what good is it?

Abstract classes represent generic objects.  They contain implementations common across an entire group of classes.  If an interface is a policy, then an abstract class is is a common mechanism.  This allows classes to only focus on the mechanism specific to its needs.  More common needs an be "abstracted."  This is allows hierarchy designers to focus change into more focuses areas as generic classes are less likely to change than specific ones.  Finally, what are classes good for if we have interfaces and abstract classes?

Abstract classes cannot be instantiated so you could not build software from, but, more importantly, classes represent the actual objects inside of your system.  This is where the contracts and generics are finally realized into usable components.   All of the other components build up to classes.  They are the culmination of your design.

26 May 11 Windows: Some Thoughts

After reading my words on Apple and Linux, you might think that I'm about to write an unabashed love letter about Windows.  Wrong.  I like Microsoft and Windows; both get unfairly criticized at times, but stating that Windows is likely to remain the top dog in the operating system game is like winning an award for being the prettiest ugly girl.  It's a backhanded compliment.

Windows is relatively user friendly, it is easy to develop software for, and it has stood up to immense scrutiny, yet even Windows falls short.  The much discussed reliability and security problems are still a concern.  Windows does not adjust to meet it users needs and each successive version takes years to develop.  The other operating systems may not be posed to push Microsoft out of the way, but Windows still has a way to go.

Why hasn't someone else built a product to challenge Microsoft and fix the problems that I mentioned above?  Microsoft's a big, company says many a basement hacker, yet those same hackers have not come up with something better.  Why?

It's not due to a lack of research.  There's been plenty of models that have drawn up about how to organize an operating system.  Many of them have been experimented with through half-baked hobby operating systems.  Yet,  Windows still remains unchallenged.

Building an operating system is hard.  A lot of specialized knowledge of hardware is required.  Hacking together a website, cobbling together a phone app, or even breaking into the console gaming market is easier and more immediately lucrative than developing a new platform, so the fact that developers avoid attacking such a market should not be a surprise.  Who climbs Mount Everest when climbing a foothill is more likely to product a reward?  Why bring all of this up?

I'd like to foster more skepticism with regard to technology. Nothing is more fundamental and warrants more skepticism than an operating system.  The operating system defines  everything.  Anyone who remembers the early operating systems will recall how buggy they were?  Crashes were frequent, which made doing things difficult, so the operating system is very relevant.  Why the need for skepticism?

Technologists have strong opinions. They certain technologies to the point of religious devotion and hate others with the scorn of a spurned woman.  Neither is a sober opinion.  Sobriety is only the way to accurate evaluate a technology.  Yes, accurately evaluating technology matters.  Poor decisions regarding technology can set an organization for a long time or even permanently sink it.  In order to make the correct decision, opinions must remain sober.

Windows is a prime example of this.  Few products have inspired such vile.  Every Windows bug is an example of the either the greed or stupidity of Bill Gates.  Apple doesn't get this sort of reaction and neither does Linux.  Neither of those products are perfect either, yet Windows seems to get a disproportionate share of the hate.  Why?  The religious battle lines have been drawn and Windows has been judged.  My point is simply that those religious battle line deserve some critical evaluation.   That's all that I'm trying to do in evaluating the operating systems.

Loading...
Join thousands and get updates for free...No-Spam Guarantee