tag:blogger.com,1999:blog-8355257.post8697598060912512558..comments2022-04-10T09:20:12.406-05:00Comments on View from the Fringe: Insidious CouplingBrian Gilstraphttp://www.blogger.com/profile/11799840454645440786noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-8355257.post-24158243580641769532008-05-06T16:25:00.000-05:002008-05-06T16:25:00.000-05:00The question of a static invocation is interesting...The question of a static invocation is interesting. Since creating and throwing an exception will swamp the cost in the null case, we need to consider the case where the field is not null. I wonder which of these sets of bytecode is faster:<BR/><BR/>private void doGetClass(org.sandbox.Bar);<BR/> Code:<BR/> 0: aload_1<BR/> 1: invokevirtual #4; //Method java/lang/Object.getClass:()Ljava/lang/Class;<BR/> 4: pop<BR/> 5: aload_0<BR/> 6: aload_1<BR/> 7: putfield #5; //Field b1:Lorg/sandbox/Bar;<BR/> 10: return<BR/><BR/>Versus:<BR/><BR/>private void doAssure(org.sandbox.Bar);<BR/> Code:<BR/> 0: aload_0<BR/> 1: aload_1<BR/> 2: ldc #6; //String b can't be null<BR/> 4: invokestatic #7; //Method assureNotNull:(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;<BR/> 7: checkcast #8; //class org/sandbox/Bar<BR/> 10: putfield #9; //Field b2:Lorg/sandbox/Bar;<BR/> 13: return<BR/><BR/>public static java.lang.Object assureNotNull(java.lang.Object, java.lang.String);<BR/> Code:<BR/> 0: aload_0<BR/> 1: ifnonnull 13<BR/> 4: new #10; //class java/lang/NullPointerException<BR/> 7: dup<BR/> 8: aload_1<BR/> 9: invokespecial #11; //Method java/lang/NullPointerException."<init >":(Ljava/lang/String;)V<BR/> 12: athrow<BR/> 13: aload_0<BR/> 14: areturn<BR/><BR/>}<BR/><BR/>Where we assume 0, 1, and 14 of assureNotNull will be executed in the non-null case.Brian Gilstraphttps://www.blogger.com/profile/11799840454645440786noreply@blogger.comtag:blogger.com,1999:blog-8355257.post-26190056578570233812008-05-06T14:48:00.000-05:002008-05-06T14:48:00.000-05:00Guice uses a utility method to do the checking:cla...Guice uses a utility method to do the checking:<BR/><BR/>class Objects {<BR/> public static <T> T nonNull(T t, String message) {<BR/> if (t == null) {<BR/> throw new NullPointerException(message);<BR/> }<BR/> return t;<BR/> }<BR/>}<BR/><BR/>The one benefit of this way of doing things over the getClass() call is that it is a static invocation and therefore may be faster than a virtual call.<BR/><BR/>I think creating utilities classes such as this on a per project basis is an acceptable way to handle the situation.Anonymousnoreply@blogger.com