Archive for the ‘programming’ tag
Writing HTML
Programmers are often required to write HTML code. Recently, on reviewing such code, I found some glaring mistakes. Based on this experience, I have assembled some points which programmers should note when developing HTML.
Version of HTML
Before writing HTML, decide upon version compliance. HTML 4.01 and XHTML 1.0 are popular choices.
Specify Version of HTML as DOCTYPE
For HTML 4.01 it is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
For XHTML 1.0:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
For a detailed list, visit: http://webdesign.about.com/od/xhtml/a/aa011507.htm
Don’t use deprecated elements like <font>
<font> has been deprecated since version 4.01 of HTML.
Use CSS for styling
For styling purposes (specifying font, color, background-color, border, etc.) use only CSS. For example, for setting the background of a page, the earlier method is:
<body bgcolor="blue">
This is better written as:
<body style="background: blue;">
Open/Close Elements
Please ensure you open and close the HTML elements in proper order. Always have the discipline of closing open elements.
Indentation
HTML is also source code which is maintained by humans. Please respect yourself and the people who will be maintaining it later: write readable HTML with proper indentation.
Validate HTML
Use a proper validation service before publishing your HTML. You may also use tools like xmllint also to validate your HTML.
Test in target browser
All our development systems are Linux. We developers test our HTMLs in Firefox. But our clients use IE. Situations like these demand additional testing effort in IE.
Freedom from fear: The path towards failure, learning and innovation
I have seen this scenario many times: programmers fearing existing code, writing extra code just to accommodate new features without changing existing code. A similar attitude I see is, is manifest in projects dealing with big databases. People working in these projects don’t dare to question the design of the Database, and subject themselves to finishing the tasks at hand to fit around the existing DB design. This is fear. Fear of:
- Uncertainty. They know existing code works. Refactoring existing might break some functionality.
- Time. The time to refactor code cannot be correctly estimated.
- Work. Of course, this is additional work.
There may be other reasons (for example, greed. The programmer might want to gain a short-term acknowledgment of his speed of delivery). But the common occurrence is Fear. And we will try to understand the implication of this fear:
- Old code gets older.
- Additional code to manage deficiencies in old code need to be created.
- The application becomes monolithic and difficult to change.
- This creates additional fear of change.
The cost involved in maintaining such code is stupendous. And how do we avoid this cost? It is, from my experience, by following some good-old practices and tools:
- Unit tests: The importance of these cannot be exaggerated. When you have a Unit test suite covering your code, it is with more confidence you can refactor it, and more confidence with which change it.
- Each developer gets his own play area: Sharing resources during development is also costly. This is the reason I encourage each developer to have his own database setup and development environment (whenever possible). This isolates the developer, and his fear of breaking the shared environment is nullified (which affects other team member’s productivity). He is more free to innovate and bring in new thoughts.
- Developer’s own coding and commit space: I also encourage people to use distributed source control systems in place of things like svn. This allows the individual to have a independent commit space, where he can commit his work as and when he completes a unit of it, without worry of breaking someone’s build. Again, a source of greater freedom.
I have seen the most unlikely people innovate by following these simple practices. So what is your take on this?
The next baby step in Haskell
One important parameter in learning a new language is the language’s approachability. I remember the difficulty I faced when learning Java. I was asked to know things like package, static function, etc. I was kept in the blank about these features till I reached the these trails in my learning. This is disappointing, and can intimidate learners from learning such language.
Haskell, just like Python (and other languages like Ruby, Perl, Groovy, etc.) provides a simple interactive shell called ghci. This allows one to immediately jump into Haskell, experimenting with its syntax without further ado.
New Year Resolution: Language to learn
We are in the mid-January of 2009, and I have taken the decision to learn one of these languages this year:
In the recent past I have been hearing some great stuff about these languages. Haskell and Erlang I have been attracted due to their powerful concurrency support. After reading Paul Graham‘s preface in On Lisp, I became attracted to Lisp (and Clojure). Haskell also has a JVM implementation, Jaskell. Coming from a Java background, I think this should be easy for me. Time will tell which one of these I will pick and learn!
Learning to Program
My personal favorite language, of course is Java. But Java is difficult to learn. Consider the Hello World program in Java:
public class MyClass{
public static void main(String[] arg){
System.out.println("Hello World");
}
}
Now consider the same program in other languages (Python, Perl, Ruby, Groovy):
print "Hello World"
When learning Java as the first programming language, the learner is forced to understand, difficult to understand concepts like package, command line parameter, visibility, arrays, etc. in the very first program itself. This is not beginner friendly.
Eric S. Raymond recommended Python for beginners. But now a days it could be any of the new scripting languages: Ruby, Groovy, Scala, or of course Python itself. Each of these dynamic scripting languages have very minimal infrastructure code. So when writing a program to do something, the code exactly means that. Very beginner friendly.
Java
After being exposed to so many languages, I still love Java. Of course, I spend lot of time still writing infrastructure code instead of core business logic even now, many of these are changing in Java. For example, to read a user input from command line, long back ago we had to write:
Before Java 5
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
br.close();
}
catch(IOException ex){
// ...
}
Java 5:
Scanner in = new Scanner(System.in); String s = in.nextLine(); in.close();
Now, in Java 6 this has been replaced with:
String s = System.console().readLine(); // No IOException thrown
Things are getting more developer friendly day by day.
Java Swing
One of my favorite parts in Java is Swing programming. All over the years since I first touched Java, Swing has constantly made me learn new things. And I have also been awe inspired so often at the wonderful extensible design of the Swing API itself.
Using Swing APIs itself is a covert educating process. When I started writing event processing code, I was covertly introduced to Observer design pattern. There is thousands of such instances where I learned good OOP design approaches without any formal education. Another area where in normal Java coding we do not spend much time is concurrency. When writing any non-trivial Swing applications, you will have to think about concurrency!
Swing has constantly challenged me to think and design smart applications. This is an area which must be covered for learning Java.
Enterprise Java
Enterprise Java is one thing I work day-in and day-out. But the majority of the time I spend when writing Enterprise Java code is: figuring out how. The Enterprise Java platform takes care of the critical areas like resource pooling, transaction management, concurrency etc., so at the end of the day, the programmer is relieved of writing this same code again-and-again. But this ease comes with the cost of configuring the system for it. Also, is Enterprise Java a good learning platform for programming? Well, for programming not exactly. But for many practices, it is. Practices include: packaging, build, testing among others.
Interrupting a Thread in Java
Long long ago, when I was studying in College, my professors taught me to abruptly interrupt a running Thread using Thread.stop() method. Later this method was deprecated. Then in some article I read to interrupt a running thread, you have to write your custom logic:
class MyThread extends Thread{
private boolean isCancelled = false;
public void run(){
while(isCancelled != true){
// do long running job
}
}
public void cancel(){
isCancelled = true;
}
}
This seems to be a valid code, but there is an issue. If we are doing some blocking operation, or an IO operation inside the loop, then the cancel notification does not reach until that is finished. Well, so how do we solve this issue?
Thread API
The java.lang.Thread class has the following API methods:
void interrupt(); boolean isInterrupted();
To signal a running Thread about our request for termination, we can call its interrupt() method. Unlike the old stop() method, this does not abruptly terminate the execution of the Thread. What is does:
| When Thread is in Blocking mode | When Thread is in normal execution |
|---|---|
| Thread’s interrupt status will be cleared, and InterruptedException thrown. | Thread’s interrupt status will be set. |
A Thread is in blocking mode during following states:
- Thread blocked in invocation of wait(...) methods; or
- join(...) methods; or
- sleep(...) methods.
Now my actual reason for exploring this concept was due to an issue in RESTClient. I had wanted to implement a Stop button just as in a normal browser. So my Thread was not blocked using any of the interruptable methods, but due to a socket IO. So how can I solve this?
class MyThread extends Thread{
public void run(){
while(isInterrupted() != true){
// do socket IO
}
}
}
But this has the same limitation as the first code I wrote. If the socket IO is in progress, this condition is not checked until the IO is done. So what finally is the solution? It is simple:
class MyThread extends Thread{
private Socket soc = ..;
public void run(){
// do socket IO
}
@Override
public void interrupt(){
if(soc != null){
soc.close(); // wrap in try/catch
}
super.interrupt();
}
}
When we close the Socket object, the IO will fail raising an IOException which we can gracefully handle.
Beautiful Closures
One of the irritating things when writing code in Java is when managing files or database resources. We have to write so much redundant code:
File f = new File("/etc/passwd");
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(f));
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
}
catch(IOException ex){
...
}
finally{
if(br != null){
try{
br.close();
}
catch(IOException ex){
...
}
}
}
So much redundancy is ground for human errors. Issues like these are beautifully solved using programming concept called Closures. For example, in the newly released 2.6 version of Python, the same would be written as:
with open('/etc/passwd', 'r') as f:
for line in f:
print line
In the above code, even when an exception is raised during file read, the file is gracefully closed when the control exits with block. A similar example in Groovy:
File f = new File("/etc/passwd")
f.eachLine{
line ->
println line
}
Martin Fowler has written a short introduction to Closures.