Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm building a Number Guessing Game for a lab in school, the basic rules of the game are you have 10 guesses to try to guess the number between 1 and 100. My teacher want me to put all the game logic in one class and use the btn_Click methods in the form class to call methods from the game logic class. I feel like it makes sense to put the try catch in the btn_CLick methods because then I can use MessageBox.show to put a message like "You have to enter a number" or "Then number must be between 1 and 100" and but he said he wants the me to be able to take the code and use it without the form class. Any suggestions?
I would not use a try-catch. You could use a TryParse and convert your input from a string into an integer. If it doesn't convert just show an error. If it does convert to an integer you can do an if-then to find out if it's within your wanted parameters.
This could be done via methods contained in the "Logic Class". You could have one method return a true/false that checks if the input is able to be an integer and another that can determine if it's in the range you want.
Your UI would then take those true/falses and display/not display your message box for an error message.
Try/Catches are expensive and it's not useful in this case. If/thens and input validation/sanitation would solve the problems you could have for this program.
I would suggest not using try/catch at all unless you really really need it. So for validating user input, instead of attempting to type-cast the value, which may throw an exception, inspect the input string to see if it is an integer. I'd be surprised if there wasn't already a method for doing this in the C# Library.
Your game logic should be unconcerned with the where and how you get the guesses (numbers) so there really shouldn't be any need for try/catch in the game logic. I'd imagine it would expose a method that might look like this:
public GuessResult MakeAGuess(int guess)
Notice that it takes an integer which it's going to compare with the target number. So nothing here is going to throw. The body might look something like this:
public GuessResult MakeAGuess(int guess)
{
if (guess > target)
return GuessResult.TooHigh;
if (guess < target)
return GuessResult.TooLow;
return GuessResult.Correct;
}
Where GuessResult is a public enum with TooHigh, TooLow and Correct values.
Your UI will be responsible for converting strings to numbers (if that's needed) and any try/catching would be done there. BUT, it would be better to use int.TryParse rather than int.Parse wrapped in a try/catch because it is more efficient. Even better would be to use a more appropriate control on your form to get user input. One that actually is designed for numbers.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
My C# (unity) application claims that an index I am trying to access within an array of strings is out of the bounds of the array. It is not. Here is the array:
public string[] fen =
{
"2q3k1/8/8/5N2/6P1/7K/8/8 w",
"7k/8/8/4b1n1/8/8/5PPP/5R1K w",
"r1bqkb1r/pppp1ppp/2n5/4p3/2B1N3/5N2/PPPP1PPP/R1BQK2R b"
Here is the code accessing it:
void Update()
{
if (PuzzleVariables.instance.puzzlePassed)
{
if (PuzzleVariables.instance.fen.Length < PuzzleVariables.instance.puzzlenumber + 1)
{
SceneManager.LoadScene("ModuleCompleted");
}
else
{
PuzzleVariables.instance.puzzlePassed = false;
FENbuild(PuzzleVariables.instance.fen[PuzzleVariables.instance.puzzlenumber -1]);
}
}
}
Instead of moving on to the next puzzle, it goes on to the ModulePassed screen.
Whenever I try printing the length of this array, it reads 1. What am I doing wrong here?
First
When the runtime says that you are out of bounds, then you ARE out of bounds.
There is no point in arguing that you are not out of bounds with the runtime. Empirically, almost everytime people discuss with their compiler, (ignoring the fact that the compiler is a bad discussion partner because it will not talk back to you but stubbornly repeat his argument over and over, and is not convincable, and immune to threats of all sorts, like throwing pc out of the window and such), it turns out: compiler is right, you are wrong. So skip that episode, and search for the mistake you made instead.
Second
If Puzzlenumber is anything other than 1, 2, or 3, or the Array is shorter than that (non initialized, using wrong array, etc), this will crash. Place a breakpoint on the line where you access your array, and check your variable and also check PuzzleVariables.instance.fen.Length. You might have initialized something you dont use.
Third
Stacktrace. Check your stacktrace to see if your line crashes, or the crash is WITHIN the method FENbuild. Maybe your input is working, but causes a crash down there.
Fourth
Singletons are only used when there is a technical reason for a class to have only one instance, (i.e. resource, printer, etc.).
Is there a reason why you do not work with normal instances? If not, singleton is an Antipattern.
Is say this, because singletons, can have side effects that also make your thing crash. Especially in a multithreaded environment like unity is.
Fifth
In Unity Inspector a public string[] fen; might be serialized => it can have totally different content assigned in the inspector, be empty etc. Changing the code afterwards doesn't change the already serialized array => The Inspector overrules any later changes in code unless you Reset the component
In short:
Please post stacktrace and maybe some reproducable code, and never use singletons.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've been introducing some new C# language features to my team - safe navigation is one of those.
Are there any significant performance reasons to avoid usage of safe navigation for every single object/property call?
e.g.:
myObject?.Field?.FieldValue
vs.
myObject.Field.FieldValue
I know this makes it so every field is null checked - but outside of a tight loop, don't the bugs this catches make it worth it? Or does this encourage lazy coding?
EDIT:
I found an entire article on this topic, hopefully it is helpful for others!
don't the bugs this catches make it worth it?
Quite on the contrary: applying safe navigation everywhere would hide bugs, rather than catching them.
Navigating a null reference by mistake is a bug in the implementation which could mean one of two things:
A field from which you navigate was not supposed to be null
You forgot to null-check a field that is legitimately null
Applying safe navigation is a good choice for case #2, because it lets you perform null check with less code. However, it is a poor choice for case #1, because it lets the object or a variable remain in a state that is incorrect from the standpoint of your program's logic.
That is why programmers should use their discretion when applying safe navigation, deciding each case individually.
Don't safely Navigate when
1) Null is actually an invalid logic for what you're doing
public string ProcessHash(User user)
{
var hash = user?.Password?.Hash
...
}
It's called Safe Navigation not Easy Null Check for a reason. Imagine you're destined to read the code above.
Does ProcessHash expect the user parameter as a null argument? If so, is the Password property of it also supposed to become null? How would you know if the previous coder has used "?." instead of "." just because he's a fan of Elvis? you'd have to analyse the whole code to find out.
2) Null is having another meaning than an unavailability in your code
What does a blind man see? Darkness? Or simply nothing?
What is an empty grocery basket?
// This is a good
Basket<Grocery> basket = new Basket<Grocery>();
var count = basket.Count(); // returns 0
// This smells bad!
Basket<Grocery> basket = null
var count = basket?.Count ?? 0;
3) You're using ?. and extension methods as a pipeline operator!
Don't use ?. to chain Properties and Methods together just because it reduces the lines you write and makes your code cool. there's lots of more well thought high level abstractions behind pipelines in fancy functional codes you see in other languages.
var resp = this.Bind<IceCreamDTO>()?.Validate()?.ToEntity()?.Insert()?.ToResponse();
There's 2 thing wrong with kind of code above.
Imagine if there was an error while validating the bound object. can you return what was wrong with it to the requester? well you can... but it's bad.
// That's not how this works. that's not how any of this works.
try
{
var resp = this.Bind<IceCreamDTO>()?.Validate()?.ToEntity()?.Insert()?.ToResponse();
...
} catch (ValidationException exp)
{
return exp.Errors.ToResponce();
}
well not clearly in the example above(realize it's all method calls not property calls), this also might break encapsulation principles if you're Navigating methods and properties together.
// Privacy violation
bool passwordValidation = user?.Password?.Hash?.Validate(hash);
// Property Security
bool passwordValidation = PasswordHash.Validate(user, hash);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
This is probably quite a simple question, but what is the best practice for return types on a try-catch block? At the moment, I'm doing stuff like this:
public List<SomeAttribute> FindAttributes(int id)
{
try
{
//Some query and some logic
}
catch (Exception ex)
{
Logger.Error(ex);
return new List<SomeAttribute>();
}
}
Is there anything particularly awful about this? The exception will get logged, and the method will return an empty list - which the calling function can handle. Is it better to return null? If so why?
In general one considers three strategies to handle partial functions (functions where only a subset of the input domain is valid): Total, Defensive, and Nominal.
Total
That means that you always return an answer. In this case you can for instance think about returning a null-pointer, in the case of String.IndexOf for instance one returns -1.
Advantages:
It is sometimes easier for a the caller not to think about potential errors. Sometimes the return value can be useful. For instance if you want to cut off a the first part of a string up (and including the first comma), you can code this as:
string foo = "Foo,Bar"
string foocut = foo.SubString(foo.IndexOf(',')+1); //Bar, in case no comma, it returns the entire string
Thus resulting in more compact code. But on the other hand it's sometimes hard to determine what the best return value is.
Disadvantages:
It requires engineering to determine the "best" return value. There are many options and each option will only be beneficial for a part of the callers.
It is sometimes impossible to distinguish between valid output where nothing went wrong and the (default) output in case something went wrong.
Defensive
Here you throw an exception (or don't catch the exception). It is up to a (domain-specific) caller to determine why the exception has been thrown and handle accurately. Util methods have in general not much knowledge about the system and thus don't know why the exception occurred.
Advantages:
The exception can be handled by the caller with the best knowledge (thus some kind of "chain of responsibilities"). This can result in better error handling (providing useful messages to the user). Not "An error has occurred in SQL query ...", but "The username already exists."
Disadvantages:
Error handling is sometimes hard. Especially in C# where one doesn't need to annotate which exception can be thrown by a method. It is not easy to cover all kinds of exceptions. It is possible that an uncatched exception will return to the top Main call crashing the application. For some applications like a webserver, that's not always an option.
Nominal
Here you document your methods and provide precoditions: in the documentation you specify what are the correct ways to use that method. This isn't always possible since sometimes the fact whether a method succeeds depends on external factor (the availability of a server, the type of OS,...). Factors a programmer doesn't necessarily controls.
Advantages:
Results in well documented (and sometimes strictly) defined methods.
Implementing the method (callee) is easier since it can assume everything will work fine.
Disadvantages:
Not always possible (sometimes the result does depend on factors one cannot control).
Writing the caller is harder, since it it has a contract that it will only call the method with the correct arguments.
It is also hard to document all conditions as well as validating that each call satisfies them. Sometimes code contracts are used to handle validation (partially) automatic.
Most programs don't stick with one strategy but mix them: for instance some exceptions are handled total, others nominal and others defensive. Or some module follows the defensive strategy whereas the other uses nominal programming.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
As I continue to further enhance my hangman game in C# to help me learn the language and think like a programmer, there are methods in it that, I think, should be in separate classes. Right now, all the code is on the Form class (Windows Form). This makes calling the needed methods really easy as I only have to use method name and use the necessary parameters. And, as it's only a simple hangman game, this may be the best way to do it. I don't know.
Specifically, one of the methods that I have reads a .txt file that has thousands of words in it, splits it into an array, shuffles the array, then calls another method to do something else.
As I read through some of the literature on C#, I'm told that you want to hide as much of your class as possible. That way you can't break your class by passing data that it can't handle. But this seems to mean that I must add a property to that class in order to access it, in addition to having to create an object of that class, just to be able to use the method I want. That seems like sort of a Byzantine way to just get access to that method.
As experienced programmers can see, I'm not thinking like a programmer yet. My focus is to get the right habits formed early, rather than have to undo bad habits later.
So the question basically is should this method be set as private in a simple program like this? What's the best practice?
Code in question is the following (method that reads the file, forms array, shuffles. etc):
private void ReadFile(StringBuilder hintlength, string[] wordlist, string lettercountpath)
{
string fileContent = File.ReadAllText(lettercountpath); //Read file
string[] array = fileContent.Split((string[]null, StringSplitOptions.RemoveEmptyEntries); //Form array
Random rand = new Random();
for (int i = 0; i < array.Length; i++) // Shuffle algorithm
{
int randIndex = rand.Next(i, array.Lenth);
string temp = array[randIndex];
array[randIndex] = array[i];
array[i] = temp;
}
for (int i = 0; i < 10; i++0) //Assigns shuffled array into wordlist array
wordlist[] = array[i];
if (j > 9) //Checks counter to see how many times it's been clicked
j =0;
Start.Enabled = false;
NewWord.Enabled = false;
WordSelection(hint length, wordlist); // Calls WordSelection method
radioButton1.Enabled = false;
radioButton2.Enabled = false;
radiobutton3.Enabled = false;
if (remainderWords == 1) // Checks remaining words counter
remainderWords = 10;
}
You should set visibility of the class members according to their place in the design, not according to the size of the class or any other considerations.
If a method or a field represents or does something that is relevant to the way the class does its work, but not to the way the users of the class see what it does, mark the member private. The fancy name for this is "implementation details": you do not want to have them exposed to ensure that you can change them later on.
If a method or a field is essential to what the class does for its users, make that member public: otherwise, nobody would be able to use that member, rendering the entire class useless.
If your class is designed for inheritance, and a method or a field is prepared for exclusive use by this class and its subclasses, make that method protected.
If a method or a field is an implementation detail that needs to be visible by other classes inside the same assembly, make the member internal. You can mix internal and protected, further restricting the access to derived classes inside the same assembly.
You should start doing this classification in your mind as you design your software. It is much easier to do this classification when you design smaller systems. However, the importance of doing it right grows tremendously as the size of your system goes up.
There is the concept of having a class for every responsibility. For you Hangman program you need a random word, which you are reading from a file. This is a good time to build a new class: One that reads a word file and gives you a random word.
The part that you will keep private is the actual collection of words. The main game has no benefit by knowing the whole collection, it just needs a random word. Thus, you could build something like:
public class HangmanWordProvider
{
private string[] _words;
public HangmanWordProvider(string inputfile) {
// code to read file into _words variable here
}
public string GetRandomWord()
{
// code to return a random word from the collection
}
}
You would then create a new instance of the word provider to use during the game. Your main HangmanGame now no longer needs to bother with reading a word file, or getting a random word from the collection. You just call your wordprovider.GetRandomWord() and know you get the required data. This is separation of concern.
Now imagine your game grows, you want to make sure the provider does not return the same word twice in a row. This would be something you build into the WordProvider, without having to touch the game class itself.
You can go further and at some point use a database or a webservice to provide words... you would still only have to change the WordProvider, not your game.
The private parts in a class are about hiding the implementation of parts that other classes do not need to know about. In your case, the game does not need to know about how the word list is stored, where it is loaded from, or what way you use to get a random result. It only needs to know how it can get a single random word.
I'm writing the simple card game "War" for homework and now that the game works, I'm trying to make it more modular and organized. Below is a section of Main() containing the bulk of the program. I should mention, the course is being taught in C#, but it is not a C# course. Rather, we're learning basic logic and OOP concepts so I may not be taking advantage of some C# features.
bool sameCard = true;
while (sameCard)
{
sameCard = false;
card1.setVal(random.Next(1,14)); // set card value
val1 = determineFace(card1.getVal()); // assign 'face' cards accordingly
suit = suitArr[random.Next(0,4)]; // choose suit string from array
card1.setSuit(suit); // set card suit
card2.setVal(random.Next(1,14)); // rinse, repeat for card2...
val2 = determineFace(card2.getVal());
suit = suitArr[random.Next(0,4)];
card2.setSuit(suit);
// check if same card is drawn twice:
catchDuplicate(ref card1, ref card2, ref sameCard);
}
Console.WriteLine ("Player: {0} of {1}", val1, card1.getSuit());
Console.WriteLine ("Computer: {0} of {1}", val2, card2.getSuit());
// compare card values, display winner:
determineWinner(card1, card2);
So here are my questions:
Can I use loops in Main() and still consider it modular?
Is the card-drawing process written well/contained properly?
Is it considered bad practice to print messages in a method (i.e.: determineWinner())?
I've only been programming for two semesters and I'd like to form good habits at this stage. Any input/advice would be much appreciated.
Edit:
catchDuplicate() is now a boolean method and the call looks like this:
sameCard = catchDuplicate(card1, card2);
thanks to #Douglas.
Can I use loops in Main() and still consider it modular?
Yes, you can. However, more often than not, Main in OOP-programs contains only a handful of method-calls that initiate the core functionality, which is then stored in other classes.
Is the card-drawing process written well/contained properly?
Partially. If I understand your code correctly (you only show Main), you undertake some actions that, when done in the wrong order or with the wrong values, may not end up well. Think of it this way: if you sell your class library (not the whole product, but only your classes), what would be the clearest way to use your library for an uninitiated user?
I.e., consider a class Deck that contains a deck of cards. On creation it creates all cards and shuffles it. Give it a method Shuffle to shuffle the deck when the user of your class needs to shuffle and add methods like DrawCard for handling dealing cards.
Further: you have methods that are not contained within a class of their own yet have functionality that would be better of in a class. I.e., determineFace is better suited to be a method on class Card (assuming card2 is of type Card).
Is it considered bad practice to print messages in a method (i.e.: determineWinner())?
Yes and no. If you only want messages to be visible during testing, use Debug.WriteLine. In a production build, these will be no-ops. However, when you write messages in a production version, make sure that this is clear from the name of the method. I.e., WriteWinnerToConsole or something.
It's more common to not do this because: what format would you print the information? What text should come with it? How do you handle localization? However, when you write a program, obviously it must contain methods that write stuff to the screen (or form, or web page). These are usually contained in specific classes for that purpose. Here, that could be the class CardGameX for instance.
General thoughts
Think about the principle "one method/function should have only one task and one task only and it should not have side effects (like calculating square and printing, then printing is the side effect).".
The principle for classes is, very high-level: a class contains methods that logically belong together and operate on the same set of properties/fields. An example of the opposite: Shuffle should not be a method in class Card. However, it would belong logically in the class Deck.
If the main problem of your homework is create a modular application, you must encapsulate all logic in specialized classes.
Each class must do only one job.
Function that play with the card must be in a card class.
Function that draw cards, should be another class.
I think it is the goal of your homework, good luck!
Take all advices on "best practices" with a grain of salt. Always think for yourself.
That said:
Can I use loops in Main() and still consider it modular?
The two concepts are independent. If your Main() only does high-level logic (i.e. calls other methods) then it does not matter if it does so in a loop, after all the algorithm requires a loop. (you wouldn't add a loop unnecessarily, no?)
As a rule of thumb, if possible/practical, make your program self-documenting. Make it "readable" so, if a new person (or even you, a few months from now) looks at it they can understand it at any level.
Is the card-drawing process written well/contained properly?
No. First of all, a card should never be selected twice. For a more "modular" approach I would have something like this:
while ( Deck.NumCards >= 2 )
{
Card card1 = Deck.GetACard();
Card card2 = Deck.GetACard();
PrintSomeStuffAboutACard( GetWinner( card1, card2 ) );
}
Is it considered bad practice to print messages in a method (ie: determineWinner())?
Is the purpose of determineWinner to print a message? If the answer is "No" then it is not a matter of "bad practice", you function is plain wrong.
That said, there is such a thing as a "debug" build and a "release" build. To aid you in debugging the application and figuring out what works and what doesn't it is a good idea to add logging messages.
Make sure they are relevant and that they are not executed in the "release" build.
Q: Can I use loops in Main() and still consider it modular?
A: Yes, you can use loops, that doesn't really have an impact on modularity.
Q: Is the card-drawing process written well/contained properly?
A: If you want to be more modular, turn DrawCard into a function/method. Maybe just write DrawCards instead of DrawCard, but then there's an optimization-versus-modularity question there.
Q: Is it considered bad practice to print messages in a method (ie: determineWinner())?
A: I wouldn't say printing messages in a method is bad practice, it just depends on context. Ideally, the game itself doesn't handle anything but game logic. The program can have some kind of game object and it can read state from the game object. This way, you could technically change the game from being text-based to being graphical. I mean, that's ideal for modularity, but it may not be practical given a deadline. You always have to decide when you have to sacrifice a best practice because there isn't enough time. Sadly, this is all too often a common occurrence.
Separate game logic from the presentation of it. With a simple game like this, it's an unnecessary dependency.