x x said:
Is it possible to use Java as a scripting language
When writing »throw away« scripts, I am faster sometimes,
because I do not care to do everything perfect. I might
try to use such a style in Java, too, sometimes:
So I define (at least) two levels of a »Java scripting style«.
For example, I wrote this to create an SQL statement:
private static void appendToOutput
( final java.util.ArrayList<java.lang.Throwable> log,
final java.lang.StringBuilder output,
final java.sql.Connection conn )
throws java.sql.SQLException
{ final java.sql.Statement statement = conn.createStatement();
try
{ if( statement.execute( query ))
appendToOutput( log, output, statement ); }
finally
{ try
{ statement.close(); }
catch( final java.lang.Exception exception )
{ log.add( exception ); }}}
The intention was to create industrial-strength code,
but it might be somewhat hard to read and to write.
Sometimes, it might be appropriate to relax requirements.
For example: Sunny-weather coding: Assume there will be
no run-time errors (including exceptions):
private static void appendToOutput
( final java.lang.StringBuilder output,
final java.sql.Connection conn )
throws java.lang.Exception
{ final java.sql.Statement statement = conn.createStatement();
statement.execute( query )
appendToOutput( log, output, statement );
statement.close(); }
I even consider starting with this version in teaching,
because it will help beginners to see the intended flow,
before everything gets hidden unter exception-related code.
Java scripting style level 2 even does not care anymore to
close everything properly, I might even drop »private« and my
beloved »final« and »java.lang«:
static void appendToOutput( StringBuilder output, Connection conn )
throws Throwable
{ conn.createStatement().execute( query )
appendToOutput( log, output, statement ); }
This is dirty code, but as a first step in teaching it might
help to see the intended operation of this method clearly and
might be ok in teaching /if/ the drawbacks and problems of
this style also are explained and a more robust solution is
shown later.
It might also be appropriate, if one needs to get first
/quick/ implementation of something in Java (»quick and dirty«).