r/learnjava • u/MIVEC_85 • Oct 09 '20
Self teaching beginner asking for someone to critique my program
Hello all,
Since losing my job to Covid I've spent my time learning Java at home. The down side is I'm limited in who I can share my code with and ask for advice.
I've spent the last couple of days creating a Hangman game and wondering if anyone can look over it and possible point out anything I should be concreting on or any glaring beginner mistakes??
https://github.com/M1VEC/HangMan
Thanks in advance!!
Edit: thank you to everyone who has offered advice, best practices and tips. I will take them all on board and change what I need to change and learn the bits I don't fully understand π
Edit 2: For anyone who posted their advice and tips, I have made multiple changes and hopefully covered all points that have been made and I welcome you to see if the changes are better. Thanks everyone!
5
u/slowfly1st Oct 09 '20
It's quite good actually. It's easy to read and follow and mostly only smaller things to point out.
Main.java
You declared some public static variables at the beginning and I couldn't see any usages (I'm not using an IDE though). Try to limit the scope as much as possible, it helps to reduce complexity.
userInteraction.into(); -> Didn't understand what it does w/o checking the implementation. ~"displayWelcomeMessage()" would have been better.
selection = new Selection("movies"); and selection.setSelection(); -> Selection of what? Maybe WordSelection? Also: setSelection looks like a setter-method, which usually takes a parameter. So it's a bit confusing, I don't really understand what it does w/o check the impl.
new PlayGame() -> General rule: Classes should be named with nouns (they are something), methods with verbs (they do something).
PlayGame.java
PlayGame extends UserInteraction, but at the same time has a UserInteraction. This I didn't understand.
private char[] available -> availableCharacters?
private final int maxWrong = 9; -> that's a constant, so you could make it static and call it MAX_WRONG_GUESS_COUNT.
private boolean validInput; -> that's only used within the method validateInput, so no need to declare it as member variable. Same for the variable endGame. The less state the class has, the simpler to understand the code.
if(new String(userAnswer).equals(new String(answer))) -> Arrays.equals(), no need to create a string to compare.
if(hintCount == 1){ -> why == 1?
DrawHangMan.java
To get rid of the if/else-stuff: Use a HashMap<Integer,String> and put 1-9 into it with the hangman-string. You could use a static initializer for it.
In newer java versions, there's multi-line-strings, that should be more convenient to work with.
Selection.java
Again lots of member variables. I didn't check, but I think some of them you can get rid of.
file = new File(dir + "\\movieSelection"); -> use File.separator instead of \\.
private String[] readFile()-method: user either try/catch/finally or try-with-resource to ensure that the resources get closed. Also this should throw an exception, when the file couldn't be found and your program should act accordingly, like displaying an error message on the console. Good exception handling is important, because if it's not, you will have strange behavior in production ;-)
int random = new Random().nextInt(setFile().length); -> instances of Random should be declared as member-variable. Two Random instances instantiated within the same millisecond will return the same random integer.
The class in general is a bit confusing. If I were to do that, I'd do something like:
WordRepository wordRepo = new WordRepository("movies");
RandomWord randomWord = wordRepo.getRandomWord();
class RandomWord {
char[] randomWord;
char[] hints;
}UserInteraction.java
playAgain(): Return statement can be simplified by simply using
return "Y".equalsIgnoreCase(play);
And also put the String "Y" first, so it will never ever throw a NullPointerException - and you don't have to ask yourself if "play" could be null.
Also: As far as I remember: There shouldn't be "_"'s within packages name. And: Class names should always start with upper case character.
2
u/MIVEC_85 Oct 09 '20
I thank you for your detailed reply! Some of the stuff I have not learned yet, like hashmap or multi line strings. Nor have I reached the sections for try catch, error handling and how to read files. These are in the 3rd section of the code with mosh course I'm doing. I done some research online when writing this program as I knew I wanted to read a file for the data.
The end goal will be to have different categories, but to get it working was why I passed 'movies' as the parameter.
I don't think I quite understood the extends lesson so I'll have to revisit that part. A lot of what you have said makes sense and is that sort of advice that I'm after as I can't get that sort of feedback from the online course.
Thanks again π
0
Oct 10 '20
[deleted]
1
u/MIVEC_85 Oct 10 '20
I will be spending the majority of today going through my code and all these replies. I've got a few things everyone have mentioned that I need to learn and research.
0
Oct 10 '20
[deleted]
1
u/MIVEC_85 Oct 10 '20
Thank you, the more technical stuff like hashmap and try,catch finally are on the 3rd section of the course I purchased. But before doing that section I've taken the last few weeks writing programs and solving problems on Codewars to try to put into practice what I've been learning.
I have a bad habit of exhausting all options before admitting defeat and asking for help, when instead holding my hand up saying I don't understand this would maybe be better.
1
u/MIVEC_85 Oct 10 '20
Thanks again for all your feedback! I've done multiple changes and I think I've covered most of your points minus the hashmap in the draw class, although I have modified it.
I also have a better understanding of try with resources. I will be adding more of these to my code and any code going forward.
3
u/chizhi1234 Oct 09 '20
You could use case/switch for your Drawhangman class so it looks better rather than keep elsing with.
But on the other hand I don't think I'm as productive as you, as I am learning java right now in uni and I still suck
1
u/MIVEC_85 Oct 09 '20
Slowfly mentioned to use hashmap string, I havn't learnt that yet but I will try this weekend.
1
u/MIVEC_85 Oct 10 '20
I decided to go with the case switch route and also altered the whole class, I think it's a lot better now, thank you
3
u/phun_2016 Oct 10 '20
You have a lot of if/else statement which you could make more elegant by using ternary statements.
You are using the test annotation in the test file with no assertTrue/ assertFalse. In fact I don't know what you are doing there.
1
u/MIVEC_85 Oct 10 '20
The intention was to use assertTrue tests when I started, but I soon figured I didn't know what tests to write. This is only the second program I've done with tests and don't really have the experience to do them properly yet.
1
u/MIVEC_85 Oct 13 '20
I've restructured my code to allow me to complete the tests I originally wanted to do. I know this is back to front but as I mentioned this is only the second time I've tried to write tests and I wasn't too sure on what tests I needed to write. When I start my next project I'll be more assertive with the tests.
2
2
u/Koyomii-Onii-chan Oct 09 '20
First of all good job on your project. I will post below some things that could be improved.
You have DrawHangMan class. From the look of it it's an utility class. This type of classes should not have the ability to be instantiated. Declare an empty private constructor for this.
In the Selection class you have the readFile() method. I suggest you use a try with resources for automatic closer of the bufferedreader. You can remove "reader.close()"
try (BufferedReader reader = new BufferedReader(new FileReader(file));)
3) Still in the class selection you have:
private String selection; // don't use the same name as the class it can be confusing
String[] split = selection.split("-"); // also don't use names that are the same with the build-in methods. split is either and array or the split() method
4) In the class UserInteraction you have
if (play.equalsIgnoreCase("Y"))
Don't use equals methods like this. You don't know what user will insert in the "play" variable. You are 100% sure that "Y" will stay the same so use
if ("Y".equalsIgnoreCase(play))
Also if I press "enter" an exception will be thrown. Consider checking for input even on the first letter.
3
u/MIVEC_85 Oct 09 '20
That is some great feedback! What you've written is really good to know that I wouldn't of learn by myself. I will make the changes later tonight or tomorrow as just settled down for dinner. I have not came across utility class before, but will look that up so I know what I should be doing. Thank you!!
1
u/MIVEC_85 Oct 11 '20
So I'm taking some time to read up on utility classes as I didn't know that's what I had created with the DrawHangMan class. What's your feeling on this, should I modify it to not be static and then not a utility class or just do what you said previously and add a private constructor? From what I've read, a lot of people don't like utility classes. As I'm a beginner I'm not sure what to do with this scenario and after what would be considered best practices.
2
u/Koyomii-Onii-chan Oct 11 '20
It's fine to make them non-static since the main focus of the class is to draw and you do this in one place. Utility classes have methods that are used all over one app. Let's say for example you do a math app and you write the method addtwonumbers(). You could use this method on lot of different classes: a matrix class, a function class, an equation class etc. You don't really need to declare a different addtwonumbers() method for each of the classes. In this case both approaches are fine. If you make them non-static you need to instantiate an object, if you let them like this make the constructor private
1
u/MIVEC_85 Oct 11 '20
Brilliant, thanks for that. I think I'll change them from being static as it's only accessed from the Game class and I don't need other classes to access it. Would it be deemed ok to instantiate it from the constructor of another class like the Game class or would it be best to instantiate it in main and pass it as a parameter into Game?
2
u/Koyomii-Onii-chan Oct 11 '20
Just declare it as private at top of Game, since you only use it there. No point in passing it as a parameter
1
2
u/njc192 Oct 10 '20
I really like your DrawHangMan class! :) I thought it was really clever. I think it looks good! I didnt look over the whole thing but from what I saw I was impressed :) Good work and keep going!
1
u/MIVEC_85 Oct 10 '20
Thank you, I'm actually in the process of cleaning it up and making it more efficient, I will let you know once I've pushed it to the repository and you can see if it's better or worse
1
1
u/SirNinjas Oct 10 '20
Hey, I'm currently also trying to learn java. What resources did you use to help you learn to make this program?
1
u/MIVEC_85 Oct 10 '20
I learned the basics from "code with mosh', I'm also learning new skills from my brother and I'm also learning from completing challenges on Codewars.
As you can see from everyone's comments and advice I've still got a long way to go. I would recommend you check out Codewars though. You have to solve mini problems that get harder and harder as you rank up, but you can select which ones to do, for me I find a subject I'm weak on and concentrate on that. Once you complete a challenge you get to see how others completed the same challenge which you can learn new tricks from.
I've stored all the ones I've completed on GitHub in a private repository along with the best answers from others.
2
1
Oct 09 '20
[removed] β view removed comment
1
u/MIVEC_85 Oct 09 '20
Thank you, I've got some feedback that I need to rectify tonight, ones a typo and one is invalid characters registering as valid.
10
u/serreplant Oct 09 '20
Cool game, well done! Just some details:
- in the intro text you say: "if you need a hint type '!' .. but you have to type '?' for hint
- if I type '_' it is registered as valid letter and I get 'Incorrect guess' and not 'Please enter a valid letter'
I would suggest writing some more tests and thinking about what could go wrong.