Monday, December 13, 2010

Not Only Iterating

In many cases we have to iterate through collections as an example we have to display some data table
in that case we pull data as collection and use iterator(or any other iteration mechanism such as for each loop,enumerations) to traverse
through it. Those iterators are very much handy if we just need to display or visit that item but in real world applications we are  not limited with that viewing part we may need to modify the collection as well
the problem   accrues when we need to do such a things.Assume we need to remove some of the elements from the collection while we are visiting each.
example



basically for -each loops and Enumerations are not allowing modifications to the collection if we use those loops as above example in many cases(@see notes) it throws a common exception called ConcurrentModificationException
this is a common mistake and it can happen in many ways follow  are some cases that this exception may encounter.
1.In multi threaded programming accessing the same collection by two or more   threads
2.In normal scenarios modifying the iterator while it's being iterate.

Avoiding the exception 

for-each loop cannot save us from here so we have to look back with our previous savior Iterator.Iterator object have few functions to modify the collection while iterate.





this will save us from that exceptions if you search through the Google you may come up with this kind of solution.But we have changed our attitude not to use Iterator so we have to find a solution with our for-each loop.
here is the simple solution and we are still stick to the for each :D and this is more safer(@see notes) than using Iterator


notes:
many cases
this exception may not be thrown in some cases and its is depend on the architecture that you are using
if you using struts this exception may not be accours because struts is based on singleton design pattern and there are no multithreaded scenario in struts(STRUTS issue a copy to every one so no need to worry of issues related to multithreaded environment)

more safer
keep in mind to use thread safe collection or make the collection thread safe explicitly for “toBeRemoved” collection
@see how to make a set thread safe explicitly

Friday, December 10, 2010

Syntax Highlighting in Blogger

We are quite new to blogging and when we blog our first posts faced difficulties when adding the code snippets. As beginners it was not that easy to find a solution for this, finally I came across this post which is quite interesting and helpful and it uses Javascript syntax highlighter .

Add Syntax Highlighting Step-by-Step
  1. Go to Design by from your Blogger Dashboard
  2. Select Edit HTML
  3. Add following code immediately after <head> tag (Better to Backup Template before editing) and Save Template and you are ready to use
    Note : remove any line of language you are not going to use
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/> 
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'></script> 

<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'></script> 

<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script> 
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'></script> 
<script language='javascript'> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
SyntaxHighlighter.all();
</script>
(Note: current version of syntax highlighter does not support text wrapping if you need that replace current with 2.1.364 in above code)

After that you can use Method 1 or 2 to apply it to your posts

Method 1 - using the <pre> tag

Method 2 - using the special <script> tag
<script type="syntaxhighlighter" class="brush: html"><![CDATA[
<html>
<head>
<title>Title of the HTML page</title>

<meta name="title" content="Help Give to the Carter Tomorrow Fund" /> 
]]></script> 
Note : you can replace 'html' to any of selected language (e.g. java, php, csharp, js, sql)

Change Theme
There are several themes currently available, this post uses shThemeDefault.css. To change the theme simply change this file to any of defined themes in here.

Encoding Code
If you are using "less than" or "greater than" symbols in your code snippets you have to use Method 2 but if you really want to use Method 1 use this to get escaped HTML code before adding it to your blog post.

Example Codes:

Before syntax highlighting (code to be inserted in the post Edit HTML view)


After syntax highlighting (final view of the code in the blog post)

That's it for syntax highlighting. Enjoy !

Thursday, December 9, 2010

Immutable Objects ?

What is an immutable object?

Immutable object is an object whose state cannot be changed or simply cannot be modified after its construction. That means once you instantiate an immutable object thats it you can never modify it.

There are many immutable classes provided by the Java platform. Examples are String, BigInteger, BigDecimal and primitive wrapper classes.

But why making classes immutable? There are many reasons,
  • Easy to design and implement
  • More secure and less error prone
  • Simple
  • Automatically thread-safe
  • Can be shared freely
The only disadvantage of immutable object can be the performance impact due to the creation of separate object for each and every distinct value.

So lets discuss the main objective of this post, how to create one? To make an immutable class you have to follow following rules,
  1. Make the class as final - ensures the class can not be overridden
  2. Mark fields as private and final - prevent from being modified directly
  3. Use constructor to construct the object completely - have to instantiate it in single line
  4. Remove any method which can change its state - state can not be changed
  5. Extra attention to mutable object fields (create new mutable object in any time passed into constructor or out of getter methods) - maintain immutability

Following is an example Employee class,
sample Employee immutable class


"Classes should be immutable unless there is a very good reason to make them mutable... If a class cannot be made immutable, limit its mutability as much as possible"
(By Joshua Bloch)



Cheers!

Monday, December 6, 2010

Iterator vs For Each

In many cases we need to iterate over collections , earlier versions of java provides few mechanisms to accomplish that task such as Iterator ,Enumerations before we going through new java feature for each ,lets discuss what are the diference's between those two interfaces

Enumerations is the older one among those two types it simple iterate through the Collection and it is not allow programmer to modify(allow remove) the collection while traverse.But more advance feature Iterator give freedom to developer to modify the iterator .

@see here is the source code of the Iterator

example of enumerations

for (Enumeration e = v.elements(); e.hasMoreElements();)
System.out.println(e.nextElement());

But there is a disadvantage with Iterator that it does not allow to traverse to bi directions and java language introduce a new feature called ListIterator it extends Iterator interface this new iterator allow developer to move bi direction.so we can iterate forward and backward
@see source code of ListIterator


Note : when we need to iterate through the collection just reconsider what is the actual need and then use appropriate mechanism rather than selecting Iterator interface for all :D and frequently going throw java docs it save us from many development errors .And don not forget to use java generics with collections because generics are more useful with collections.hopes to discuss generics in next article so stay in touch

Back to the main topic
The question is why we asked to use new "for each" loop,even Iterator interfaces(including ListIterator as well) are full filling most of the requirements,the simple answer is iteration over collections are uglier than than it should be and using Iterators are opportunity for errors
.Because coding is not just giving solutions for a problems ,we have to maintain readability of the code those kind of iterations are reduce the readability of the code,the lack of readability guide you to critical coding errors.
Following is a nice article that you may have gone through if not go through follow article it is no use of including it in side this blog :D
@see For-Each
if you don't have enough time to go through it follow is a simple demonstration how for each improves readability of the code
example :




























is improved for each more nicer ? if so get use to that coding standards.

by the way just keep in mind that every programmer is doing mistakes even very experts,one way of avoiding those mistake is keep nice and clean code so make sure to use such mechanism to improve your readability of the code