Sunday, November 28, 2010

dup and clone: What's the difference?

dup and clone are used in ruby to create duplicate/clone of an object. So what's the difference between them? They differ in how they operate on frozen object. When frozen object is cloned using clone, the cloned object remains frozen, while when frozen object is duplicated using dup, the duplicated object is not frozen.

Saturday, November 27, 2010

Ruby: freezing your object

Before diving in, lets look into what are mutable and immutable objects.

Mutable object is object that can be modified anytime during its life time. Immutable object is object that cannot be modified after it is created.

In ruby object can be made immutable anytime using freeze method. Once the object is frozen, it cannot be modified further in its life time. Any attempt to modify frozen object results in TypeError. Let's take a look at simple example of freezing a string object.


Once str is frozen there is no way it can be unfrozen.

Ruby also provides frozen? method to check whether object is frozen or not.


One important point to take a note about freeze method here is that freeze makes object immutable and not object reference variable. Take a look at below code.


obj1 and obj3 points to one instance of FreezeTest and obj2 points to another instance of FreezeTest. Once obj1.freeze is invoked, instance of FreezeTest to which obj1 and obj3 are pointing is frozen and not obj1 and obj3 variables. Both these variables can be modified to point to any other instance as seen in above code.


So where can freeze method be useful? Two places I can think of

  1. Creating a true constant object: By true constant, I mean constant variable that refer to immutable object. Lets take example from rails. request.rb defines LOCALHOST constant as

    LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze

    By freezing array to which LOCALHOST points, rails makes sure that no one should be able to modify definition of localhost by removing and adding elements to array.

  2. Using object as hash key: Once object is used as hash key, we want to make sure that it's hash is not changed otherwise it will be difficult to find value associated with it. One of the way to achieve this is by freezing object and then using it as hash key.

What All Rubyist Should Know About Threads

Tuesday, November 23, 2010

Google App Engine, things to know

Goodbye Google App Engine (GAE) provides some details one should be aware before starting using GAE as platform for new killer web app.

Sunday, November 21, 2010

Using ActiveRecord without Rails

Following ruby code shows how to use active record in non rails environment.



Contents of database.yml:

Friday, February 04, 2005

Encapsulation is not information hiding

Excellent article describing the difference between Encapsulation and Information hiding with real life example. Read it.

Saturday, January 15, 2005

ROWNUM Pseudocolumn with ORDER BY

In Oracle to limit the number of rows return we use ROWNUM in the WHERE clause. Suppose if we want first 10 rows of emp table, then the sql query will be something like

SELECT id, name FROM emp WHERE ROWNUM < = 10


And if we want sorted result then might be ( as i thought for first time)

SELECT id, name FROM emp WHERE ROWNUM < = 10 ORDER BY name

The above query does not work as we want. The WHERE clause is applied before the ORDER BY clause. Oracle picks the first 10 rows and then applies ORDER BY on them. We need to first sort the data and then select the first 10 rows. Here is the query:

SELECT id, name FROM (SELECT id, name FROM emp ORDER BY name) WHERE ROWNUM<=10


You have to do this if the column in ORDER BY clause is non-primary key. If the column is primary key then simple query will do. Look at the below sql query

SELECT id, name FROM emp WHERE ROWNUM < = 10 ORDER BY id DESC

here id is primary key.

Also one more thing i noticed that we cannot use greater than(>) operator with ROWNUM. The query returns zero rows.


Tuesday, December 28, 2004

Design Vs. Architecture

Weblog showing the difference between Design and Architecture.

http://www.artima.com/weblogs/viewpost.jsp?thread=84070

Thinking about objects

Nice weblog, discussing whether one can make sense of the objects in the langauge independent way.

http://www.artima.com/weblogs/viewpost.jsp?thread=85308

Wednesday, September 01, 2004

Overriding validate() method for Containers.

I found an interesting problem when overriding the validate() method of the JPanel. I wanted to do some operation when the size of the parent changes. But when the program was executed nothing happened. The validate() method was not called. Where was the problem???????

Actually the answer lies in the validateTree() method of Container class . The validate() method is called only for the Containers which are Window otherwise the validateTree() method is called. So the flow is something like this :

validate() method of Container calls the validateTree(), which in turn calls the validate() if Container is Window otherwise validateTree().

So if your Component is Window then override validate() method otherwise override validateTree() method.

Wednesday, July 07, 2004

Using SAX Parser from validating XML document in Java 1.4

By default the SAX parser does not validate the XML document against DTD.
To validate a XML document, call setValidating(true) on SAXParserFactory instance.

Your handler class must override error(SAXParseException e) method of the DefaultHandler to throw an exception (see the example below). If you don't do this your xml document will be parsed and client(user/other program) will not know about the exception. The SAX parser calls this method if any error occurs while parsing. It is the responsibility of the handler writer to make this exception available to the external world.

The default implementation of error method is empty(i.e. it does not perform any operation).

In xml document DOCTYPE should be included. The parser takes the DTD from the DOCTYPE.

Example:

The below given java example prints the element in the console as they are encountered. If the example is executed with validbooks.xml no exception is thrown. But if the invalidbooks.xml is used exception will be thrown for <abc> tag.

If the error method is removed from the code, both the xml documents(invalidbooks.xml and validbooks.xml)is parsered without any exception.

DTD:

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT age (#PCDATA)>
<!ELEMENT book (person+)>
<!ELEMENT first (#PCDATA)>
<!ELEMENT last (#PCDATA)>
<!ELEMENT person (first,last,age)>





validbooks.xml

<?xml version="1.0"?>

<!DOCTYPE book SYSTEM "books.dtd">
<book>
<person>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
</person>
<person>
<first>Bill</first>
<last>Gates</last>
<age>46</age>
</person>
<person>
<first>Steve</first>
<last>Jobs</last>
<age>40</age>
</person>
</book>




invalidbooks.xml

<?xml version="1.0"?>
<!DOCTYPE book SYSTEM "books.dtd">
<book>
<person>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
</person>
<person>
<first>Bill</first>
<last>Gates</last>
<age>46</age>
</person>
<person>
<abc></abc>
</person>
<person>
<first>Steve</first>
<last>Jobs</last>
<age>40</age>
</person>
</book>




Java Program:

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXTest extends DefaultHandler
{
public void startElement(String namespaceURI, String sName, String qName, Attributes attrs)
{
System.out.println("<" + qName + ">");
}

public void endElement(String namespaceURI, String sName, String qName)
{
System.out.println("");
}

public void error(SAXParseException e)throws SAXParseException
{
throw e;
}

public static void main(String[] args)
{
DefaultHandler handler = new SAXTest();

SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
try
{
SAXParser parser = factory.newSAXParser();
System.out.println(parser.isValidating());
parser.parse("books.xml", handler);
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Monday, July 05, 2004

Headless in Java

Headless support is for application that want to process images but run on server which does not has display. Click
herefor more information.

Note: Java 1.4 onwards support headless and does not require X server.