<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Artem&#039;s blog &#187; Java</title>
	<atom:link href="http://artemgolubev.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://artemgolubev.com</link>
	<description>Thoughts on software</description>
	<lastBuildDate>Tue, 20 Apr 2010 18:20:37 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Why do I need inheritance in OOP? Real-world examples.</title>
		<link>http://artemgolubev.com/why-do-i-need-inheritance-in-oop-real-world-examples/</link>
		<comments>http://artemgolubev.com/why-do-i-need-inheritance-in-oop-real-world-examples/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 02:22:18 +0000</pubDate>
		<dc:creator>Artem</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://artemgolubev.com/why-do-i-need-inheritance-in-oop-real-world-examples/</guid>
		<description><![CDATA[The problem in general is that it is sometimes unclear from books why do we need some particular technology. In this case we are going to discuss why do you need inheritance and where it is used in real-life applications.
Let us at first remind what is inheritance (samples in Java):
public class Pet {
  public [...]]]></description>
			<content:encoded><![CDATA[<p>The problem in general is that it is sometimes unclear from books why do we need some particular technology. In this case we are going to discuss why do you need inheritance and where it is used in real-life applications.</p>
<p>Let us at first remind what is inheritance (samples in Java):</p>
<pre>public class Pet {
  public void say() { }
}

public class  Dog extends Pet {
  public void say() { System.out.println("I am a dog."); }
}

public class  Cat extends Pet {
  public void say() { System.out.println("I am a cat."); }
}

public class Test{
  public static void main(String[] args) {
    Pet pet1 = new Dog();
    Pet pet2 = new Cat();
    pet1.say();
    pet2.say();
  }
}</pre>
<p>This  programm will output:</p>
<p>I am a dog.</p>
<p>I am a cat.</p>
<p>The idea is very simple: despite pet1 and pet2 are of type Pet, pet1 is pointing to object of class Dog and pet is pointing  to object of class Cat.</p>
<p>The common question which is usually raised is: why we don&#8217;t have just  Dog pet1 = new Dog(); and Cat pet2 = new Cat(); ? Whe do we need to access it via Pet?</p>
<p>Let me give you some real-world examples where do we need it:</p>
<p>1. Servlets. When we create a servlet we inherit base servlet class and override method  doGet() or doPost()to add our functionality to the servlet. The server (for example Tomcat) have list of our servlet classes deployed, and as soon as it gets request for our servlet it loads our class, create an object and call doGet() or doPost() on it. As soon as server have no idea what classes do we have it address object of our class via variable of type HttpServlet.</p>
<p>2. The similar idea was used in early versions of Struts library.</p>
<p>3. In .NET as well as in Java you override Exception class or one of it&#8217;s successors to create exception specific to your application. The system (Java or .NET)  knows only how to work with Exception (and RuntimeException specificly in Java) and works with all your exceptions uniformaly.</p>
]]></content:encoded>
			<wfw:commentRss>http://artemgolubev.com/why-do-i-need-inheritance-in-oop-real-world-examples/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Break and continue statements will stop exception flow</title>
		<link>http://artemgolubev.com/break-and-continue-statements-will-stop-exception-flow/</link>
		<comments>http://artemgolubev.com/break-and-continue-statements-will-stop-exception-flow/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 03:59:59 +0000</pubDate>
		<dc:creator>Artem</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[break]]></category>
		<category><![CDATA[continue]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java language specification]]></category>

		<guid isPermaLink="false">http://artemgolubev.com/break-and-continue-statements-will-stop-exception-flow/</guid>
		<description><![CDATA[As it is said in The Java Language Specification (http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.15):
&#8220;The preceding descriptions say &#8220;attempts to transfer control&#8221; rather than just &#8220;transfers control&#8221; because if there are any try statements within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, [...]]]></description>
			<content:encoded><![CDATA[<p>As it is said in The Java Language Specification (<a href="http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.15"><font color="#5588aa">http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.15</font></a>):<br />
&#8220;<span style="font-style: italic">The preceding descriptions say &#8220;attempts to transfer control&#8221; rather than just &#8220;transfers control&#8221; because if there are any </span><code style="font-style: italic">try</code><span style="font-style: italic"> statements </span><span style="font-style: italic">within the break target whose </span><code style="font-style: italic">try</code><span style="font-style: italic"> blocks contain the </span><code style="font-style: italic">break</code><span style="font-style: italic"> statement, then any </span><code style="font-style: italic">finally</code><span style="font-style: italic"> clauses of those </span><code style="font-style: italic">try</code><span style="font-style: italic"> statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a </span><code style="font-style: italic">finally</code><span style="font-style: italic"> clause can disrupt the transfer of control initiated by a </span><code style="font-style: italic">break</code><span style="font-style: italic"> statement.</span>&#8221;<br />
Let&#8217;s look into next example:</p>
<pre>
public class Test {
	private static void test() throws Exception {
		for (int i = 0; i &lt; 3; i++) {
			try {
				throw new Exception("Exception text");
			} finally {
				System.out.println("Finally exception " + i);
				continue;
			}
		}
		System.out.println("Impossible");
	}

	public static void main(String[] args) throws Exception {
		test();
		System.out.println("Impossible 2");
	}
}</pre>
<p>will produce output:<br />
<code><br />
Finally exception 0<br />
Finally exception 1<br />
Finally exception 2<br />
Impossible<br />
Impossible 2<br />
</code></p>
<p>So, be extremely careful with your breaks!</p>
]]></content:encoded>
			<wfw:commentRss>http://artemgolubev.com/break-and-continue-statements-will-stop-exception-flow/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to access overridden methods of superclass of a superclass in Java?</title>
		<link>http://artemgolubev.com/no-way-to-access-overridden-methods-of-superclass-of-superclass-in-java/</link>
		<comments>http://artemgolubev.com/no-way-to-access-overridden-methods-of-superclass-of-superclass-in-java/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 03:42:28 +0000</pubDate>
		<dc:creator>Artem</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[override]]></category>
		<category><![CDATA[polymorphism]]></category>
		<category><![CDATA[super]]></category>
		<category><![CDATA[superclass]]></category>

		<guid isPermaLink="false">http://artemgolubev.com/no-way-to-access-overridden-methods-of-superclass-of-superclass-in-java/</guid>
		<description><![CDATA[Let us consider an example:

public class Test2 {
  static class TestClass1 {
      int x = 1;
      String test() {
          return "1";
      }
  }

  static class TestClass2 extends TestClass1 [...]]]></description>
			<content:encoded><![CDATA[<p>Let us consider an example:</p>
<pre>
public class Test2 {
  static class TestClass1 {
      int x = 1;
      String test() {
          return "1";
      }
  }

  static class TestClass2 extends TestClass1 {
      int x = 2;
      String test() {
          return "2";
      }
  }

  static class TestClass3 extends TestClass2 {
      int x = 3;
      int testX() {
          return ((TestClass1)this).x;
      }
      String test() {
          return super.test();
      }
  }

  public static void main(String[] args) {
      TestClass3 obj = new TestClass3();
      System.out.println(obj.testX());
      System.out.println(obj.test());
  }
}</pre>
<p>It produces expected output<br />
<code><br />
1<br />
2<br />
</code></p>
<p>The point is that there is no way to call test() method of the TestClass1 class!<br />
<code><br />
super.super.test()<br />
</code><br />
won&#8217;t compile but<br />
<code><br />
((TestClass1)this).test()<br />
</code><br />
will produce java.lang.StackOverflowError.</p>
<p>Despite that we can access superclass members of any level by casting this to appropriate class (see The Java Language Specification at <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.11.2">http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.11.2</a>), polymorphism allows us to access immediate superclass only, not overridden methods of higher levels (see The Java Language Specification at <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.9">http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.9</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://artemgolubev.com/no-way-to-access-overridden-methods-of-superclass-of-superclass-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some approach for writing equials() and hashCode()</title>
		<link>http://artemgolubev.com/some-approach-for-writing-equials-and-hashcode/</link>
		<comments>http://artemgolubev.com/some-approach-for-writing-equials-and-hashcode/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 03:40:24 +0000</pubDate>
		<dc:creator>Artem</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[DTO]]></category>
		<category><![CDATA[entity]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[hashCode]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://artemgolubev.com/some-approach-for-writing-equials-and-hashcode/</guid>
		<description><![CDATA[The problem described in details in http://www.hibernate.org/109.html
The problem is that if we implement equals()/hashCode() as comparison and hashCode() of entity&#8217;s ids (see http://djeang.blogspot.com/2005/08/override-equals-and-hashcode-methods.html) then the hashCode() (and, possibly, equals()) will change after saving entities if ids are generated by DB.
To solve this issue I can suggest to use inner classes with equals()/hashCode(). It will not [...]]]></description>
			<content:encoded><![CDATA[<p>The problem described in details in <a href="http://www.hibernate.org/109.html">http://www.hibernate.org/109.html</a><br />
The problem is that if we implement equals()/hashCode() as comparison and hashCode() of entity&#8217;s ids (see <a href="http://djeang.blogspot.com/2005/08/override-equals-and-hashcode-methods.html">http://djeang.blogspot.com/2005/08/override-equals-and-hashcode-methods.html</a>) then the hashCode() (and, possibly, equals()) will change after saving entities if ids are generated by DB.<br />
To solve this issue I can suggest to use inner classes with equals()/hashCode(). It will not affect Hibernate&#8217;s internal collections taskflow, but will allow you to use ids in equals()/hashCode() <span style="font-style: italic">after</span> entities are persisted. On other hand hashCode() and equals() will not change in your persistent objects after you have saved it.</p>
<pre>
public class Test3 {
   static class SomeEntity {
       private Integer id;

       private String data;

       public SomeEntity() {
           super();
       }

       public SomeEntity(Integer id, String data) {
           super();
           this.id = id;
           this.data = data;
       }

       public Integer getId() {
           return id;
       }

       public void setId(Integer id) {
           this.id = id;
       }

       public String getData() {
           return data;
       }

       public void setData(String data) {
           this.data = data;
       }

       public class SomeEntityId {
           private SomeEntity link = null;

           public SomeEntityId(SomeEntity link) {
               super();
               this.link = link;
           }

           @Override
           public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if ((obj == null) || (obj.getClass() != this.getClass()))
   return false;
  if (this.link.getClass() != ((SomeEntityId) obj).getLink().getClass())
   return false;

               Integer thisId = link.getId();
               Integer otherId = ((SomeEntityId) obj).getLink().getId();
               if ((thisId == null) || (otherId == null))
                   throw new RuntimeException("Id not defined!");

               return thisId.equals(otherId);
           }

           @Override
           public int hashCode() {
               Integer thisId = link.getId();
               if (thisId == null)
                   throw new RuntimeException("Id not defined!");

               return thisId.hashCode();
           }

           public SomeEntity getLink() {
               return link;
           }
       };

       public SomeEntityId getDTO() {
           return new SomeEntityId(this);
       }
   }

   public static void main(String[] args) {
       SomeEntity e0 = new SomeEntity(null, "no id");
       SomeEntity e1 = new SomeEntity(1, "e1");
       SomeEntity e2 = new SomeEntity(2, "e2");
       SomeEntity e3 = new SomeEntity(3, "e3");
       SomeEntity e33 = new SomeEntity(3, "e33");

       Set<someentity.someentityid></someentity.someentityid> aSet = new HashSet<someentity.someentityid></someentity.someentityid>();
       // aSet.add(e0.getDTO());
       aSet.add(e1.getDTO());
       aSet.add(e2.getDTO());
       aSet.add(e3.getDTO());
       aSet.add(e33.getDTO());

       System.out.println("set size: " + aSet.size());
       System.out.println("set:");
       for (SomeEntity.SomeEntityId seId : aSet) {
           SomeEntity se = seId.getLink();
           System.out.println("entity: " + se.getData());
       }
   }
}</pre>
<p>I even could suggest you to add it to entities code generation in such tools as Hibernate Tools.<br />
I would also like to mention also that SomeEntityId object could be stored in transient field of an entity.<br />
Comments are welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://artemgolubev.com/some-approach-for-writing-equials-and-hashcode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Algorithm for generating serialVersionUID for java entities</title>
		<link>http://artemgolubev.com/algorithm-for-generating-serialversionuid-for-java-entities/</link>
		<comments>http://artemgolubev.com/algorithm-for-generating-serialversionuid-for-java-entities/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 03:32:11 +0000</pubDate>
		<dc:creator>Artem</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java entity]]></category>
		<category><![CDATA[serialVersionUID]]></category>

		<guid isPermaLink="false">http://artemgolubev.com/algorithm-for-generating-serialversionuid-for-java-entities/</guid>
		<description><![CDATA[Here is some way of generating serialVersionUID for java entities.
It is stable in sense that it depends only on your schema, not JVM/time or date of creation.
On the other hand it depends on all fields in entity. If we have next n fields:
typeName_1 fieldName_1;
typeName_2 fieldName_2;
&#8230;
typeName_n fieldName_n;we could calculate
serialVersionUID =
(fieldName_1.hashCode() XOR typeName_1.hashCode()) * 31^0+
(fieldName_2.hashCode() XOR typeName_2.hashCode()) [...]]]></description>
			<content:encoded><![CDATA[<p><font class="postbody">Here is some way of generating serialVersionUID for java entities.<br />
It is stable in sense that it depends only on your schema, not JVM/time or date of creation.<br />
On the other hand it depends on all fields in entity.</font><font class="postbody"> If we have next <font style="font-style: italic">n</font> fields:<br />
typeName_1 fieldName_1;<br />
typeName_2 fieldName_2;<br />
&#8230;<br />
typeName_n fieldName_n;</font><font class="postbody">we could calculate<br />
<font class="postbody">serialVersionUID =<br />
(fieldName_1.hashCode() XOR typeName_1.hashCode()) * 31^0+<br />
(fieldName_2.hashCode() XOR typeName_2.hashCode()) * 31^1 + &#8230; +<br />
(fieldName_n.hashCode() XOR typeName_n.hashCode()) * 31^n</font><font class="postbody"> </font><font class="postbody">where fieldName_i.hashCode() is hashCode() of fieldName_i string<br />
(for int id; it will be &#8220;id&#8221;.hashCode())<br />
and typeName_i.hashCode() is hashCode() of typeName_i string<br />
(for int id; it will be &#8220;int&#8221;.hashCode())</font><font class="postbody">so, we will be independent from<br />
1) JVM<br />
2) time/date of creation<br />
and depend on<br />
<font class="postbody">1) fields order<br />
</font><font class="postbody">2) field types<br />
3) field names </font></font></font></p>
]]></content:encoded>
			<wfw:commentRss>http://artemgolubev.com/algorithm-for-generating-serialversionuid-for-java-entities/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get rid of your nested if operators!</title>
		<link>http://artemgolubev.com/get-rid-of-your-nested-if-operators/</link>
		<comments>http://artemgolubev.com/get-rid-of-your-nested-if-operators/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 03:18:07 +0000</pubDate>
		<dc:creator>Artem</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://artemgolubev.com/get-rid-of-your-nested-if-operators/</guid>
		<description><![CDATA[Every one of you know how it is disappointing that you can not use
switch
operators with strings, doubles, your custom objects, etc. But anyway sometimes it is possible to get rid of your nested ifs if you will use static maps. Let us consider an example: here we need to set JavaBean properties of certain types:

 [...]]]></description>
			<content:encoded><![CDATA[<p>Every one of you know how it is disappointing that you can not use</p>
<pre>switch</pre>
<p>operators with strings, doubles, your custom objects, etc. But anyway sometimes it is possible to get rid of your nested ifs if you will use static maps. Let us consider an example: here we need to set JavaBean properties of certain types:</p>
<pre>
 protected static Object fillTestBean(Object bean) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException {
  Method[] methods = bean.getClass().getMethods();

  for (Method method : methods) {
   if (RTTIUtils.isSetter(method)) {
    Class type = RTTIUtils.getSetterType(method);
    if (type == String.class)
     RTTIUtils.invokeSetter(bean, method, testStr);
    else if (type == boolean.class)
     RTTIUtils.invokeSetter(bean, method, testBoolean);
    else if (type == byte.class)
     RTTIUtils.invokeSetter(bean, method, testByte);
    else if (type == char.class)
     RTTIUtils.invokeSetter(bean, method, testChar);
    else if (type == short.class)
     RTTIUtils.invokeSetter(bean, method, testShort);
    else if (type == int.class)
     RTTIUtils.invokeSetter(bean, method, testInt);
    else if (type == long.class)
     RTTIUtils.invokeSetter(bean, method, testLong);
    else if (type == float.class)
     RTTIUtils.invokeSetter(bean, method, testFloat);
    else if (type == double.class)
     RTTIUtils.invokeSetter(bean, method, testDouble);
    else if (type == Boolean.class)
     RTTIUtils.invokeSetter(bean, method, testBooleanObj);
    else if (type == Byte.class)
     RTTIUtils.invokeSetter(bean, method, testByteObj);
    else if (type == Character.class)
     RTTIUtils.invokeSetter(bean, method, testCharacterObj);
    else if (type == Short.class)
     RTTIUtils.invokeSetter(bean, method, testShortObj);
    else if (type == Integer.class)
     RTTIUtils.invokeSetter(bean, method, testIntegerObj);
    else if (type == Long.class)
     RTTIUtils.invokeSetter(bean, method, testLongObj);
    else if (type == Float.class)
     RTTIUtils.invokeSetter(bean, method, testFloatObj);
    else if (type == Double.class)
     RTTIUtils.invokeSetter(bean, method, testDoubleObj);
    else if (type == Date.class)
     RTTIUtils.invokeSetter(bean, method, testDate);
   }
  }

  return bean;
 }</pre>
<p>(here all variables starting with test are constants)<br />
Seems really annoying to write all this ifs and, also what if we will need to check values? Another function will also need this nested ifs!<br />
In this case I usually do the following (factory method -like solution):</p>
<pre>
 private static final Map<class ,></class> initObjects = new HashMap<class ,></class>();
 private static boolean isCosideredType(Class type) {
  return initObjects.containsKey(type);
 }
 static {
  initObjects.put(String.class, testStr);
  initObjects.put(boolean.class, testBoolean);
  initObjects.put(byte.class, testByte);
  initObjects.put(char.class, testChar);
  initObjects.put(short.class, testShort);
  initObjects.put(int.class, testInt);
  initObjects.put(long.class, testLong);
  initObjects.put(float.class, testFloat);
  initObjects.put(double.class, testDouble);
  initObjects.put(Boolean.class, testBooleanObj);
  initObjects.put(Byte.class, testByteObj);
  initObjects.put(Character.class, testCharacterObj);
  initObjects.put(Short.class, testShortObj);
  initObjects.put(Integer.class, testIntegerObj);
  initObjects.put(Long.class, testLongObj);
  initObjects.put(Float.class, testFloatObj);
  initObjects.put(Double.class, testDoubleObj);
  initObjects.put(Date.class, testDate);
 }

 protected static Object fillTestBean(Object bean) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException {
  Method[] methods = bean.getClass().getMethods();

  for (Method method : methods) {
   if (RTTIUtils.isSetter(method)) {
    Class type = RTTIUtils.getSetterType(method);
    if (isCosideredType(type)) {
     RTTIUtils.invokeSetter(bean, method, initObjects.get(type));
    }
   }
  }

  return bean;
 }</pre>
]]></content:encoded>
			<wfw:commentRss>http://artemgolubev.com/get-rid-of-your-nested-if-operators/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
