Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / January 2006

Tip: Looking for answers? Try searching our database.

Advantages of using private static methods in a class

Thread view: 
HalcyonWild - 31 Dec 2005 12:49 GMT
Hello all,

I generally make small helper methods, private and static, inside my
java class as , for example, below.

//can use substring too, but this for example
private static String getFirstCharacter(String str)
{
   char [] c = str.toCharArray[];
   return ""+c[0];
}

I am having doubts if static methods is a good thing to do. Is it any
better or worse, if I make the method non-static. Is this a good
practice.

I searched previous group posts on Google to find if this has been
discussed before, but could not find it. (It returns almost all posts
with private and static in them).

What I understand is that the call is bound at compile time, if the
method is marked as static, and therefore you can consider it as good
as inline code. But I think I might be forgetting something, I am not
sure. (I moved to Java programming about a year ago).

I am going to read up more on that today, I thought I could have your
opinions too.

BTW, A very Happy New Year in advance. :)

Thanks.
andreas kinell - 31 Dec 2005 15:35 GMT
> Hello all,
>
[quoted text clipped - 27 lines]
>
> Thanks.

static or not should generally be a design issue rather than a performance
issue. This is true especially for larger applications. If the method
belongs to a class rather than an object, then make it static.
IMO, it is perfectly ok to make helper methods static.

andreas
Kent Paul Dolan - 31 Dec 2005 16:14 GMT
> I am having doubts if static methods is a good thing to do.

In general, if the method is related to the functionality focus
of the class, but doesn't make use of any of an instance
object's member variables, then make the method static; to
do elsewise misleads the next maintainer.

Also, it can be helpful to have a class never meant to be
instanced (instead of letting its parameterless constructor
come into existence by default, make it  "private" to prevent
that ever happening, like so:

 public class Foo
 {
   private Foo() { super(); }
 }

and no client can accidentally "new" it and not have the
compiler complain), which contains helper methods
that are universally useful. Two I'm finding handy now
are one to create an ImageIcon from a URI's PNG file's
data, and one to both add a Component to a JPanel,
and also add that Component to the JPanel's layout
manager, to allow me to create the Component without
giving it a name, in the client routine:

package edu.asu.dt.evwf;

import java.awt.Component;

import javax.swing.JPanel;
import javax.swing.ImageIcon;

import java.net.URL;

public class EvwfUtilities
{

 /**
  * Prevent accidental instancing.
  */
 private EvwfUtilities() {super();}

 /**
  * Add a Component to both a JPanel and its layout
  * manager's responsibility.
  */
 public static void addComponentToJPanel
 (
   JPanel targetJPanel,
   String componentName,
   Component componentToAdd
 )
 {
   targetJPanel.add( componentToAdd);
   targetJPanel.getLayout().addLayoutComponent
   (
     componentName,
     componentToAdd
   );
 }

 /**
 *  Returns an ImageIcon, or null if the path was
 *  invalid.
 */
 public static ImageIcon getImageIconByLocation
 (
   String imageLocation
 )
 {
   java.net.URL imgURL = EvwfUtilities.class.getResource
   (
     imageLocation
   );
   if (imgURL != null)
   {
     return new ImageIcon(imgURL);
   }
   else
   {
     System.err.println
     ( "ERROR in " +
       "EvwfUtilities.getImageIconByLocation(...)\n" +
       "Couldn't find file: " +
       imageLocation
     );
     return null;
   }
 }
}

The former allows creating of the Component right in the method call,
anonymously, like so, where the output of the createVerticalGlue()
method would otherwise need to be assigned to a local variable to
use it two places.

   EvwfUtilities.addComponentToJPanel
   (
     s_soliton,

"EvwfWaterLayersTabDeltaSurfacesControlsJCheckBoxStackVerticalGlue",
     Box.createVerticalGlue()
   );

This tends to make for clean, pretty, terse code.

FWIW

xanthian.
Roedy Green - 03 Jan 2006 00:52 GMT
>//can use substring too, but this for example
>private static String getFirstCharacter(String str)
>{
>    char [] c = str.toCharArray[];
>    return ""+c[0];
>}

That would be more quickly implemented with   str.charAt( 0 );

String.valueOf( str.charAt( 0 ) );

or even more efficiently

str.substring( 0, 1 );

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Rodrigo Zechin - 03 Jan 2006 11:32 GMT
It is not as good as inline code (unless the optmizer is able to
actually inline it), but it is faster than a public call. The big deal
is not on the method beeing static or not, but on beeing private.

A private static call generates a "invokestatic" opcode.. (code 0xB8)
A private call generates a "invokespecial" opcode.. (code 0xB7)
A public call generates a "invokevirtual" opcode.. (code 0xB6)

Both "invokestatic" and "invokespecial" are faster than
"invokevirtual", but I couldn't find any information about wich one is
faster (please note that this is obviously implementation-depedent).

Interface calls are the slowest ones... and they generate a
"invokeinterface" opcode (0xB9).

Hope this helps,
Zechin
Thomas Hawtin - 03 Jan 2006 12:29 GMT
> It is not as good as inline code (unless the optmizer is able to
> actually inline it), but it is faster than a public call. The big deal

On a modern desktop JVM inlining is no problem. Running on phones may be
a different matter.

> is not on the method beeing static or not, but on beeing private.

private and static both produce non-virtual calls, so I don't see there
is much difference there.

> A private static call generates a "invokestatic" opcode.. (code 0xB8)
> A private call generates a "invokespecial" opcode.. (code 0xB7)
> A public call generates a "invokevirtual" opcode.. (code 0xB6)

For a long time the additional cost of a virtual method call has been
effectively zero. It makes no sense to worry about.

Bytecodes are irrelevant, because if they are executed many times the
code will be compiled.

> Both "invokestatic" and "invokespecial" are faster than
> "invokevirtual", but I couldn't find any information about wich one is
> faster (please note that this is obviously implementation-depedent).
>
> Interface calls are the slowest ones... and they generate a
> "invokeinterface" opcode (0xB9).

Even an interface call will get inlined.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Roedy Green - 03 Jan 2006 16:33 GMT
>Both "invokestatic" and "invokespecial" are faster than
>"invokevirtual", but I couldn't find any information about wich one is
>faster (please note that this is obviously implementation-depedent).

Think about what each op has to do:

call static method : invokestatic eventually turns into an ordinary
machine language call (push return address and jump).

call private instance method: invokespecial turns into an ordinary
call with an extra push of the object's address.  The callee finds it
methods and fields relative to that address.

call public instance method: invokevirtual indexes into  a vtbl in the
object to get the address of the code, then calls that, pushing the
object's address.

call interface (instance method): invokeinterface is the hairiest of
all since the method it wants is not at the same place in a vtbl in
each object.  It needs a list of offsets where the method was, cached
from previous searches, and does a little lookup.  It has to push the
object's address. A lot of cleverness goes into optimising this
process since interface calls are now used so frequently.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.