Skip to main content

Posts

Showing posts from 2007

Do you like static imports?

Static imports have been around since Java 1.5, but they are a feature that I have rarely used, or even seen much in code. I guess that's because static imports is not a must have thing, but something that is nice to have . Using static imports takes some pain away from typing code. For example, instead of writing System.out.println("some message"); we could statically import System.out and write it as follows: static import  System.out; public class  HelloWorld  {    public static  void  main ( String args []) {      out.println ( "Hello World" ) ;    } } Well using static imports definetely takes the pain away from typing System.out every time. However sometimes using static imports can also reduce the readability of code, because we would have to look at the imports to know if a variable in code was declared within that class itself or imported statically. Having said that, one place where I would definetely use static imports is in imp

Spot the mistake

Can you spot the mistake in this code? // BROKEN - throws NoSuchElementException! for (Iterator i = suits.iterator(); i.hasNext(); ) for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(i.next(), j.next())); If not, check this article on the Java for...each loop. Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

The risk of invoking public methods in Java

In the past few posts we have discussed how it can be dangerous to extend a class that we do not control, if it has not been designed for subclassing. We understood this concept with a specific example from Josh Bloch's book: Effective Java. In the example we subclassed the HashSet class in the JDK. Without repeating the material, I will simply reiterate what I said in my previous post: The real problem was the class AbstractCollection which was not designed properly for inheritance. It is a non-final class with a public method addAll(Collection c) which invokes another non-final public method add(Object o) . Here is a possible implementation of the HashSet class that does not break the DRY principle and is also safe for extending...

Never invoke a public method from another public method

In the previous post we saw how subclassing from a class not designed for inheritance, can be dangerous. Using composition instead of inheritance would have solved the problem. But what was the crux of the problem? Could such a trap have been avoided? Could AbstractCollection have been implemented so that such a situation would not have arisen in the first place? The real problem was the class AbstractCollection which was not designed properly for inheritance. It is a non-final class with a public method addAll(Collection c) which invokes another non-final public method add(Object o) . How should AbstractCollection have implemented add(Object o) and addAll(Collection c) to prevent such a problem? I do not know if this problem has been fixed in OpenJDK. They may have not been able to do so to maintain backwards compatibility. You can check out the sources from their website . In the next post we will discuss an idiom for preventing such a situation.  Discuss this post in the lea

A Java example showing the dangers of implementation inheritance

I ended my previous post with a paragraph from Josh Bloch's book, Effective Java . In his book, Josh explains why inheriting classes from a different package (especially inheriting from a class that may not be designed and documented for inheritance) can be dangerous. Below you will find Josh's example (from Effective Java ) that explains the concept. Many many thanks to Josh Bloch for graciously giving me permission to reproduce the example here :-) The class InstrumentedHashSet is a subclass of HashSet, that maintains a count of the number of objects added. It overrides the add(Object o) and addAll(Collection c) methods from HashSet to maintain a count of objects added to it. These methods increment the count and then delegate responsibility for adding the element to HashSet. The number of objects added can be obtained from the method getAddCount() . This seems like a reasonable way to count objects added to the Set. Unfortunately it's not. But first let's have a l

Inheritance and composition

Inheritance is used for Code resuse To support polymorphism Disadvantages of inheritance Difficult to change the interaface of the subclass Superclass is always instantiated Can get complex and unmanageable Composition is used for code reuse Disadvantages of composition We cannot use polymorphism We cannot extend the system by adding subclasses May have a slight performance overhead Usage Inheritance: IS- A Composition: HAS - A Example 1 : public class Car {    private Engine engine;    public void start () {}    public void stop () {} } public class SUV extends Car {    public void start () {} //overrides the start method from Car    public void fourByFourMode () {} } Example 2 : public void someMethod () {    Car c = new SUV () ;    c.start () ; } Example 3 : public class Car {    private Engine engine;    public void start () {      engine.start () ;      //maybe do something more    }    public void stop () {} }

High cohesion

[Time: 4 mins] Stuff that goes together, stays together Easy to discover relevant code Levels of cohesion packages classes methods So in very simple words, cohesion is keeping related stuff together so we can find what we want without too much difficulty. Example 1 : public class Student { //cohesive methods public void registerForCourse () {} public void deregisterFromCourse () {} viewTranscripts () {} //methods below are not in synch with the responsibilities of the Student class //hence cohesion is broken submit grades () {} submitCourseSchedule () {} } Java2html Resources: High cohesion on Wikipedia Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Loose coupling

[Time: 4:32 mins] Loose (or low) coupling means (in a generic sense) that an entity can interact with another entity without being concerned with the internal implementation, and through a stable interface. Low coupling is implemented by using principles of information hiding. When two entities are loosely coupled, internal changes in one of them do not affect the other. The calling method is coupled to the called method and not it's implementation. Since we have already discussed encapsulation and information hiding in detail, I will not repeat it here. Loose coupling is achieved with information hiding And by programming to the interface rather than the implementation Example 1 : Tightly coupled system public void aMethod () { ArrayList myList = new ArrayList () ; doSomethingWithList ( list ) ; } private void doSomethingWithList ( ArrayList list ) { } Example 2 : Loosely coupled system public void aMethod () { List myL ist

Don't repeat yourself

The code says everything once and only once, which is the essence of good design. -- Martin Fowler [Time: 4:44 mins] Repititive code makes maintainance more difficult There are more places to change We may forget to change some of them Increases probability of bugs Types of repitition In methods in a class Accross the entire software Example 1: DRY violated public class Account { public void transferFunds ( double amt, Account dest ) { //transfer funds //generate email... create connection //create message //dispatch email } public void delete () { //delete account //generate email... create connection //create message //dispatch email } } Java2html Example 2: DRY honoured public class Account { public void transferFunds ( double amt, Account dest ) { //transfer funds dispatchEmail ( ... ) ; } public void delet

Keep it simple

[Time: 5:37 mins] One should not increase, beyond what is necassary, the number of entities required to explain anything - Occams Razor KISS helps keep software manageable The UNIX kernel is an example of a functionally complex software implemented in simple design Intentional complexity Enthusiasm to use design patterns Enthusiasm to make a system uber flexible Feature bloat Unintentional complexity Maintainance quick fixes Laziness in refactoring Resources: PrematureGeneralization Discuss this post in the learning forum . Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Software design principles

Over the next few posts, I will cover some basic software design principles. There are some well known software design principles that serve as guideposts for us in the design process. But here is something to always keep in mind while using design principles to guide us in our design. While principles, patterns, heuristics, and guidelines offer valuable advice about how to do things the right way, they don't serve as substitution for thinking on our own. Unfortunately, I think we all too often let these principles, etc. do the thinking for us. -- Kirk Knoernschild The audiio snippet below is a very simple and brief introduction to software design. Please click on the start arrow to begin the audio. Stay tuned for more on software design in the next few posts posts... [Time: 2:20 mins] Discuss this post in the learning forum . Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

A student's perspective on Java

From some time I have been very keen to publish a post that describes a student's perspective on Java. Over the years Java has gone from a simple easy to learn language to quite a huge beast. The volume of things one has to learn and keep up in Java poses a special challenge to students who wih to learn the language. I would like to post experiences of how various students coped with the challenge of learning Java. In this post, Sanket Daru, a student in one of my Java classes at SCIT describes his experience with Java. I am particularly glad to post Sanket's thoughts, since he is one of the brightest and most enthusiastic students, that I have had the pleasure of teaching. Q. How did you go about learning Java? A. It all began in 2003 during my graduation. We had Java in our curriculum. I attended the Java faculty’s first and second lecture and knew that “maybe he is a genius, but he knows nothing about the heads or tails of teaching.” Convinced and determine

Compiling Java source files with supplementary characters

Java source files can also contain supplementary characters as strings as well as identifiers if the character is a string or a digit. Here is a video that shows how we can compile Java source files that contain supplementary characters as Strings. Click on the image to download the video.     Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Changes in Java to support supplementary Unicode characters

Support for supplementary characters might need changes in the Java language as well as the API. A few questions come to mind. How do we support supplementary characters at the primitive level (char is only 16 bits)? How do we support supplementary characters in low level API's (such as the static methods of the Character class) ? How do we support supplementary characters in high level API's that deal with character sequences? How do we support supplementary characters in Java literals? How do we support supplementary characters in Java source files? The expert commitee that worked on JSR-204 dealt with all these questions and many more (I'm sure) . After deliberating as well as experimenting with how the changes would affect code, they came up with the following solution. The primitive char was left unchanged. It is still 16 bits and no other type has been added to the Java language to support the supplementary range of unicode characters.  Low level API's, such as

It's been a while since I posted

It's been a week since I posted last. I am really sorry, this is the second time in succession that I have missed my target of posting at least thrice a week. By way of an excuse, all I have is a lame "it's been a bit crazy at work" . I am messing around with a lot of client side technologies, like AJAX and the plethora of libraries that accompany it, and all this without really understanding Javascript well enough. One of the libraries I am checking out is DWR (Direct Web Remoting) . It allows Javascript code to invoke Java objects. All this is done by creating proxy objects in Javascript that make AJAX calls to the DWR Servlet, which in turn invokes the Java objects. I personally think, it's a very nice concept, and it also supports reverse AJAX. Would you like to know more about DWR? Please comment and let me know. I will then post a series on DWR after completing the current one on Unicode characters.   On a total tangent, here's a little something from

Supplemantary character support in Java

In the last post I wrote that supplementary characters in the Unicode standard are in the range above U+FFFF, which means they need more than 16 bits to represent them. Since the char primitive type in Java is a 16 bit character, we will have to use 2 char's for them. I just finished reading some stuff on supplementary character support in Java, and well, there are parts I understood right away and parts that are going to need further reading. I will try to share what I am learning on this blog. However, let us first clarify some terminology. Character: Is an abstract minimal unit of text. It doesn't have a fixed shape (that would be a glyph ), and it doesn't have a value. "A" is a character, and so is "€", the symbol for the common currency of Germany, France, and numerous other European countries. Character Set: Is a collection of characters. Unicode is a coded character set that assigns a unique number to every character defined in the Unicode

Catching up with Java 5

Java 5 (a.k.a Tiger) has been around from a while. But there are still many developer's (including myself) who do not know about and use all it's features. So, in an effort to educate myself and help others, I have decided to spend some time everyday reading Java 1.5 Tiger A Developer's Notebook , and share my findings with others on this blog. Something I found out today (I know this should have happened long back, but such is the profession of programming :-) ), is that since Java 1.5 there is support for Unicode 4 which supports a supplemantary character set, that goes beyond 16 bits. An interesting implication is that a the char data type may no longer be able to hold all characters, because those in the supplementary range can now take upto 21 bits. This means that a string that contains certain characters may have to encode them as 2 char data types. Such a pair of characters that represents one codepoint is known as a surrogate pair. Now a string with n codepoints m

Java reference types - an example and questions

Dr. Heinz Kabutz has an excellent example for Soft, Weak, and Phantom references in one of his newsletters. You can view it here . I also created mind maps for the Java garbage collector and Java reference types. You can download the images by clicking on the links below: Java garbage collector Reference types in Java    Before concluding the series on Reference types in Java, here are some simple questions for you to test your knowledge. Q1. Consider the following code: String s = new String("abc"); SoftReference sf = new SoftReference(s);  What is the reference type (strong or soft) for "abc" ? Q2. What is the main difference between phantom  references and the other (soft and weak) two references? Q3. Consider the following code: SoftReference sf = new SoftReference("abc");  WeakReference wr = new WeakReference("123");  Which of the two strings will be garbage collected first, when the JVM needs memory?   Note: This text was originall

Reference queue

The garbage collector puts Reference objects in the ReferenceQueue after their referents have been reclaimed (Phantom references are an exception, because they continue to retain a link to their referents even after they are placed on teh ReferenceQueue). In most cases when Soft and Weak references are used, we do not care to monitor the ReferenceQueue. However, in case of PhantomReferences, we do want to monitor the ReferenceQueue, because they are used when we wish to do some cleanup activities when the reference is reclaimed. In such cases, a thread which monitors the ReferenceQueue to find out which objects have been reclaimed will be effective. The WeakHashMap class in the JDK however, follows a slightly different strategy as explained here . While Soft and Weak references can be created without being associated with a ReferenceQueue, Phantom references must always be associated with a ReferenceQueue. The java.lang.ref.ReferenceQueue class gives us three methods to interact

Phantom references

Phantom references are the weakest of the three reference types. There is however a significant difference between Phantom references and the other reference types. Objects that are referenced by phantom references are put on the reference queue before the memory occupied by their referents is reclaimed, while soft and weak references are enqueued after the memory occupied by their referent is reclaimed. Another important difference in the words of Ethan Nicholas is; "A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead. How is that different from WeakReference, though?" So what good are Phantom References? Well according to the documentation : Phantom refer

Weak references

A weak reference is similar to a soft reference, except that objects that are weakly reachable will be garbage collected before objects that are softly reachable. When the JVM needs memory, it will first reclaim all unused objects, if the reclaimed memory is still not sufficient, then all weakly referenced objects will will be garbage collected, and if it needs even more memory, then it will reclaim memory from softly referenced objects.   WeakReference wr = new WeakReference(new String(“abc”));       ReferenceQueue rq = new ReferenceQueue(); WeakReference wr = new WeakReference(new PhantomReference(new String(“abc”), queue));       String s = new String(“abc”); ReferenceQueue queue = new ReferenceQueue(); WeakReference wr = new WeakReference(s); PhantomReference pr = new PhantomReference(s, queue); s = null;     All of the above are examples of weak references. In the above example we see two new concepts; phantom reference, and refere

Soft references

If an object is not referenced by by a strong reference and there is at least one link to that object with a soft reference, then the object is a softly referenced object. Java provides us a class, which is a subclass of java.lang.ref.Reference, called SoftReference. Soft references are created by encapsulating the object which we want to refer, inside a SoftReference object. Some examples of soft references are shown below. SoftReference sf = new SoftReference(new String(“abc”));   SoftReference sf = new SoftReference(new WeakReference(new String(“abc”))); String s = new String(“abc”); SoftReference sf = new SoftReference(s); WeakReference wr = new WeakReference(s); s = null; In these examples we see another type of reference called a weak reference. The next section talks about weak references. Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

New series - reference types in Java

Starting this week, I will post a series of blogs on "Reference Types In Java". So here goes... Since version 1.2, Java supports references other than the commonly used strong reference . An object is said to be strongly referenced, when at least one path to the object from the root set of references contains a strong reference. A strong reference is the traditional type of reference which is created by the = operator. The garbage collector considers a strongly referenced object to be in use and will not reclaim it. This statement creates a strong reference. String s = new String("abc");  The String object holding the value “abc” is strongly referenced because the variable 's' directly refers to it. Java 1.2 supports three more types of references; SoftReference, WeakReference, and PhantomReference. Whenever we want an object to be softly, weakly, or phantomly referenced, we do not directly reference the object using an '=' operator. We instead

A process for teaching a peer taught online course

Sometime back I wrote a blog on the motivation for conducting online, peer taught courses, and the kind of infrastructure such a course would need. Once we have the basic infrastructure in place, it may be useful to define a simple process or a set of guidelines for students as well as mentors to help them as they proceed with the course. It is very important to explain the learning methodology and it's benefits to the students and mentors. The students must understand right at the beginning that learning that is spoon fed is the most ineffective way of learning. The core process that they are to follow is learning by doing, and participating with other students, mentors, and practitioners. Traditional lectures would also be needed, but their purpose should be to introduce students to the topics and show them how to build on the knowledge by practicing and participating. The mentors should interact with the students through lectures, online groups, and blogs. The participation

A process for teaching a peer taught, online course - contd

Once all the grading and other process details are explained to the students, the faculty starts by explaining the first topic in a kickstart fashion and giving a set of resources to the students for further understanding. So, for example, if the topic is “Input/Output in Java”, the faculty will explain the basic architecture of the IO library, they will demonstrate a simple program that reads input from a console and writes to the console. The lecture ends with an introduction of the full capabilities of the library and a list of resources which the students must study to further their understanding. If possible a topic may also be linked to a project milestone. The students will then proceed with their learning by reading the link or maybe viewing screencasts, or listening to podcasts. They should write their learning and perspectives on their blog, and ask doubts on he newsgroup. The mentors will follow the students blogs and help them with their understanding by commenting on the b