Refactoring Web App code when API gets added later

69 Views Asked by At

I have a Web Application for which we are adding an API now.

I am looking for best practices to keep in mind while working on this.

I am considering these factors:

  • DRY: Avoid redundancy (to the extent possible). Take for example, a part of the code which handles a form submission. There are some parts which are applicable for only Web Form submission but not relevant to the equivalent API Post call. I am thinking of modularizing the common code behind this Post handlers. I must add that the handler classes for Web Form and API are different. I am creating a third class which will have the common methods. This third class would be inherited by the two handler classes (along with their other base classes, multiple-inheritance).

  • Should I refactor the code such that the Web Form 'Post' handler method in turn calls the API Post method?

Thanks.

1

There are 1 best solutions below

2
On

I think the specifics of this will vary significantly on a case by case basis, but I did something like this recently, and I'll share what I came up with.

This is how I organized my handlers so I don't repeat myself:

class MyHandler(webapp2.RequestHandler)
    class ApiHandler(MyHandler):
        class Ajax(ApiHandler): # Ajax calls on my website
        class V0(ApiHandler): # V0 of my REST API for third parties
    class WebHandler(MyHandler):
        class HomePage(WebHandler):
        class OtherPage(WebHandler):

I added a lot of utility methods that can be used by subclasses. For example, MyHandler has a write_json method because that is used in a lot of places, and ApiHandler has a process_json method because that is used only by APIs.

I think it is a bad idea to avoid repeating yourself by having one post method call another post method. Instead, I think it would keep your code cleaner to do the refactoring at the model level.