سؤال

first of all let me say that this is not so much a question of how to get it to work, it is more a question of whether this is good practice or not.

I want to implement a deck of cards (As seen in a lot of games, for example TCG games), with a custom shuffle() method... For now it uses a standard library method, but that may change in the future.

The code:

package model;

import java.util.Collections;
import java.util.Stack;

/**
 *
 * @author Frank
*/
public class Deck<T> extends Stack<T> {
    public void shuffle() {
        Collections.shuffle(this);
    }
}

Current code where I use it:

private Deck<Card> deck;

Just wondering if this is good practice, eager to hear answers.

هل كانت مفيدة؟

المحلول

No this is not good practice. Your Deck class should contain a Stack, it should not be a Stack.

I'm not sure you want Stack anyway. It is more likely you want ArrayList<Card> or something like it.

نصائح أخرى

I'd better use delegation instead of inheritance here. Extending a stack makes you stuck with it forever, while delegation will let you replace a stack with something else easily.

Additionally, it is generally not best practice to extend collections. Java 8 would introduce a lot of new things to collections which could break you implementation or your logic.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top