Sunday, May 10, 2009

Web Services: Code-First vs Contract-First approach

One of my colleagues who recently moved to work in a maintenance project based on Java, came back to discuss about the Web Service pattern followed there. He used terms like ‘Top-Down’ and ‘Bottom-Up’ approach and mentioned that so many different things were possible in the Java world.

Curious to find out more on what he exactly meant and also in a secret desire to defend .Net, I explored based on the details he gave.

1. Parameters passed to the web method can be validated based on a limit/range.
a. Ex. Value passed in for an integer parameter can be checked if the value is within a defined range or format. Or a date parameter can have a range specified
2. The Web service code was generated from a defined WSDL and not the usual other way around.

Below are my findings:
There are two approaches to build a web service: Code First approach and Contract First approach.

1. Code First approach – where you write the web methods and then add a web reference of this service in whatever client you are using. If it is a .Net client, it will generate a wsdl file and a reference.vb (or .cs) to define the types and methods used/defined in the service.

2. Contract First Approach – you start working on building the WSDL file first. Define and write your types and methods in the WSDL. The code is generated from this WSDL (.Net provides the option through the wsdl.exe tool).

Which approach to choose, purely depends upon the requirement. The contract first approach is surely the only option when you are leaning on interoperability. If your web service is just going to be consumed internally by your own applications (like how I have been using it all along), then the code first approach should be totally fine.

The contract first approach is tedious and could easily get messy if you are not sure of what you are doing. Also it requires a person to have a very good understanding of the schema design and should be able to fluently code. But then there are quite a few schema designer tools available. But by modifying the schema, you can perform restrictions on the parameters and can even perform schema validations.

One solution that is very popular is Thinktecture Contract First. They provide you with a nice option where it integrates smoothly into the Visual Studio IDE and makes the code generation out of a schema file pretty simple and easy. Also among the many other options, they have encapsulated the Web Service custom validation of SOAP requests against the definitions defined within the source WSDL file using Attributes.

I shared these findings with my colleague and made him realize that what he had seen in his new project is not something related specifically to Java.

References:
http://www.frotscher.com/download/JUG-ContractFirst.pdf
http://ftp.mcs.anl.gov/pub/tech_reports/reports/P1319.pdf

No comments: