David Pashley: Intelligently Designed
Some one on a mailing list pointed out this cartoon and thought I'd
share it with people:
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class MarkableInputStream extends InputStream
private InputStream inputstream;
private int maxpos = 0;
private int curpos = 0;
private int mark = 0;
private ArrayList<Integer> buffer = new ArrayList<Integer>();
public MarkableInputStream(InputStream is)
inputstream = is;
@Override
public int read() throws IOException
int data;
if(curpos == maxpos)
data = inputstream.read();
buffer.add(data); maxpos++;curpos++;
else
data = buffer.get(curpos++);
return data;
@Override
public synchronized void mark(int readlimit)
mark = curpos;
@Override
public boolean markSupported()
return true;
@Override
public synchronized void reset() throws IOException
curpos = mark;
You can use it like:
if (!istream.markSupported()) istream = new MarkableInputStream(istream);This could probably be improved on, most notably by not using an ArrayList. I'm not sure what performance penalty that adds. It should be possible to use a normal array as the readlimit parameter to mark() says how many bytes the stream should record before throwing old data away in favour of new input. The class above will record all data from the start of the stream, so could result in a significant amount of memory usage. Hope you find it useful.
Reader reader = new InputStreamReader(inputstream, "ASCII");Imagine your surprise when it happily reads in non-ascii values, say UTF-8 or ISO8859-1, and converts them to a random character.
import java.io.*;
public class Example1
public static void main(String[] args)
try
FileInputStream is = new FileInputStream(args[0]);
BufferedReader reader
= new BufferedReader(new InputStreamReader(is, args[1]));
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
catch (Exception e)
System.out.println(e);
beebo david% java Example1 utf8file.txt ascii I t rn ti n liz ti n beebo david% java Example1 utf8file.txt utf8 I t rn ti n liz ti nSo, I hear you ask, how do you get Java to be strict about the conversion. Well, answer is to lookup a Charset object, ask it for a CharsetDecoder object and then set the onMalformedInput option to CodingErrorAction.REPORT. The resulting code is:
import java.io.*;
import java.nio.charset.*;
public class Example2
public static void main(String[] args)
try
FileInputStream is = new FileInputStream(args[0]);
Charset charset = Charset.forName(args[1]);
CharsetDecoder csd = charset.newDecoder();
csd.onMalformedInput(CodingErrorAction.REPORT);
BufferedReader reader
= new BufferedReader(new InputStreamReader(is, csd));
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
catch (Exception e)
System.out.println(e);
This time when we run it,we get:
beebo david% java Example2 utf8file.txt ascii java.nio.charset.MalformedInputException: Input length = 1 beebo david% java Example2 utf8file.txt utf8 I t rn ti n liz ti nOn a slightly related note, if anyone knows how to get Java to decode UTF32, VISCII, TCVN-5712, KOI8-U or KOI8-T, I would love to know.
However, RDBO achieves its perl speed by aggressive inlining of stuff etc. - for example the main object retrieval function in RDBO's manager class is >3000 lines in a single sub. DBIC values extensibility over a few extra sub calls, so methods are much more broken out and there are many more ways to hook into the DBIC execution process to extend.Also its idea of resultsets is something I really love. Here's a small example to illustrate that:
my $user_rs = $schema->resultset('User')->search( registered => 1 );
$user_rs = $user_rs->search(
comment.title => 'Foo' ,
join => 'article' => 'comment' ,
order_by => 'user.name',
,
);
# no sql executed yet. # now you can use your resultset as an iterator or query a list of User # objects from it or ..
while (my $user = $user_rs->next) ...
# or
my $count = $user_rs->count;Using these resultset makes it extremely easy to built up queries piece by piece and to work together well with, for example, a templating system. You don't need to fetch all row-objects and give them to your template. You can just pass the iterator to the template library. There's a lot more to say about this two object-relational mappers (for example RDBO supports prefetching of multiple one-to-many at once, which DBIC doesn't), but maybe you just should take a look yourself. I personally prefer DBIx::Class for its vast extensibility.
use strict;
use warnings;
use Benchmark qw(:all) ;
use Foo;
use DBI;
sub class_dbi
for my $foo (Foo->retrieve_all())
my $bar = $foo->bar;
sub dbi
my $dbh = DBI->connect("dbi:Pg:dbname=$db;host=$host",$user, $passwd);
my $sth = $dbh->prepare("SELECT * FROM foos;");
$sth->execute();
while(my $row = $sth->fetchrow_hashref())
my $bar = $row-> bar ;
cmpthese(100,
'Class::DBI' => 'class_dbi();',
'DBI' => 'dbi();',
);
The results:
brick david% perl benchmark.pl
s/iter Class::DBI DBI
Class::DBI 10.3 -- -97%
DBI 0.351 2845% --
Class::DBI is more than 28 times slower than using DBI directly. I'm
hoping that someone will now tell me "Oh you just do blah", otherwise
I'm going to have to rewrite some of my code. One thing to learn from
this is that reduction in development time can often cost you more in
other areas, and it's often runtime performance.
Update: It appears that the bug is that
Class::DBI::Pg does't set the Essential list of columns, so
Class::DBI uses the primary column. you can fix this by adding the
following to your database modules:
__PACKAGE__->columns(Essential => __PACKAGE__->columns);Remember you'll need to do that for each of your modules; you won't be able to do it in your superclass, as you won't have discovered your columns yet. This has increased performance, but not massively. New timings (with the addition of using Class::DBI through an iterator):
s/iter Class::DBI it Class::DBI DBI Class::DBI it 6.35 -- -2% -94% Class::DBI 6.23 2% -- -94% DBI 0.350 1714% 1680% --Update 2: It appears that further speedgains can be made by not using Class::DBI::Plugin::DateTime::Pg to convert the three timestamp columns in my table into DateTime objects.:
s/iter Class::DBI it Class::DBI DBI Class::DBI it 1.26 -- -11% -72% Class::DBI 1.12 12% -- -69% DBI 0.350 260% 220% --
ALTER TABLE entries
ALTER COLUMN created TYPE TIMESTAMP WITH TIME ZONE
USING TIMESTAMP WITH TIME ZONE 'epoch' + created *interval '1 second';
With thanks to the PostgreSQL
manual for saving me hours working out
how to do this.
gettimeofday( 1129717666, 622797 , NULL) = 0
access("/etc/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
access("./network/admin/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
access("/etc/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
access("./network/admin/sqlnet.ora", F_OK) = -1 ENOENT (No such file or directory)
fcntl64(155815832, F_SETFD, FD_CLOEXEC) = -1 EBADF (Bad file descriptor)
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
times(NULL) = -1808543702
.
.
.
Has your client been up for more that 180 days? Well done; you've
just come across the same bug that has bitten two of our customers in
the last week. Back in the days of Oracle 8, there was a fairly imfamous
bug in the Oracle client where new connections would fail if the client had
been up for 248 days or more. This got fixed, and wasn't a problem with
Oracle 9i at all. Now Oracle have managed to introduce a similar bug in
10.2.0.1, although in my experience the number of days appears to be
shorter (180+).
Thankfully, this has been fixed in the 10.2.0.2
Instant Client. More information can be found on forums.oracle.com
and www.redhat.com.
Picture this: nervous first-year, short shorts, longer t-shirt, brown dress shoes, newly broken glasses taped together with white sports tape. He begins his first varsity tennis practice, he is excited. So excited in fact that he tips over the ball hopper while doing warm-ups, spilling tennis balls all over the court. That’s when they started calling me ‘Trainwreck,’ coach wanted to call me ‘Shoes,’ but the team agreed on Trainwreck,. Andrew ‘Trainwreck’ Kessel ‘07 said.See also Athlete of the Week (scroll down to “Week 29”) and Cobbers Beat Scots 7-2 in Moorhead . I never even played intramural sports in college, so I can only appreciate Andrew’s success vicariously. Also, I’m now hosting a website for Jonah’s nascent photography business, Kessel Imaging. (Kids these days, they want to do everything with Flash! In my day, we hand-coded HTML and CSS.)
if (string != null && strong.equals("string"))
This quickly becomes tiresome and the test for null distracts from
the meaning of the code. Fortunately I was reminded of an improvement
for string objects. Ideally, we should all be writing comparison
conditionals like rvalue == lvalue. (an rvalue mostly is an expresion
you can't assign to). The most common rvalue is a literal value like a
string constant. The
advantage of getting into the habit of writing code like this is that
you'll discover at compile time when you accidentally write =
rather than ==. Because you can't assign to an rvalue, the
compiler will complain. What makes this interesting from a java string
point of view is that you can call methods on string literals. Comparing
a variable to a string literal, rather than calling .equals()
on a variable is that the string literal is not going to be null, so you
can remove the test for null and simplify the code:
if("string".equals(string))
I know it's not everyone's cup of tea, but I prefer it to testing for
null every time I look at a string. The other thing is that I've been
reading Hardcore Java by Robert Simmons at work. Considering I've only
got a few pages in so far. I've received a surprisingly large number of
ideas to improve my code.
The one that sticks in my head is using assert for doing
post and pre conditions on your functions. Using asserts have number of
advantages over throwing exceptions, including the fact they get
optimised away when you do a production release. In Eddie, during a
<feed> element I determine the version of Atom that we are
parsing. This had a number of nested if/else if/else blocks. At
the end of the function, I wanted to make sure I had set the version
string to something, so had the following code:
if (!this.feed.has("format"))
throw new SAXParseException("Failed to detect Atom format", this.locator);
However, using assertions I can write this as
assert(this.feed.has("format")) : "Failed to detect Atom format";
I highly recommend the Hardcore java book if you want to improve your java
programming. It includes sections on the new features of Java 1.5 and
using collections. I've made a couple of other cleanups including going through member
variable access specifiers to make sure they are right and making
several public methods and variables and making them
priavte. I also have a couple of ideas about refactoring some
of the code to clean it up. Redesigning and refactoring code is almost
more fun than writing it in the first place. You get to be in
competition with yourself, challenging yourself to write better code
and end up with cleaner code in the process.
A couple of things I want to do in the near future is use a profiler
and code coverage tools. If anyone has recommendations for either of
these tools that integrates nicely with eclipse, I'd love to know.
print join ", ", map ord, split //, $foo;This mess of perl might be easier to understand if I put the brackets in:
print join (", ", map( ord, split( //, $foo)));
What this does is split $foo into a list of characters. It then uses
map to run ord() on each item in the list to return a new list
containing the numeric character values. We then join these again with
", " to make the output easier to read.
david% perl -e 'print join ", ", map ord, split //, "word";' 119, 111, 114, 100The map function is familiar to functional programmers and is very powerful, but beware it can reduce the clarity of your code. [0] Me
// Copyright 2006 David Pashley <david@davidpashley.com>
// Licensed under the GPL version 2
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class Date
private Calendar date;
static String[] date_formats =
"yyyy-MM-dd'T'kk:mm:ss'Z'", // ISO
"yyyy-MM-dd'T'kk:mm:ssz", // ISO
"yyyy-MM-dd'T'kk:mm:ss", // ISO
"EEE, d MMM yy kk:mm:ss z", // RFC822
"EEE, d MMM yyyy kk:mm:ss z", // RFC2882
"EEE MMM d kk:mm:ss zzz yyyy", // ASC
"EEE, dd MMMM yyyy kk:mm:ss", //Disney Mon, 26 January 2004 16:31:00 ET
"-yy-MM",
"-yyMM",
"yy-MM-dd",
"yyyy-MM-dd",
"yyyy-MM",
"yyyy-D",
"-yyMM",
"yyyyMMdd",
"yyMMdd",
"yyyy",
"yyD"
;
public Date(String d)
SimpleDateFormat formatter = new SimpleDateFormat();
d = d.replaceAll("([-+]\\d\\d:\\d\\d)", "GMT$1"); // Correct W3C times
d = d.replaceAll(" ([ACEMP])T$", " $1ST"); // Correct Disney timezones
for (int i = 0; i < date_formats.length; i++)
try
formatter.applyPattern(date_formats[i]);
formatter.parse(d);
date = formatter.getCalendar();
break;
catch(Exception e)
// Oh well. We tried
The only date formats I can't get it to parse are <4-digit
year>-<day of year> and <2digit year><day of
year> (e.g. 2003-335 and 03335 for
2003-12-01). If you can add support for those and other date formats
I'll gladly take patches.
Next.