r/javahelp • • Mar 16 '21

I wrote a simple card deck with a shuffle capability, can anyone review it? I’m newer to java and don’t want to build bad habits.

Github link in comments

16 Upvotes

23 comments sorted by

•

u/AutoModerator Mar 16 '21

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

4

u/wsppan Mar 16 '21 edited Mar 16 '21

Looks pretty good. Couple things:

  1. You can use the pretty efficient Collections.shuffle() method based on fisher-yates.

  2. You can make your code more generic by handling different deck sizes (i.e. casinos use multiple decks for black jack or a deck used to play pinochle)

2

u/[deleted] Mar 16 '21

Noted, thanks. I’m using this for a blackjack game so i went with 52

3

u/wsppan Mar 16 '21

Like I said, casinos use anywhere from 1 - 8 standard 52 card decks, shuffled, for their dealer shoes. So, your code should be able to take 52 to 416 cards (one to eight 52-card decks) prior to shuffling and dealing.

3

u/djavaman Mar 16 '21

The card constructor seems odd with the user of cardCount.

A two value constructor seems more natural. And that would give you something like this:

for(int rank = 0; rank < 14; rank++) {

for(int suite = 0; suite < 4; suite++) {

deck.add(new Card( rank, suite ));

}

}

2

u/desirecampbell Mar 16 '21

I expected Card to have a two param constructor as well. The use of cardCount is interesting but seems weirdly limited. I also would have expected the Deck constructor to take an int param for the number of cards in the deck.

Also, returning the Deck's deck arraylist allows other classes to modify the list directly, it would be safer to return a copy of the list instead.

2

u/le_bravery Extreme Brewer Mar 16 '21

I wanted to also jump on this and say similar things, but add some additional reasoning why it's bad to do it this way.

1st: OP, good work! You've built something that works. That's not easy, and the fact that you're asking for feedback is great. The desire to improve is always good.

So, with code, one of the primary qualities is reusability and coupling between sections of code. One of the primary problems programmers deal with is code which has dependencies on other code. Either explicit or implicit. Ideally, you want to manage your dependencies so you know what and where to make a complete change that may be required.

Currently, your Deck constructor has an explicit dependency on the Card constructor. This is totally known and expected, as to construct a deck, you probably have to construct some cards.

However, your Deck constructor *also* has an *implicit* dependency on the inner workings of the Card constructor. Because you're not passing in the Suit and Rank independently into the constructor, and instead relying on that static variable, you tie the Deck constructor to the Card constructor.

In your code, there is only one right way to call the Card constructor, and that's using the code in the Deck class, that's not visible for the Card constructor. So, say you want to change something in the Card class in the future. Now you have to make a change in the Deck class.

So why does this matter? Well, if you're never going to make any changes, it doesn't. But, as professionals, programmers are asked to change and evolve their systems over time.

You say you're currently building a blackjack system. Some changes I could see coming in the future: multi-deck functionality. Adding new games. What if a new game requires a Joker to be added as a Rank? Could you make any of these changes only touching one of your classes? Maybe? Maybe not. These are the considerations you should look at for designing classes.

Also, another harder concept that *would* trip you up if you included it: Threading and concurrency. Currently, your Card constructor relies on the static variable with no guarding whatsoever. If you had two Decks being constructed in parallel the resulting decks would probably contain 52 cards each, but they would almost certainly contain duplicates in weird quantities. You may not even have a full set of 2 decks split between them, and you may end up with 3-4 of the same card instead of just 2 copies in incorrect decks.

1

u/[deleted] Mar 16 '21

ah yes I totally see what you mean. I was only making this for a blackjack project so I decided to instead use the static variable, as I don’t need to construct any cards outside of Deck. How might I begin to make this thread safe? I have * some * experience with asynchronous javascript and I imagine there are some parallels with it.

2

u/le_bravery Extreme Brewer Mar 16 '21

Thread safety is hard. In this case, using that static variable approach, there is no way to make it thread safe.

For information on thread safety, I suggest reading at least the first few chapters of “Java Concurrency in Practice” by Brian Goetz.

The thing that makes concurrency hardest in Java is the memory model. There’s keywords like synchronized and volatile which can be used to allow the same object to be shared by multiple threads. It’s fairly easy to get an object to be thread safe with those tools but the real thought has to go into how to make it thread safe and fast and performing as required. There’s levels of complication here.

Wherever possible, it makes sense to make it so a class can be used across threads, and an object instance can be isolated to a single thread.

2

u/PacManiac42 Mar 16 '21

Or maybe even better: Make the enums from Card public and use them for the creation of the deck:

for (Rank rank : Rank.values()) {
    for (Suite suite : Suite.values()) {
        deck.add(new Card(rank, suite));
    }
}

1

u/PacManiac42 Mar 16 '21

It's a solid start. Some small stuff:

You made some member variables final ("suite" and "rank" in Card), but others, which could also be final, not (e.g. "value" in Card, "deck" in Deck). My advice: make all member variables final, if possible.

On the other hand, on local variables and method parameters the "final" keyword adds little value and should be omitted in my opinion.

Avoid static state, like the "cardCount" in Card. I think this should go into Deck.

To me, the "do ... while" loop in "shuffle()" is harder to read than a classic "for" loop:

for (int i = 0; i < times; i++) {
   ...
}

And of course: only implement shuffle (or sort or similar stuff) only yourself if you want to do it for fun. Otherwise always use existing libraries.

1

u/[deleted] Mar 16 '21

I originally wanted to have the while loop be like a falsy clean loop (e.g. while(—i)) but once i found out java didn’t do implicit boolean casting i instead just added a comparison instead of making it a for loop. Also I feel like while describes what I am trying to a do a little better. As for the final variables or lack thereof, I come from javascript where there is a cult around always using const so I think I brought that with me. I wanted value to be non-final because I intended on possibly changing it for aces in blackjack.

2

u/wildjokers Mar 17 '21 edited Mar 17 '21

Out of curiosity why do you have a static cardCount variable in Card? That counter should be non-static and should be in Deck. A card is in a deck so the deck should know how many cards it has.

Also, you should get used to putting the { on the same line i.e.:

if (something) {

instead of

if (something) 
{

If you get a java job most likely they will use the first style. On occasion you will find people using the style you are but it is rare. You want to see as many lines of code as you can and a line dedicated to the opening bracket is a waste of screen real estate. This applies everywhere you use an opening bracket, not just for ifs.

For this, private ArrayList<Card> deck = new ArrayList<>(); it is more common to use the interface name on the left side, so use this instead:

private List<Card> deck = new ArrayList<>();

In your for loops you have a couple of values (14 and 4) that are meaningless to other people reading your code. Put them in constants with descriptive names. 14 * 4 is 56, so not sure why you are choosing 56 cards. Descriptive names for those would probably help, as would a small comment with a quick explanation why you are choosing 56 cards instead of 52.

In your do/while condition you are using prefix decrement, you are just asking for subtle bugs using prefix. You should consider refactoring that so prefix decrement isn't used.

Declaring variables in one line like this:

int max, index;

is generally frowned upon in java. Just put them on separate lines.

Why are you cloning the newDeck?

deck = (ArrayList<Card>) newDeck.clone();

Not needed.

You may want to see if you can reorder the list in-place instead of creating a new Deck for each shuffle. Can get interesting solutions if you google "java reorder list in place".

Also, instead of a List for your Deck, consider using a Stack. A deck of cards is perfectly represented by a Stack (except for the need to shuffle).

EDIT: I now see that you start your outer loop at 1 but your inner loop at 0. Why? I have a feeling you were having trouble getting exactly the number of cards you wanted and were just messing with your loop start value and condition until you got the number you wanted. Might I suggest this instead:

  for(int i = 0; i <= 12; i++) {
        for(int j = 0; j <= 3; j++) {

Also instead of passing the constructor of Card an int. Simply provide it its Rank and Suite enums. You will need to pull the two enum out as their own classes. So:

 public Card(Suite suite, Rank rank)

1

u/nutrecht Lead Software Engineer / EU / 20+ YXP Mar 17 '21

You really should never use static variable to carry state. That static 'cardcount' is something you desperately want to avoid. Doing this at a larger scale is going to make your code impossible to understand and debug eventually.

https://stackoverflow.com/questions/19209468/why-is-global-state-bad

-1

u/erihel518 Mar 16 '21

Looks pretty good to me. Good Job!

I would be careful using features from anything greater than Java 11 unless you don't have another option. Most devs stick to the LTS(Long Term Support) versions. The next should be Java 17 later this year.

Just curious, Why did you choose to use ENUM's? Just for practice with it? Not that there's anything wrong with it, It got the job done. I probably would have had a different approach.

3

u/yevster Mar 16 '21

Enum seems like the perfect choices or suit and rank, as raw numbers should not be used without additional logic. But instead of exposing those enums, you hide them inside Card and leak the underlying integer values. Why???

1

u/yevster Mar 16 '21

Similarly, the Card constructor is aware of the implementation details of the enums, whereas those should be encapsulated inside the Enums for a cleaner approach.

1

u/yevster Mar 16 '21

I’d highly recommend reading Effective Java by Joshua Bloch - it’s exactly about the kinds of good habits you’re trying to pick up and bad habits you’re trying to avoid.

2

u/PacManiac42 Mar 16 '21

Why would you not use enums here? I think it's a very sensible choice for this use case.

1

u/desirecampbell Mar 16 '21

As another pretty new Java programmer, I'd also use enums (though I would have put them into a separate file) - what method would you have gone with?

1

u/wildjokers Mar 17 '21

I would be careful using features from anything greater than Java 11 unless you don't have another option. Most devs stick to the LTS(Long Term Support) versions. The next should be Java 17 later this year.

This is like beating a dead horse; however, if you don't pay for support LTS means absolutely nothing and you should just always stay on the most recent release. Why would you care what version a vendor has chosen to offer long term support for if you aren't paying for long term support?

Just curious, Why did you choose to use ENUM's? Just for practice with it? Not that there's anything wrong with it, It got the job done. I probably would have had a different approach.

This is an absolutely perfect use of enums and enums is the correct approach.