I finished my last post on this blog and something began nagging at me. I wrote all about extending a JavaScript class and listed some extended methods I built. All of a sudden I realized I didn't need one of them. (go back and read the original post here.)
Let's look back
Here is the extended class I wrote about:
class AllCards extends Deck {
constructor() {
super()
this.namedCards = []
}
addCardtoDeck(card) {
super.addCardtoDeck(card)
if (card.name) {
this.namedCards.push(card)
}
}
resetNamed() {
this.namedCards = this.unplayedCards.filter(card => card.name)
}
}
If you didn't go back and read my previous post (rude) here is what's going on. I wrote a very simple card game that used a very unique deck of cards (you can't buy these cards in stores). I had built a class to keep track of different decks of cards involved. I extended playable decks (the computer's and players cards) and I also extended an AllCards deck that kept track of every card in the game (even the ones that were not being played with) and also kept track of each card's names and rules.
I needed to keep track of which cards had names and which ones didn't so I "cleverly" extended my addCardtoDeck class to keep track of named cards.
So far so good.
Then I mentioned I created a method called resetNamed that rebuilt my named deck when a new game is started. (Many cards may have gained names while you played).
I posted my blog entry and went to work on something else.
rebuilt my named deck.
extended class to keep track of named cards.
rebuilt my named deck.
extended class to keep track of named cards.
rebuilt my named deck.
extended class to build named deck.
named deck.
named deck.
Wait a second!!!
Not so Clever
I wrote a nice little extended method, but then later wrote a simple method that had the same result. That's repeated work and repeated work is inefficient coding.
So I got rid of the extended class (keeping the original class that builds the deck of all cards). I found the method that called on my Deck class to rebuild all the decks before a new game and leveraged that method before the original game.
The only thing an original game does that repeat games does not do is fetch card data from my database. So truly that rebuilding section of code was just building decks (it didn't matter if they existed before or not)
First games and new games both run a prepForGame method (clear some bits of the DOM, make an addition to the Game Log, clear any old decks), then a first game Fetches Data and sorts that data. After that both first and new games run resetNamed and deal cards to the User and the Computer.
The end result looks so much cleaner. Instead of building my array of Named Cards in two different ways I now did it one place, in one way. Much simpler if I ever need to make future changes.
So my clever extended method wasn't as clever as just not using that method at all.
Top comments (0)