Feeds:
Posts
Comments

After some hesitation I’ve bought my first DSLR – Canon 450D.
After a few days of playing I’m quite happy with it. Now I only miss 50mm f/1.8 lens, so in near future I’m planning to buy it. Kit lens is ok for everyday shooting, but I want a faster lens for portraits.

Meet my 5 months old baby girl Lėja:

Leja

Canon EF-S 18-55mm f/3.5-5.6 IS (Shutter: 1/25, aperture: 4.0, ISO: 400)

Recently I was working on a small console application with a few threads that concurrently updated the database. I had to make things transactional and separated so each thread had to have it’s own connection.
ThreadLocal to the rescue:

package electro.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Thread local database connection.
 * Main thread is expected to call init with database connection parameters.
 *
 * @author Viktoras Agejevas
 *
 */
public class ThreadConnection {

	private static ThreadLocal<Connection> connection = new ThreadLocal<Connection>();

	private static String user;

	private static String pass;

	private static String url; 

	private static String driver;

	private static boolean initialized = false;

	/**
	 * Initializes ThreadConnection with connection data.
	 *
	 * @param user database username
	 * @param pass database password
	 * @param url database connection jdbc url
	 * @param driver database driver name
	 */
	public static  void init(String driver, String url, String user, String pass) {
		ThreadConnection.user = user;
		ThreadConnection.pass = pass;
		ThreadConnection.url = url;
		ThreadConnection.driver = driver;
		ThreadConnection.initialized = true;
	}

	/**
	 * Gets connection associated with current thread.
	 *
	 * If currently associated connection is closed, recreates a new connection.
	 *
	 * @return database connection bound to this thread
	 * @throws SQLException if database access error occurs
	 *         or db driver is missing
	 */
	public static Connection getConnection() throws SQLException {
		if (!initialized) {
			throw new IllegalStateException(
					"ThreadConnection is not initialized");
		}

		if (connection.get() == null || connection.get().isClosed()) {
			try {
				Class.forName(driver);
			} catch (ClassNotFoundException e) {
				throw new SQLException(
						"Can't find db driver: " + e.getMessage(), e);
			}

			connection.set(DriverManager.getConnection(url, user, pass));
		}

		return connection.get();
	}
}

At the application entry I just init the database connection parameters and after that every thread can access it’s connection:

package electro.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

public class Runner {

	public static void main(String[] args) throws SQLException {
        ThreadConnection.init("org.hsqldb.jdbcDriver", "jdbc:hsqldb:test", "sa", "");

        Connection connection = ThreadConnection.getConnection();
        // main thread's connection

        new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Connection connection = ThreadConnection.getConnection();
					// this thread's connection
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
        }).start();
	}
}

At my current job we have some annual developer test which consists of some general computing/programming/architecture questions. Personally I haven’t done the test, but I have reviewed a corrected test (the test was on paper) of my colleague. One question caught my attention:

Define encapsulation.
a) Hiding internal details of an object.
b) Aggregating child objects inside a parent object.
c) Wrapping data and functions that operate on that data inside an object.

The answer c) was shown to be correct and the answer a) (which my college answered) was marked as incorrect.
I honestly think that a) is correct and c) is almost correct – if we change ‘Wrapping’ to ‘Hiding’ in it it would be really correct.

After all this I had a discussion with the test creator and he thinks that encapsulation and information hiding are completely separate things. According to him, encapsulation is just wrapping of data (no hiding of anything) and that every Java object is inherently (by design) encapsulated and that hiding internal details/data has nothing to do with encapsulation.

I think that this point of view is quite narrow and misses the general point of encapsulation. I think that encapsulation and information hiding are almost synonymous – supplementary and tandemic.

I will not even try to explain my point, people much more authoritative than me have already done that:

Design Patterns – Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Glossary:
“Encapsulation – The result of hiding a representation and implementation in an object. The representation is not visible and cannot be accessed directly from outside the object. Operations are the only way to access and modify an object’s representation.”

Design Patterns – Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, p. 19 (this quote shows that object is not encapsulated by definition):
“Because inheritance exposes a subclass to details of its parent’s implementation, it’s often said that ‘inheritance breaks encapsulation’.”

Object-Oriented Analysis and Design with Applications by Grady Booch, Ivar Jacobson, and James Rumbaugh, p. 51:
“Encapsulation is most often achieved through information hiding (not just data hiding), which is the process of hiding all the secrets of an object that do not contribute to its essential characteristics; typically, the structure of an object is hidden, as well as the implementation of its methods. “No part of a complex system should depend on the internal details of any other part” [50]. Whereas abstraction “helps people to think about what they are doing,” encapsulation “allows program changes to be reliably made with limited effort” [51].”

Effective Java™ Second Edition by Joshua Bloch, p. 67:
“The single most important factor that distinguishes a well-designed module from a poorly designed one is the degree to which the module hides its internal data and other implementation details from other modules. A well-designed module hides all of its implementation details, cleanly separating its API from its implementation. Modules then communicate only through their APIs and are oblivious to each others’ inner workings. This concept, known as information hiding or encapsulation, is one of the fundamental tenets of software design.”

Code Complete Second Edition, Steve McConnell, p. 567 (this book has a lot of information about encapsulation, this quote is chosen because it uses both notions synonymously):
“Encapsulation (information hiding) is probably the strongest tool you have to make your program intellectually manageable and to minimize ripple effects of code changes. Anytime you see one class that knows more about another class than it should–including derived classes knowing too much about their parents–err on the side of stronger encapsulation rather than weaker.”

Wikipedia, http://en.wikipedia.org:/wiki/Encapsulation_(computer_science)
“In computer science, encapsulation is the hiding of the internal mechanisms and data structures of a software component behind a defined interface, in such a way that users of the component (other pieces of software) only need to know what the component does, and cannot make themselves dependent on the details of how it does it.”

These quotes clearly show that encapsulation and information hiding are almost synonymous.

So is any Java object is inherently encapsulated? Is Point object, that has public x and y properties encapsulated? I think the answer should be clear…

time

I was always fond of precise time. One day I wondered how NTP works and in the way decided to create SNTP Java client (RFC-2030).

For now client has only basic features and works only in unicast mode. Currently SNTPJC doesn’t update system time, if such feature might be needed by someone, it might be implemented using JNI.

This programming session was ignited by academic curiosity so I don’t think I will actively develop it any further. But the source code might be useful for somebody so here’s the SNTPJC google code project.

If you are interested in testing it – go and download latest sntpjc-<version>.jar and execute it with some NTP server address:

java -jar sntpjc-<version>.jar ntp.data.lt

Output:

Checking with: ntp.data.lt (92.61.32.9)
System time offset is: -0.004765 s

Great post that explains why I bothered programming it.

Older Posts »