Matthew Johnson

Page Body


Part 1A Tick 7

This is the last tick a first year computer scientist had to do in 2002. So I thought I'd have some fun. The specification was a program which, given one argument, would download that URL, and print it to the screen. Given two arguments it should use the second one as a file to download it to.

This is my first attempt. As you can see it is about a page long, and has nice errors and so on
[wget.java]

I then tried to reduce it in length. The first one has a line setting the output stream to System.out if you only provide one argument. So, I then considered if I could set the standard input and output streams to the ones I wanted - you can. I also wanted to remove the try/catch blocks, since they take up a lot of space. I did this by declaring that the whole main procedure throws Exception. The extra error I wanted ( "syntax: java wget <url> [file]") I then implemented, by throwing an exception with my string in the constructor.
[wget2.java]

In this one we have put a try/catch block back in again, and got rid of the case. Here, you can see, we just use the args array without checking the length, and when this causes an exception we catch it, and ignore it, because the line that failed won't have set the in or output stream and it will stil be stdin/stdout. You can see the typical empty for loop for doing the actual copy, as in the previous example. In this program, specifying no parameters just returns - you don't get an error.
[wget3.java]

With help from Mike Cripps, we removed the try catch block, and use the ternary operator a?b:c to set the stdin and stdout to either the values they were already, or the new ones we want depending on the length of the array args. Note that this will always perform two tests and two calls of System.set{In or Out}, rather than the previous two - which are more efficient. This version, however, reduces the program to only 3 lines of code within the main {} method.
[wget4.java]

Adam Biltcliffe pointed out that (at a huge cost of efficiency) the open of the output stream could be done in the for loop, using append, so that it reopened the stream every time you write a block, and I noted that the open of the read could be done in the for loop initialiation part, so that this reduces it to 1 line of actual code, which is a for loop with an empty body
[wget5.java]

Lastly, for those of you who have noticed that java is a UTF-8 supporting language, I decided to transliterate the original program into Runic characters. This would have been quite a fun one to submit as a tick.
[wget6.java]

Part 1A students should probably not submit any of these as answers for your ticks. Tickers are generally unhappy about it - and there are some issue regarding flushing buffers etc which you will need to be able to explain.