Wednesday, February 25, 2009

REST and Déjà vu

REST is getting a lot of attention. I'm still working my way through "RESTful Web Services" by Leonard Richardson and Sam Ruby.

As I understand REST, if I want to access a resource I can use the GET method and I will receive a representation of that resource that includes that resource's data. If I want to update the resource, I use the PUT method to "save" the resource's new data.

What does that remind me of? Think. Think.

Ah yes! My early days of coding in C. I would get a struct-full of data from somewhere, change one or more members, and then call some method that persisted those changes. The struct I was changing just contained data and had no behavior.

Object Orientation

Later on I learned how to encapsulate the struct's data and use functions to provide behavior for the struct. Then I learned about Object Orientation (OO). With OO, as a user of an object, I don't need to know anything about the object's data, what its members mean, valid combinations of data, etc. I let the object handle all that stuff.

I know OO isn't a panacea and that it isn't universally accepted and that those who do accept it rarely agree on what it means or how to do it right. But hasn't it taught us that encapsulation is good?

I do know that I don't want to go back to programming like I did in my early days of C programming.

Un-RESTful Web Services

I'm not saying that we need to start exposing all our objects via URIs. Objects typically have chatty interfaces (lots of fine-grained messages passed to the object) and chatty doesn't scale very well.

I do think that the Facade design pattern can be used to keep the interfaces more chunky (fewer, but coarser-grained messages passed to the facade) and our systems performing better.

This is the approach that many web services use today.

Hackable URLs

REST provides hackable URLs:

GET /book (returns all books)
GET /book/123 (returns the representation of book #123)

That's very cool. There's nothing preventing us from using hackable URLs in web services. In fact all you Smalltalkers and Objective-Cers might feel right at home with URLs like:

/book/123/delete (deletes book #123)
/book/124/loanToUser/432 (loans book #124 to user #432).
/books/addTitle/Object+Thinking/copies/4/branch/Central (adds 4 copies of a book to one branch's inventory)

Encapsulation

Another reason why we use objects is because our object's representation, the very thing that REST makes public, might change and we don't want the user of our object to be affected by a change to our object's internals.

Conclusion

I'll keep reading the RESTful Web Services book and hopefully I'll find out that I've misunderstood everything and that REST really is a step forward (or at least sideways) and not a step backwards.