<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Databases and Life &#187; Coding</title>
	<atom:link href="http://www.databasesandlife.com/category/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.databasesandlife.com</link>
	<description>Adrian Smith's blog</description>
	<lastBuildDate>Wed, 14 Dec 2011 10:13:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Wicket auto-complete text fields</title>
		<link>http://www.databasesandlife.com/wicket-auto-complete-auto-suggest-text-fields/</link>
		<comments>http://www.databasesandlife.com/wicket-auto-complete-auto-suggest-text-fields/#comments</comments>
		<pubDate>Tue, 30 Aug 2011 16:50:35 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=894</guid>
		<description><![CDATA[It&#8217;s modern practice in web applications to augment text fields with suggestions while one types. There are plenty of Javascript libraries out there to do that, and plenty of integrations with the Java web framework Wicket out there as well, but somehow none quite did exactly what I wanted, so I&#8217;ve rolled my own Wicket code (based [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s modern practice in web applications to augment text fields with suggestions while one types. There are plenty of Javascript libraries out there to do that, and plenty of integrations with the Java web framework <a href="http://wicket.apache.org/" target="_blank">Wicket</a> out there as well, but somehow none quite did exactly what I wanted, so I&#8217;ve rolled my own Wicket code (based on JQuery). And here they are.</p>
<p>What I wanted, but what other Wicket / Javascript libraries did not do, were:</p>
<ul>
<li>I wanted to allow the user to type <strong>multiple values</strong>. If you compose a message in Gmail, you want to be able to enter multiple recipients, not just one.</li>
<li>I wanted to have the option to either allow the user to type in <strong>options which were not presented</strong> (e.g. like when composing a message in Gmail, or typing in tags into Stack Overflow) or <strong>restrict</strong> them to the options presented (like recipients in Facebook)</li>
<li>I wanted to either allow the <strong>options to be included in the HTML</strong> page (e.g. for a set of 10 options, there is no point forcing the user to wait for a server round-trip to fetch matching options), or allow the options to be <strong>fetched from the server</strong> (e.g. if there are 1M options, they can&#8217;t be included in the HTML page).</li>
<li>I wanted the <strong>API to be incredibly simple</strong>. I want to include a single <code>&lt;input&gt;</code> into the Wicket HTML document, create the object in Java using a constructor, and attach the data source (client-side or server-side) in a single line.</li>
</ul>
<p>Surprisingly all of the above are not particularly easy to achieve simultaneously. But they are now done:</p>
<ul class="tight">
<li><a href="http://www.databasesandlife.com/blog-attachments/databasesandlife-util-javadoc/com/databasesandlife/util/wicket/MultipleValueAutoSuggestTextField.html"><code>MultipleValueAutoSuggestTextField</code></a> (auto-suggest = can also type in other values)</li>
<li><a href="http://www.databasesandlife.com/blog-attachments/databasesandlife-util-javadoc/com/databasesandlife/util/wicket/MultipleValueAutoCompleteTextField.html"><code>MultipleValueAutoCompleteTextField</code></a> (auto-complete = only those values allowed)</li>
</ul>
<p>And coupled with my newly created extensive multi-lingual location hierarchy database (hierarchy in the sense of 2nd district -&gt; Vienna -&gt; Austria -&gt; Europe -&gt; World, multi-lingual in the sense I have these displayable strings in various languages), allows me to create a MultipleValueLocationTextField subclass, which can be included in a host HTML page in one line of HTML and one line of Java, and which synchronizes its data with a <code>Location[]</code> in the client code (e.g. straight from/to a domain object), and it looks like this:</p>
<p><img src="http://www.databasesandlife.com/blog-attachments/20110830-wicket-auto-complete-drop-down.png" alt="" width="474" height="131" /></p>
<p>The source for the two Wicket fields linked to above is LGPL. <a href="http://www.databasesandlife.com/blog-attachments/databasesandlife-java-util.zip">Download Databases &amp; Life Util ZIP</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/wicket-auto-complete-auto-suggest-text-fields/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Converting an SVG to a PDF programmatically</title>
		<link>http://www.databasesandlife.com/svg-to-pdf/</link>
		<comments>http://www.databasesandlife.com/svg-to-pdf/#comments</comments>
		<pubDate>Sat, 20 Aug 2011 13:08:47 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=869</guid>
		<description><![CDATA[Searching for this topic on the web led to various libraries, all of which were no doubt very powerful, all of which were extremely large and difficult to use if one didn&#8217;t know how. Plenty of advice existed on the internet, &#8220;use library X&#8221;, but when the library has hundreds of thousands of lines that [...]]]></description>
			<content:encoded><![CDATA[<p>Searching for this topic on the web led to various libraries, all of which were no doubt very powerful, all of which were extremely large and difficult to use if one didn&#8217;t know how. Plenty of advice existed on the internet, &#8220;use library X&#8221;, but when the library has hundreds of thousands of lines that isn&#8217;t really enough information. I didn&#8217;t even mind in which programming language the solution was to be written.</p>
<p>After hours of searching, reading Javadocs, reading source, and experimenting, I finally came up with the following lines of Java code.</p>
<p>Alas, this method can only convert from a SVG <em>file</em> to a PDF<em> file</em>, i.e. these have to be files existing on the disk, they cannot be URLs, in memory, cannot be streamed, and the SVG cannot be an in-memory DOM object. My SVG is dynamic: I&#8217;m altering/creating it at runtime (after all, if I wasn&#8217;t doing that, I could just save the PDF somewhere statically in the first place and wouldn&#8217;t need to do the conversion). And I want to deliver the PDF to the browser so streaming would be good for me. But no matter, I use <a href="http://download.oracle.com/javase/6/docs/api/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String%29">File.createTemporaryFile</a> together with <a href="http://download.oracle.com/javase/6/docs/api/java/io/File.html#deleteOnExit()">deleteOnExit</a> to create these files, and just ignore the fact that if the JVM exits abnormally, e.g. the computer suffers from a power failure, these files will never get deleted, and, over a long enough time-span, will fill up the disk until the computer fails.</p>
<p>Here are the lines:</p>
<pre>import org.apache.batik.apps.rasterizer.DestinationType;
import org.apache.batik.apps.rasterizer.SVGConverter;
import ...

<strong>// SVG is created programatically as a DOM Document </strong>
Document svgXmlDoc = ...

<strong>// Save this SVG into a file </strong>
File svgFile = File.createTempFile("graphic-", ".svg");
svgFile.deleteOnExit();
TransformerFactory tFac = TransformerFactory.newInstance();
Transformer transformer = tFac.newTransformer();
DOMSource source2 = new DOMSource(svgXmlDoc);
FileOutputStream fOut = new FileOutputStream(svgFile);
try { transformer.transform(source2, new StreamResult(fOut)); }
finally { fOut.close(); }

<strong>// Convert the SVG into PDF </strong>
File outputFile = File.createTempFile("result-", ".pdf");
outputFile.deleteOnExit();
SVGConverter converter = new SVGConverter();
converter.setDestinationType(DestinationType.PDF);
converter.setSources(new String[] { svgFile.toString() });
converter.setDst(outputFile);
converter.execute();</pre>
<p>And I have the following JARs (search using Google to find the projects and download them):</p>
<ul class="tight">
<li>avalon-framework-4.2.0.jar</li>
<li>batik-all-1.7.jar</li>
<li>commons-io-1.3.1.jar</li>
<li>commons-logging-1.0.4.jar</li>
<li>fop-0.95.jar</li>
<li>log4j-1.2.15.jar</li>
<li>xml-apis-ext.jar</li>
<li>xmlgraphics-commons-1.3.1.jar</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/svg-to-pdf/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The method invocation operator, and expressions, in PHP</title>
		<link>http://www.databasesandlife.com/the-method-invocation-operator-and-expressions-in-php/</link>
		<comments>http://www.databasesandlife.com/the-method-invocation-operator-and-expressions-in-php/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 14:01:48 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=826</guid>
		<description><![CDATA[PHP is a weird language. $x = new Foo(); print $x-&#62;bar(); works fine as you&#8217;d expect. but print new Foo()-&#62;bar(); print (new Foo())-&#62;bar(); all do not work. I do not understand how you can build an expression parser, where the code above works, and the code below does not. It&#8217;s almost as if &#8220;$x = [...]]]></description>
			<content:encoded><![CDATA[<p>PHP is a weird language.</p>
<pre>
$x = new Foo();
print $x-&gt;bar();
</pre>
<p>works fine as you&#8217;d expect. but</p>
<pre>
print new Foo()-&gt;bar();
print (new Foo())-&gt;bar();
</pre>
<p>all do not work.</p>
<p>I do not understand how you can build an expression parser, where the code above works, and the code below does not. It&#8217;s almost as if &#8220;$x = new XXX(xxx)&#8221; a separate case searched for by the parser?</p>
<p>I mean if you have an expression parser capable of handling brackets, i.e. (1+2)*4, and you have the expression (new Foo()) and you have the concept of $object->method() then how can it possibly not work?</p>
<pre>
$ <strong>cat -n x.php</strong>
     1  &lt;?php
     2
     3  class Foo {
     4     function bar() { return 4; }
     5  }
     6
     7  $foo = new Foo();
     8  print $foo-&gt;bar();
     9
    10  print (new Foo())-&gt;bar();

$ <strong>php -e x.php</strong>
Parse error: syntax error, unexpected T_OBJECT_OPERATOR
in /home/adrian/x.php on line 10
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/the-method-invocation-operator-and-expressions-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visibility &amp; type inference in Java</title>
		<link>http://www.databasesandlife.com/visibility-type-inference-in-java/</link>
		<comments>http://www.databasesandlife.com/visibility-type-inference-in-java/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 16:51:45 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=790</guid>
		<description><![CDATA[In Java, private classes can be used in signatures of public interfaces. This makes no sense! I had a situation the other day that I wanted to break one line down into multiple lines for readability. But it wasn&#8217;t possible. If I wrote the code as one line it worked; multiple lines it didn&#8217;t. This [...]]]></description>
			<content:encoded><![CDATA[<p><strong>In Java, private classes can be used in signatures of public interfaces. This makes no sense!</strong></p>
<p>I had a situation the other day that I wanted to break one line down into multiple lines for readability. But it wasn&#8217;t possible. If I wrote the code as one line it worked; multiple lines it didn&#8217;t. This is rather inconsistent! The following public class demonstrates the situation:</p>
<pre>
public class PublicObject {
    <strong>private </strong>class <strong>PrivateObject </strong>{ }

    private PrivateObject x;
    <strong>public </strong>void setX(<strong>PrivateObject </strong>x) { this.x=x; }
    <strong>public </strong><strong>PrivateObject </strong>getX() { return x; }
}
</pre>
<p>As you see, PublicObject instances are allowed to provide public methods which take and return PrivateObject instances, however that doesn&#8217;t make a lot of sense, as you can&#8217;t write client code which creates or manipulates PrivateObject instances.</p>
<p>But in fact that&#8217;s not true. Java does, in a very few places, use type inference (more info <a href="http://james-iry.blogspot.com/2009/04/java-has-type-inference-and-refinement.html">here</a>) to guess the type of objects, to save the programmer typing. And the public/private rule enforcement seems to be:</p>
<ul class=tight>
<li>You get an error if you write the name of a private class anywhere in your client source</li>
<li>If you just use type inference to use the object, and avoid ever explicitly writing the class name in your source code, it compiles and works fine.</li>
</ul>
<p>So the following code works:</p>
<pre>
myPublicObject.setX(myPublicObject.getX());
</pre>
<p>but the following code doesn&#8217;t:</p>
<pre>
PrivateObject x = myPublicObject.getX();
myPublicObject.setX(x);
</pre>
<p>And the reason the first line works is that, although the code is clearly using PrivateObject instances, it doesn&#8217;t ever use the word &#8220;PrivateObject&#8221; in the source code.</p>
<p>Surely, whether you explicitly reference the class in your code, or implicitly using the language&#8217;s type inference, are just syntactic differences only, and you should either be allowed to do both or neither.</p>
<p>(In .NET, the equivalent code does indeed not compile.)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/visibility-type-inference-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Position of the star when declaring C pointers</title>
		<link>http://www.databasesandlife.com/position-of-the-star-when-declaring-c-pointers/</link>
		<comments>http://www.databasesandlife.com/position-of-the-star-when-declaring-c-pointers/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 15:51:29 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=764</guid>
		<description><![CDATA[There is a great debate in C-style languages about the position of the asterisk and the space when declaring pointers: MyType *x; // Original C style MyType* x; // The other style I was reminded of this when attending an Objective-C training course recently. Apple&#8217;s tools create declarations of the first form, the trainer preferred [...]]]></description>
			<content:encoded><![CDATA[<p>There is a great debate in C-style languages about the position of the asterisk and the space when declaring pointers:</p>
<pre>MyType *x; // Original C style
MyType* x; // The other style</pre>
<p>I was reminded of this when attending an Objective-C training course recently. Apple&#8217;s tools create declarations of the first form, the trainer preferred the second form. I remember having an opinion on this debate back when I first came across the second form, good to see that debate is still alive and well.</p>
<p>The logic for the second type is that x is a &#8220;pointer to MyType&#8221; and therefore one should separate the type (MyType*) from the name of the variable. That would make sense however the syntax of C doesn&#8217;t work that way. The line</p>
<pre>MyType* x,y;</pre>
<p>is confusing, it appears to imply that both x and y are pointers to MyType. I have read many times that this is dangerous, and the solution is never to declare more than one variable on a line.</p>
<p>However in fact it&#8217;s not dangerous at all, and one needn&#8217;t remember an arbitrary rule to remove this danger. The star is in the wrong place, and that&#8217;s where the confusion comes from. If one writes the statement differently:</p>
<pre>MyType *x, y;</pre>
<p>Then it becomes clear that only x is the pointer and y is not a pointer.</p>
<p>Therefore, I must side with Apple&#8217;s tools as opposed to our trainer. One has to use the syntax as it was intended, and it was intended that the type is adopted by all variables in a declaration, the level of indirection (pointers) however is not. As that&#8217;s the case, and cannot/will not be changed, the level of indirection (the number of stars) must be next to the variable name, and not the type.</p>
<p>In my opinion, to write the star next to the type should be a compile error.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/position-of-the-star-when-declaring-c-pointers/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t use the @author Javadoc tag</title>
		<link>http://www.databasesandlife.com/dont-use-the-author-javadoc-tag/</link>
		<comments>http://www.databasesandlife.com/dont-use-the-author-javadoc-tag/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 13:23:17 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=684</guid>
		<description><![CDATA[In Javadoc there is an @author tag so you can specify who originally wrote the class, method, etc., being documented. /**  * This represents a user of the system as stored in Oracle.  * @author Adrian Smith  */ class User { ... } But really, what&#8217;s the point, when version-control tools such as &#8220;svn log&#8221;, [...]]]></description>
			<content:encoded><![CDATA[<p>In Javadoc there is an @author tag so you can specify who originally wrote the class, method, etc., being documented.</p>
<pre>/**
 * This represents a user of the system as stored in Oracle.
 * <strong>@author Adrian Smith</strong>
 */
class User { ... }
</pre>
<p>But really, what&#8217;s the point, when version-control tools such as &#8220;svn log&#8221;, &#8220;svn blame&#8221; and exist? (And any project where it would be necessary to determine the author necessarily involves more than one person, any (at least) any project involving more than one person requires a version control system.)</p>
<ul class="tight">
<li>The information in version-control log is always accurate</li>
<li>The information in the source file might originally have been accurate, but the class may have been heavily refactored by someone else</li>
<li>Some people start classes by copy/pasting another file and changing it: the tag will be wrong in those cases (the people who do that aren&#8217;t going to be the people who read/write/update doc)</li>
</ul>
<p>I suppose there could be a case for using @author in the cases that the source is distributed without any version control information. But at least on the projects I work on, that&#8217;s never the case.</p>
<p>The project I&#8217;m currently working on has random @author tags all over the place, due to various copy/paste action and refactoring. The @author tag bears no relation to the person who last changed the code, who knows about it, or even who&#8217;s still in the company. Wrong documentation is worse than no documentation, as you might be tempted to believe wrong documentation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/dont-use-the-author-javadoc-tag/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Checked exceptions and Java Callables</title>
		<link>http://www.databasesandlife.com/checked-exceptions-and-java-callables/</link>
		<comments>http://www.databasesandlife.com/checked-exceptions-and-java-callables/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 11:45:03 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=624</guid>
		<description><![CDATA[Java supports checked exceptions. Many people have strong opinions about if they are good or bad. I believe they are good, but let&#8217;s agree that Java has them and they&#8217;re not going away. (Any exception extending &#8220;Exception&#8221;, which can to be thrown from a method, must be declared at the end of method&#8217;s signature, and [...]]]></description>
			<content:encoded><![CDATA[<p>Java supports checked exceptions. Many people have strong opinions about if they are good or bad. I believe they are good, but let&#8217;s agree that Java has them and they&#8217;re not going away.</p>
<p>(Any exception extending &#8220;Exception&#8221;, which can to be thrown from a method, must be declared at the end of method&#8217;s signature, and any caller of the method must handle the exception or itself declare to throw that type of exception; Any exception extending &#8220;RuntimeException&#8221; need not be declared on method signatures. A programmer is free to choose which superclass to extend when designing their own exceptions.)</p>
<p>There are two ways of dealing with tasks which should be run in the future, both of which are very inelegant w.r.t. checked exception handling.</p>
<ul>
<li><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Runnable.html">Runnable</a> &#8211; the task (method) may not throw any checked exception, as the &#8220;run&#8221; method does not declare any checked exceptions (as &#8220;Runnable&#8221; defines the method; and the interface, provided by Java, cannot know what exceptions your code may throw)</li>
<li><a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Callable.html">Callable</a> &#8211; &#8220;Solves&#8221; the problem with Runnable in that the task/method may throw a checked exception. To achieve this the interface declares &#8220;throws Exception&#8221; meaning <em>any </em>checked exception may be thrown. This means the caller must handle &#8220;catch Exception&#8221; i.e. handle all checked exceptions, which again gives you no safety as to which exceptions can actually be thrown (the purpose of checked exceptions in the first place)</li>
</ul>
<p>(In addition, the difference between these two interfaces is solely the way they deal with exceptions. But you wouldn&#8217;t know that, or know which interface uses which strategy, by looking at their name!)</p>
<p>What one would need would be to extend the generics system to deal with exceptions. For example:</p>
<pre>interface Callable&lt;V,<strong>E</strong>&gt; {
    V call() <strong>throws E</strong>;
}

class MyException <strong>extends Exception</strong> { .. }

class MyCallable implements Callable&lt;MyObject, <strong>MyException</strong>&gt; {
    MyObject call() <strong>throws MyException </strong>{
        throw new MyException(); // ok to throw, signature declares it
    }
}

void usingCallable(MyCallable e) {
    e.call(); // <strong>error: must catch MyException</strong>
}</pre>
<p>The generic parameter &#8220;E&#8221; would have to be a list of exception classes as opposed to just one class.</p>
<p><strong>Update: </strong>I was surprised to find out that using generic parameters for checked exceptions is basically supported! However it still isn&#8217;t very useful, as:</p>
<ul class=tight>
<li>There is no way for the generic parameter E to be a <em>list </em>of exceptions</li>
<li>Callable/Runnable interfaces provided by Java do not support it</li>
<li>All the useful ThreadPool code that comes with Java support only Callable/Runnable</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/checked-exceptions-and-java-callables/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The special variable &#8220;_&#8221;</title>
		<link>http://www.databasesandlife.com/the-underscore-variable/</link>
		<comments>http://www.databasesandlife.com/the-underscore-variable/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 14:05:39 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=479</guid>
		<description><![CDATA[Reading this blog post, Destructuring binds in Ruby just now reminded me of a feature I love about Prolog which I wish would make it into other languages. Firstly, I love assigning a list to a list of lvalues i.e. variables; this is possible in both PHP and Perl which I use regularly; and no [...]]]></description>
			<content:encoded><![CDATA[<p>Reading this blog post, <a href="http://citizen428.net/archives/427-Destructuring-binds-in-Ruby.html">Destructuring binds in Ruby</a> just now reminded me of a feature I love about Prolog which I wish would make it into other languages.</p>
<p>Firstly, I love assigning a list to a list of <a href="http://cplus.about.com/od/glossar1/g/lvalue.htm">lvalues</a> i.e. variables; this is possible in both PHP and Perl which I use regularly; and no doubt many other languages. (But not Java: why not!?)</p>
<pre>
    ($a, $b) =      ($b, $a);  // Perl
list($a, $b) = array($b, $a);  // PHP
</pre>
<p>PHP, as always, wins in inelegance, having the left side syntactically different to the right side. While it&#8217;s obviously the case that a list of values and a list of lvalues are technically different, I don&#8217;t think this difference should be expressed in the syntax.</p>
<p>I mean, in most languages you write e.g. $foo=4 and $bar=$foo; in both those cases you write $foo but yet they do something different (lvalue and rvalue); given that you write them the same there i think the same should apply to lists.</p>
<p>But I digress &#8211; What I want to mention is using &#8220;underscore&#8221; to mean &#8220;any variable&#8221;. I first saw this in Prolog.</p>
<p>For example, imagine you have to implement an interface (e.g. in Java), it requires you to write a function taking two parameters, but one of the parameters you don&#8217;t care about. Wouldn&#8217;t it be nice to write</p>
<pre>
interface ExistingApi {
   public void createObject(String name, Object otherInformation);
}

class MyInstanceOfTheApi {
   public void createObject(String name, _) {
      ...
   }
}
</pre>
<p>i.e. this shows clearly you do not care about the second parameter. </p>
<p>In current Java (and all languages I program including Perl, PHP) you have to give all variables a name even if you don’t use them, either in function definitions or in “assign to a list” scenarios mentioned above. It is then left as an exercise to the reader to determine if these variables are used or not, and indeed an exercise to the writer to name the variable they are never going to use.</p>
<p>I mean yes, technically you can actually just call variables “_” (or “$_” (except in Perl where “$_” already means something)) but that would then be a coding convention as opposed to a language feature, and who knows if the coding convention is actually used correctly by a programmer. (If “_” is a variable there’s nothing stopping someone from using its value.)</p>
<p>And then you have the problem if you have two variables you don&#8217;t care about, you can&#8217;t call them both &#8220;_&#8221;.</p>
<p>By the way, <a href="http://books.google.com/books?id=VjHk2Cjrti8C&#038;printsec=frontcover&#038;dq=Programming+in+Prolog&#038;source=bl&#038;ots=IHQtLmvJqC&#038;sig=RFhnlEzs_Nu_GkwTQD_Z3som5Ds#v=onepage&#038;q&#038;f=false">Programming in Prolog</a> is an excellent book.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/the-underscore-variable/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java is lacking a String &#8220;join&#8221; function</title>
		<link>http://www.databasesandlife.com/java-is-lacking-a-string-join-function/</link>
		<comments>http://www.databasesandlife.com/java-is-lacking-a-string-join-function/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 10:49:49 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=465</guid>
		<description><![CDATA[Between Java 1.0 and Java 1.3 (1996-2002 according to Wikipedia) there was no way to split strings into an array or a list. In Java 1.4 the authors of Java saw it fit to introduce a method to split strings, String csvData = "field1,field2,field3"; String[] fields = csvData.split(","); However they did not introduce a method [...]]]></description>
			<content:encoded><![CDATA[<p>Between Java 1.0 and Java 1.3 (1996-2002 according to Wikipedia) there was no way to split strings into an array or a list.</p>
<p>In Java 1.4 the authors of Java saw it fit to introduce a method to split strings,</p>
<pre>String csvData = "field1,field2,field3";
String[] fields = csvData.split(",");
</pre>
<p>However they did not introduce a method to &#8220;join&#8221; strings! Even in Java 7 there is no way to do this, e.g. via a static String.join method (2002-now).</p>
<p>OK I realize this is not &#8220;rocket science&#8221;, and I appreciate it exists in various versions in various third-party libraries, but still, it&#8217;s something every program needs to do at some point, it&#8217;s annoying to have to re-define it or think about it for each application.</p>
<p>For example, in one project I was working on in the last 6 months, such a function was created, and then had a bug! (OK but to be fair, that was not the only bug in the application!)</p>
<p>Come on, I mean this is a totally trivial function, totally necessary, available in all scripting lanuags why is it still not in Java?!</p>
<p>(P.S. Want to see an &#8220;enterprise java&#8221; solution to this problem? Check out the <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Joiner.html#method_summary">number of methods on this class</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/java-is-lacking-a-string-join-function/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Java varargs: inconsistent behaviour if you pass an array</title>
		<link>http://www.databasesandlife.com/java-varargs-inconsistent-behaviour-if-you-pass-an-array/</link>
		<comments>http://www.databasesandlife.com/java-varargs-inconsistent-behaviour-if-you-pass-an-array/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 10:39:07 +0000</pubDate>
		<dc:creator>adrian</dc:creator>
				<category><![CDATA[Broken]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.databasesandlife.com/?p=461</guid>
		<description><![CDATA[In Java 1.4 there was the function Arrays.asList. You could pass it an array and it would make a list out of it. String[] myArray = new String[] { "foo", "bar" }; List myList = Arrays.asList(myArray); In Java 1.5 this was retrofitted for varargs; you could simply pass elements to the function List&#60;String&#62; myList = [...]]]></description>
			<content:encoded><![CDATA[<p>In Java 1.4 there was the function Arrays.asList. You could pass it an array and it would make a list out of it.</p>
<pre>String[] myArray = new String[] { "foo", "bar" };
List myList = Arrays.asList(myArray);
</pre>
<p>In Java 1.5 this was retrofitted for varargs; you could simply pass elements to the function</p>
<pre>List&lt;String&gt; myList = Arrays.asList("foo", "bar");
</pre>
<p>I never really understood how that worked in a backwards-compatible way; I mean either the function takes an array of stuff, or it takes individual elements, surely?</p>
<p>It turns out, that with the varargs syntax, the caller is not forced to pass individual elements, the caller can instead pass an array of elements.</p>
<pre>List&lt;String&gt; myList = Arrays.asList("foo", "bar");
List&lt;String&gt; myList = Arrays.asList(new String[] { "foo", "bar" });
</pre>
<p>The above two calls are identical, both return a List&lt;String&gt;.</p>
<p>But surely this is really dangerous? I mean Arrays.asList does not make any assumptions about what types of arguments it accepts; the list can be composed of any object.</p>
<p>How can it be certain that you want to have an List of Strings, and not a List containing a single element which is a String array? (An array is an object.)</p>
<p>To demonstrate this inconsistency:</p>
<pre>String[] arr = new String[] { "foo", "bar" };
Arrays.asList(arr);            // returns List&lt;String&gt;
Arrays.asList(arr, arr);       // returns List&lt;String[]&gt;
Arrays.asList(arr, arr, arr);  // returns List&lt;String[]&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.databasesandlife.com/java-varargs-inconsistent-behaviour-if-you-pass-an-array/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

