Saturday, September 29, 2007

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() {}
}
Java2html

I will end this post with the first paragraph from Item 17, of Joshua Bloch's excellent book, Effective Java. In the book this paragraph is followed by a code example that explains this very well, however, I am not sure if I can include the example under fair use. Crying..

Inheritance is a powerful way to achieve code reuse, but it is not always the best tool for
the job. Used inappropriately, it leads to fragile software. It is safe to use inheritance within
a package, where the subclass and the superclass implementation are under the control of the
same programmers. It is also safe to use inheritance when extending classes specifically
designed and documented for extension (Item 15). Inheriting from ordinary concrete classes
across package boundaries, however, is dangerous. As a reminder, this book uses the word
“inheritance” to mean implementation inheritance (when one class extends another).
The problems discussed in this item do not apply to interface inheritance (when a class
implements an interface or where one interface extends another).

Can you think of a situation where subclassing an existing class can break the semantics of your code, because of a certain undocumented feature of the superclass? Let me give you a hint. Assume a collection class has 2 methods

add(Object o) - to add the specified object to the collection

addAll(Collection c) - to add each element of the specified Collection to this collection.

Now assume that addAll(Collection c) internally invokes add(Object o) for every object in the collection.

Can you think of a situation that will result in a bug, if we subclass this class and override the above methods to add a functionality that keeps track of how many elements have been added to the collection?

Resources:

  1. Compostion vs. Inheritance
  2. Composition and interfaces

Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

-----
COMMENT:
AUTHOR: Josh Bloch
EMAIL:
IP: 71.202.105.255
URL:
DATE: 09/29/2007 10:22:58 PM
Yes, you can include the example under fair use:)

Josh
-----
COMMENT:
AUTHOR: Parag
DATE: 10/02/2007 09:17:55 AM
Thanks a lot Josh. I will include the example in the next post.

--
Regards
Parag

Friday, September 21, 2007

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:


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
myList = new ArrayList();

doSomethingWithList(list);

}

private void doSomethingWithList(List list) {

}

Java2html
  • Loose coupling contains the scope of change when an implementation is modified



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Saturday, September 15, 2007

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 delete() {
//delete account
dispatchEmail(...);
}

public dispatchEmail() {
//generate email... create connection
//create message
//dispatch email
}
}
Java2html

Resources:

  1. http://www.artima.com/intv/dry.html
  2. Don't repeat yourself
  3. Once and only once
  4. Code harvesting




Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Wednesday, September 12, 2007

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



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Sunday, September 09, 2007

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]




Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Wednesday, September 05, 2007

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 determined never to attend his class again, I went straight to the book-shop, opposite to my college, and grabbed a copy of “Java 2 the Complete Reference” by Herbert Schildt.

I spent the rest of the semester studying the entire book cover-to-cover not to mention, spending nights at stretch working hard to get my hands-on right and accurate. I used to do a lot of stupid things with Java, by creating dumb applications, but all that gave me good experience and insight into the Java language, its working and above all made me confident that I can develop applications using Java.

After this, we got a really nice faculty for advanced Java and that faculty provided me the much needed guidance that I missed during the days I started programming in Java.

Q. What parts did you have a hard time understanding and how you overcame the difficulties?

A. Collection classes took some time and effort to be understood… I kept on using different collection classes in my dumb applications thereby figuring out each one’s unique working. It’s only through trial and error that one can get the basics straight. For advanced understanding, referring to books and the internet is the best way to progress.

Also, using advanced frameworks presented its unique challenges to me and till date I am facing some or the other difficulties using some or the other new feature of Java. Today, I rely on the WWW for guidance. I refer to a lot of material that’s available online whenever I hit a road-block. If all fails, I post to the group to get answers from someone who has been there and done that. It helps, the community based learning!

Till date, multi-threading is something that sends shivers down my spine! I know the basics and have done quite a good work on it but still I am never sure that my multi-threaded application will give me the desired result or not!

Q. What are the most common mistakes that students often make?

A. The biggest mistake that I have seen amongst my peers, is that they just read a really good book on Java (or any language for that matter) but never voluntarily venture out to get their hands-on correct. Bookish knowledge gets them the much needed marks/grades but makes them dumb programmers. They know about all the various “fancy” features the language has to offer without knowing even how to get the very “basics” working!

People who do venture out to get their hands-on correct, get easily dis-heartened when they hit a road-block. One must remember that failures are stepping stones to success and that as long as you don’t fall, you will never know how higher you can go. The internet is rich with resources and everything is served on a platter these days by Google.

Q. Anything else that you think may help the students?

A. Always remember that you need a good guide (a teacher) who can help you get your basics straight but if you don’t get one, don’t worry. Be your own guide and venture out into the world of Java on your own. It isn’t that scary. It’s very important to remember that you will learn Java if-and-only-if you venture out into Java world on your own. Hitting road-blocks is a boon, it only helps you in knowing a lot more, and things that you never knew exist are uncovered only when you hit a road-block.

Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net
Here are the comments from the original post

-----
COMMENT:
AUTHOR: Tarun Chandel
URL: www.tarunchandel.blogspot.com
DATE: 09/05/2007 01:08:33 PM
Sanket has given some really good points and his experience on learning Java can be applied to most of the things in life, whether it's technology or any other thing. The one point I really like is that never let a bad teacher affect your enthusiasm for learning.

I think very few lucky people get really good teachers. I am one of those lucky few to have you as a teacher. On the teacher's day I would like to thank you for making a difference in my and many other's life just by being there in front of the class.

Wishing you a very happy Teacher's Day!
-----
COMMENT:
AUTHOR: Parag
DATE: 09/06/2007 09:04:19 AM
Hi Tarun,

Thank you for the kind words and good wishes.

Good luck for everything :-)

--
Regards
Parag

Monday, September 03, 2007

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.

 

JavaSourceEncoding.JPG 



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net