On Fri, Mar 26, 2004 at 11:01:34AM +0100, Jacek Laskowski wrote:
> Michael Forster wrote:
> >I have inherited a load of beans and other class files from a previous
> >developer now he has done some strange things which I just would like to
> >make sure I understand what he is/was doing.
> >
> >Most of his functions (sorry All) of his functions in non ejb files are set
> >to public static This means that you don't need to create an instance of
> >the class to access the function which means he was not using proper OOP
> >techniques, suggesting he was not doing things in the correct manner.
> >
> >I would be better creating an instance of the class and then using the
> >functions in the correct manner? What are peoples views on this - I can
> >see
> >how it has made it quicker to call utility functions but the correct way
> >should be to instantiate a class and call the functions from there?
>
> Hey,
>
> It mostly depends on what the static operations have to do. If they
> don't use any instance variables (e.g via getters, setters) they're
> utilities and thus static. Although it's not seems to be OO-approach by
> some I don't see any other way to sort it out other than declaring them
> as 'public static'.
>
A common approach for avoiding making everything static is to make the
class into a singleton, so there is one static method to get the
singleton instance, then you can invoke on that instance till your
heart is content.
One tell-tale sign of when something might be better off as non-static
is when you find yourself constantly passing in the same information
over and over again. Imagine what java.io.File would look like as all
static:
File.exists("foo.txt");
File.length("foo.txt");
File.getAbsolutePath("foo.txt");
File.rename("foo.txt","bar.txt");
Sure, you could do it like that, but you'd have to resolve the string
"foo.txt" over and over again before doing any 'exists', 'lenght', or
'rename' operations. Worse yet, you could never pass the file object
to another object as a parameter! Now everyone else using the same
information needs that stupid "foo.txt" string too. Yuk!
Some things to look for.
-David