Monday, February 27, 2006

Re: JSTL - What's the point?

Chris,

But I think the JSTL was meant to be a base framework, allowing developers to extend and write their own tags. They're called "custom tags", and they can be pretty useful.

For example, I can write a tag that handles the logic for displaying a set of page number links. Then the web designer just needs to know how to place [foo:pagination style="xyz"/] on the page, and voila, the pagination comes out. Or, you could log an advertisement impression with a simple tag like "[ads:logImpression position="${pos}"/]. Then the code behind this tag can do whatever it needs to do -- in this case, log an impression to the database. The former example results in HTML output, and the latter doesn't.


The examples you give make perfect sense. Placing custom tags which encapsulate all the display logic within them is fine. The designer and the presentation layer don't see any of that logic. This is precisely the idea behind ASP.NET web controls like <asp:DataGrid> or <asp:Calendar>. I only took issue with having tags like <c:if> and <c:foreach> ingrained within the html. I didn't see them as being any improvement over scriptlets within html.

(I had to use [ and ] above instead of less-than and greater-than - blogger wouldn't let me enter less-than and greater-than!)

Yeah < and > are special characters. The browser interprets it as being an html tag and tries to parse it. To actually display it you have to use &lt; and &gt;.

There are some frameworks built on top of servlets/JSP/JSTL that provide higher-level custom tags, such as Struts and JSF, as you mentioned. Components such as "DataGrid" as nice for rapid development, but if you need to customize that component, the built-in tags may not work well. (I don't know much about DataGrid in particular, as I'm not familiar with .NET)

I dunno how custom tags like <ads:logImpression> are developed (I assume using JSTL/EL?), but in ASP.NET these web controls are basically classes. So the <asp:Calendar> control is actually implemented in System.Web.UI.WebControls.Calendar within the .NET framework. Its 'real' code - as in implemented using C#. So all the rules of OOP apply here. All web controls directly or indirectly inherit from the base System.Web.UI.Control class which provides some common functionality. And it's really easy to customize any functionality you would want. Just create your own custom controls that inherit from one of these base controls and override away. These controls also allow you to hook in callbacks for certain events which is another way to customize the controls. Check out this article which provides a nice explanation of both processes.

Could you post or link a simple ASP.NET example showing this separation of UI/model?

One of the areas where the Servlet/JSP model wins is in the clear separation between the control code and the presentation. There are two separate components. Requests (generally) hit Servlets after which they are forwarded to independent JSPs. In ASP.NET, there is only one component - the Page. Although this page is separated between into a .aspx file (UI) and a .cs/.vb file (code) using the Code Behind Model, these are compiled down to one component. So basically all requests go to a Page and then could potentially be forwarded elsewhere. It's sort of "backwards" to the MVC model. So the Servlet/JSP API model is richer in that sense. Having said this, the Code Behind model does have its advantages. Probably the biggest one being all the UI components are represented as objects which can be manipulated in the code behind page. Here is a simple explanation of the concept.

Re: JSTL - What's the point?

What is the logic behind separating presentation from code? Apart from the "MVC pattern"/"loosely coupled principle", it is also to accommodate designers and coders....The "logic" is still ingrained within the presentation. It is still code, just with tags, instead of java. How is this any better for designers or code maintenance? Somehow this made no sense to me.

What you mentioned is very right. See this post section Using the SQL Actions

<excerpt>
The JSTL includes a number of actions that provide a mechanism for interacting with databases. The previous sentence should, at a very minimum, send up a red flag in your architectural visions. One might ask, "Do I really want to be able to perform SQL actions such as queries, updates, and transactions from my JSP? Isn't that business logic that belongs in the model?" The answer is yes. Yes, yes, yes. To follow a Model-View-Controller (MVC) architecture, which is the predominant design pattern used in building web applications today, you definitely want to keep your model information in your business logic. This means that you don't want it in your JSPs. Why then are these actions even provided in the JSTL? Good question and one that I've discussed with various members of the JSR-53 expert group. The reason is the "C" or community in the Java Community Process (JCP). The community has asked for it, the community has gotten it.
</excerpt>

So thats that. Even the tags Mohnish mentioned are not that great. But... its fine.

Adding to the comment ; JSTL was a another step. Jsp did something better than Servlets. Jstl added something. Then Jstl EL was added which was purposefully given a more JavaScript like syntax. Now we have JSF which gives a more component based web dev feel. I don't know much on JSF though. Also there are actually competing web frameworks in the Java world like Struts, Tapestry... So again loads of choice :)

ASP.NET has the right solution for separation with web controls.

Could you post or link a simple ASP.NET example showing this separation of UI/model?

How is webapp dev in php? Do they too generally look out for such MVC stuff?

Friday, February 24, 2006

JSTL - What's the point?

I've been taking a look at Web related stuff in Java lately. Nothing too complex, just your basic Servlets/JSP. The general concepts behind these web frameworks (ASP[.NET], PHP, Ruby etc...) are all similar. The book I'm reading (Head First Servlets and JSP) has a nice way of explaining the components of the Java system. It starts with the simplest way to accomplish your goal, then shows what's wrong with it and finally how to improve upon it.

First you got your basic requests hitting a Servlet that does some processing and spits out HTML to the client. Nice and simple, but writing all that HTML code within the Servlet is horrible. Enter JSP. JSPs can contain the presentation (HTML). So now your requests hit a Servlet that does the processing after which it redirects to your JSP which has all the HTML code. Now there's a nice separation between code (Servlet) and presentation (JSP). But the JSP is pretty static. What if the presentation needs to be dynamic and depends on the processing done in the Servlet. Enter Scriptlets. These are code segments within JSP that can make the page dynamic. Great... you get nice dynamic pages now, but your presentation is cluttered with code. Enter JSTL (Java Server Tag Library). This is a tag library which is to replace those scriplets. So instead of code you have 'html like' tags.

This is pretty new to me, so I was trying to understand the rational behind it all. The progression made sense from Servlets to JSP to Scriptlets. But somehow the point of JSTL was completely lost on me.

What is the logic behind separating presentation from code? Apart from the "MVC pattern"/"loosely coupled principle", it is also to accommodate designers and coders. Designers can work on the presentation and not have to deal with code. But when you look at JSTL, its core tags are <c:if>, <c:choose>, <c:forEach>, <c:set>, <c:remove> etc... It's just replacing code statements with tags. The "logic" is still ingrained within the presentation. It is still code, just with tags, instead of java. How is this any better for designers or code maintenance? Somehow this made no sense to me.

ASP.NET has the right solution for separation with web controls. You can place these components within a page. These are plain tags like <asp:DataGrid>, <asp:Textbox>, <asp:Labels> etc... They are just responsible for rendering plain html. The logic to decide WHAT they render is placed in a 'code behind' page. Complete separation of code from presentation. Designers don't need to see any logic disguised as tags. I've heard of Java Server Faces which is something that's similar to this thats come up recently. Rahul can expand on it. But I can't believe JSTL was considered a solution at some stage.

Wednesday, February 22, 2006

Outsourcing and Globalization

Seems like stories about outsourcing have cooled a bit. Atleast sources I check haven't been making too much noise about it lately. One of the podcasts I listen to had an interview with a guy who has a small co in NY and outsources to two cos in India - Pune and Delhi. I thought his story was pretty good. Check it out here.

Sunday, February 19, 2006

Broadband as a utility

Really blows my mind... 100 megabits for $25 per month.

Rahul had recently sent me a link to an interview with Josh Bloch/Neal Gafter (java gods) over at javapolis. One of the questions asked was about future directions about the language. Neal Gafter talked about doing more on the client side. He mentioned how the gmail experience would be much better if it could be used as a client app with better offline support. You really have to wonder if this is going to be an issue moving forward with services like what City Telecom is offering - always on connectivity at huge speeds.

Thursday, February 09, 2006

Re: One Thread to rule them all

Since we're having a discussion on threads, this article seemed topical - Threads Without the Pain

Re: One Thread to rule them all

I've used threads in C and Java. In C, I used the pthreads (POSIX threads) library. Of course, it's not as peaceful as threads in Java.

Synchronization is done using mutexes and condition variables. Mutexes allow you to avoid race conditions. Condition variables allow you to wait until any specified condition is satisfied. There's a bunch of functions that are used to do this - pthread_mutex_init/lock/unlock/trylock etc. and pthread_cond_init/wait/broadcast etc.

Of course, thread operations are completely procedural in nature - pthread library functions that take as arguments function pointers/thread variables (pthread_t) and such other stuff.

򪪪򪪪򪪪򪪪򪪪Here's a decent tutorial for pthreads.

Sometimes, it's better to just fork() processes and have them communicate using pipes, semaphores in shared memory etc.

Just a personal opinion - while a lot of things are much easier to do in Java, I would still recommend trying them out in C (or C++) atleast once. You just get a slightly 'inside' view of things... not just threads, even stuff like socket programming. However, for day to day use, Java's a better bet.

Have never used threads in Lisp but I do know that there's a package for threads. While Lisp is projected as an AI language, it has support for a whole lot of things from threads, sockets, interfacing with the OS etc. (OT - While the 'biggest deal' about lisp is its natural use to do functional programming, it also supports procedural and object oriented programming)

Monday, February 06, 2006

Re: One Thread to rule them all

The generic question now. Have you guys come across any similar stuff in other languages? Java has had good support for threading since the early days and now in Java 5 this has been greatly enhanced. What about other languages? C++, C#. And anyone have info about dynamic languages like Lisp, Python etc?

I haven't seen the pattern (WorkerThread) that you wrote about... having one worker thread manage multiple tasks. I don't think this pattern is there in .NET. From what I understand, .NET has a different framework. There is probably a one to one similarity with the Threading package (atleast pre Java 5.0). However, .NET has an asynchronous framework built into all delegates. You can invoke delegates with myDelegate.BeginInvoke() and it will run asynchronously. That is, control will be immediately returned. I believe it picks a thread from a ThreadPool and executes it on that in the background. It's pretty nice in that all your own custom delegates get this feature for free.

When talking about UIs and threads there's another important aspect. Any updates to UI controls should only be made by the thread that created it. So if you have a background thread doing some work and you want to display a message in the UI when it's done, you can't simply access the control and update it directly. You need to marshal any updates through the 'owner' thread. Here's an example in C#...

// UI
public class ClientUI : System.Windows.Forms.Form
{
  private System.Windows.Forms.Label lblStatus;

...

  private void UpdateStatus()
  {
    if ( this.lblStatus.InvokeRequired )
    {
      this.lblStatus.Invoke( new MethodInvoker( this.UpdateStatus ) );
    }
    else
    {
      this.lblStatus.Text = "Done!";
    }
  }
}


All UpdateStatus() is doing is setting a property on a Label. UpdateStatus() would likely be registered as a callback. So when the background thread is done with its processing, it would raise an event and UpdateStatus() would get called. When it does, it can't just update the control since it is not the 'owner' thread. So it needs to marshal the call. This is done with this.lblStatus.Invoke(). MethodInvoker() is just a delegate which takes methods that don't have any arguments and returns nothing. Invoke() takes care of the marshalling.

What's the if/then statement for? InvokeRequired is a property on every UI control. It will tell you if the call was made from the thread that owns the control or not. If it does own it, it's just a direct update, if not, it needs to be marshalled.

All UI elements inherit from the Control class and all of them in turn have the InvokeRequired property and Invoke() method.

One Thread to rule them all

In UI Applications it is a requirement to run some tasks in different threads so that the user will not notice a lag while performing some operations. Also often these threads are either of not very long duration or need to be run one after the other. So how do we solve this?


A small diversion to Threads in Java

Now in Java the Runnable interface is used to create threads. Runnable contains a single method run() which needs to be implemented.

<code>
public class MyThread implements Runnable {
public void run() {
//do some task
}
}
</code>

To execute the above as a separate thread you need to call the start method of the Thread class. The Thread class can accept a Runnable instance

<code>
new Thread(new MyThread()).start()
</code>

start() internally performs some housekeeping to actually create the new thread. After performing the necessary operations, Runnable.run() is called.


Back to our UI Application.

What is done is a simple event queue is built for handling all non-ui tasks. Which internally contains a Queue and a single thread.

<code>
public class Worker implements Runnable {

private Queue queue;
private boolean running;

private Worker INSTANCE = new Worker();

private Worker() {
new Thread(this).start();
}

public static Worker getInstance() {
return INSTANCE;
}

public void run() {
if(!running) {
running = true;
while(true) {
if( queue.peek() ) {
Runnable runnable = queue.pop();
runnable.run();
}
}
}

public void addRunnable(Runnable runnable) {
queue.push(runnable);
}

}
</code>

I have just given a basic skeleton here and left out the most important part of synchronizing the class. The running boolean was added to prevent new Thread(Worker.getInstance()).start(). You guys see any more errors? Threads are one of my primary weaknesses which I hope to rectify by learning about the new Java 5 Concurrency features.


For small tasks it is more efficient to use a Worker like this which internally doesn't create a new Thread for each task and re-uses a Thread or even a thread pool. This is because the start() method does quite a bit internally.

In Swing it's suggested to use a SwingWorker class which does something similar. Also Java 5 (Tiger) has added a new SwingWorker class which is additionally Generic.

The generic question now. Have you guys come across any similar stuff in other languages? Java has had good support for threading since the early days and now in Java 5 this has been greatly enhanced. What about other languages? C++, C#. And anyone have info about dynamic languages like Lisp, Python etc?

Saturday, February 04, 2006

Refactoring enhanced

Probably the single most common refactoring one does when writing code is renaming variables. Saw this cool feature in Visual Studio 2005...