Re: Perl Pro but Java Newbie: Need nudge in proper direction for
my favorite Perl routine in Java
/usr/ceo wrote:
pubic class Display {
public static void puts( String[] args ) {
for (int i=0; i<args.length; i++)
__puts( arg[i] );
}
public static void puts( String arg ) {
__puts( arg );
}
private static void __puts( String arg )
{ System.out.println( arg ); }
}
This can be reduced to:
public class Display {
public static void puts(String... args) {
for (String arg : args)
System.out.println(arg);
}
}
(Uses variable arguments and the for-each loop, both features of Java 5
and above).
import com.myorg.utils.Display;
public class TestPuts {
public static void main( String[] args ) {
puts( "A single string test." );
// This is specifically where I seem to be having trouble
passing a
// String[] array to the puts( String[] args ) call
implementation.
// But maybe the implementation itself in the Display class
isn't
// the way to go?
puts( {
"This is line 1",
"This is line 2",
"This is line 3"
} );
}
private static void puts( String[] args ) { Display.puts( args ); }
private static void puts( String arg ) { Display.puts( arg ); }
}
As others have said, this can be reduced to this:
// No need for the general import if all you have is the static function
import static com.myorg.utils.Display.puts;
public class TestPuts {
public static void main(String... args) {
puts("A single string test.");
puts("This is line 1",
"This is line 2",
"This is line 3");
}
}
Everything seems fine as far has the implementation goes in the
Display class. But maybe that's the wrong way to go about it? I
can't believe I have to use a fifty letter package name class method
to print a line to the console. (This is one of the things I hate
about Java, but anyway...)
Perl tends more towards a procedural programming paradigm, while Java is
more OOP. The act of printing to the console is theoretically rare in a
Java app, over the act of printing to an unspecified stream, e.g. it
could be a log or a console. So the console output stream is but one
stream among many, that would only be set at some configuration time.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth