Tuesday, July 11, 2017

Starting off with class based views

I started migrating a few of the view functions to class based views. So far, either my views are very different which implies there is not much scope of class inheritance or I need to spend some time thinking of a class inheritance hierarchy. So far, the code below gives an idea of the class based views I have generated.

So I created a BaseView that inherits the in-built View class from Django. This BaseView has a get and a post function which is what I need now. Maybe I can add more later. Each function calls the get_context_data member function which creates the member data context. This context is passed to a template called template_name using the render function. Neither template_name or context are defined in the BaseView. The next class view is the PapersDisplay view that inherits the BaseView. This therefore does not have the get or post methods but merely defines the template_name and contains the get_context_data method that generates the context dictionary.

In a way, this results in cleaner and lesser code because every view does not need the render function which was repeated every time in every view function. However, the code structure is fairly simple. Another option is to create another class with extracts all the papers and inherit that class to add the authors and other data to it. The reason is that the class which extracts all papers could be reused again and again as it seems like a fairly commonly performed task. To add even more abstraction, it might also be possible to create another class which inherits the papers class and provides to each paper, the authors in the paper.

The documentation suggests to be wary about adding too many layers of abstraction as in that case modifying code may become difficult. So I guess I will have to perform the tradeoff between efficiency in code and ease in later development.

No comments:

Post a Comment