Lesson 29 - Refactoring
LEARN
Today
- Refactoring
- Test-driven changes
- Convert to ForeignKey
Django for Beginners - Chapter 15
- Comments on Articles
- Articles app
- URL, Templates, Views
- ForeignKey - Comment, Article
Refactoring
- All code naturally decays
- Refactoring is needed to improve the structure while preserving functionality
- Design after the code is written
Martin Fowler
- Refactoring - Martin Fowler
- Defines why, when, and how to refactor
Why
- Incrementally improve code structure
- Preserve the usefulness of the code
- Protect the investment
- Refactoring is the single most important skill
When
- In preparation of new features
- When it gets hard
- After the features work
How
- Automated test rule - Test it or take it out
- Find duplicate code and dead code
- Remove it
- Test-driven development
- Test, Fix, Enhance, Improve (refactor)
Tests
- Do not refactor without tests
- Let the tests guide you
- Spot check with manual testing
BUILD
Visual Studio Code Tools
- Analysis
- Peek/Go To Definition, Declaration, References
- Show Call Hierarchy
- Refactoring
- Extract Method
- Extract Variable
- Move Method
- Rename
To Do
- Test
- Build tests Author, Book Foreign Keys
- Prep Manual Test script
- Extend
- Convert Authors, Book, Chapters to use ForeignKey
- Improvements
- Simplify and refactor
Demo Code
- Demo Code
- Follow along with my source code
- Clone my repo and edit the code
Author Data Model
Create a representation for Authors
python
class Author(models.Model):
name = models.CharField(max_length=200)
user = models.ForeignKey(User, on_delete=models.CASCADE)
Book Data Model
Create a representation for Chapters in the Book
python
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
Chapter Data Model
Create a representation for Chapters in the Book
python
class Chapter(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=200)
Author's Books
List the Book by an Author
book/views.py
```python
urls.py
path('author/', AuthorDetailView.as_view(), name='author_detail'),
class AuthorDetailView(DetailView): template_name = 'author_detail.html' model = Author
def get_context_data(self, **kwargs):
author = Author.objects.get(pk=self.kwargs['pk'])
return dict(object=author, books=Book.objects.filter(author=author))
```
Project 10 - Superhero News
- Views
- Query for Articles about each Hero in HeroDetailView
- Add the article list to hero detail template
- Data
- Add hero as ForeignKey in Article
- Migrate
- Tests
- Hero Data
- Hero Views
- Article Data
- Article Views
Project 10 - Views
- Superhero Selector Page
- Profile Tab
- News Tab
- Article Views
- Hero Views
Project 10 - Data
- Investigator Data Type
- Investigator <-- Hero <-- Article
- Views support proper queries
- Hero News style
Project 10 - Tests
- Data/Views
- Investigator, Hero, Article