Founder and Lead Engineer at TestDriven Labs (2017–present) · Author has 92 answers and 625.1K answer views · 5y ·
Pros of using Class-Based Views (CBVs) in Django:
- Code reusability: You can reuse your code anywhere in your project — i.e., a view class can be inherited by another view class.
- Reduced Code Duplication: Keeping it DRY! Again, rather than writing the same code over and over again, you can have your views inherit from a base view.
- Well-structured code: Who doesn't like readable code? With CBVs, you can restructure and refactor your code to make it more pleasant and appealing by “hiding” unnecessary code in parent classes and/or mixins.
- Extensibility: Your code can be extended with mixins to include more functionalities.
Cons:
- Readability: Hiding code in parent classes can make your code more elegant, but readability (and understandability) can suffer since not all the code is readily available in a single location.
- Overkill: If the view has a one-off functionality, it's probably overkill to use CBVs. Use them in places where you know you’ll need to reuse a portion of code across multiple views.
- Decorators: It’s harder to implement view decorators with CBVs as they require extra imports.
Django ships with a number of generic view classes that are great for common tasks. If you can take advantage of them either by themselves or with a few overrides, I would start with them. From there, I generally go with Function-based Views (FBVs). If I find myself writing the same code again and again across multiple views, I’ll then look to refactor them into CBVs.
2.6K views ·
View upvotes
· View 1 share
· Answer requested by 1 of 1 answer
Something went wrong. Wait a moment and try again.