Reputation: 2151
I am college student (computer science) and have just started a C# programming class.
For our assignments I have been using a class called "Display" where I put any console output that could be used several times throughout a project. For example, a request to continue or exit program. Instead of typing it out several times in Main()
I just call the method from the Display
class.
Another student in a higher level class has told me that I should not do this. That it is poor coding practice and that I should just include all methods within the primary class (containing Main()
) and only use other class when absolutely needed.
I am just looking for some input and advice.
I was asked to include code. I was going to originally, but didn't want to make this post too long. I have chosen one assignment that is fairly short. I want to clarify that I am just learning so the code is not as elegant as many of you can write. Constructive criticism is very much welcome.
Ultimately I am just playing with the use of classes. I know that some of the methods in the Display class could just as easily be in Main().
This is the Program class that contains Main()
namespace Chapter_6_10
{
class Program
{
static void Main()
{
string triangle = "", result = " ";;
char printingCharacter = ' ';
int peakNumber = 0;
Display.Instructions();
Display.Continue();
// perform a do... while loop to build triangle up to peak
do
{
Console.Clear();
Request.UserInput(out printingCharacter, out peakNumber);
int counter = 1, rowCounter = 0;
do
{
do
{
triangle += printingCharacter;
rowCounter++;
}
while (rowCounter < counter);
counter++;
rowCounter = 0;
triangle += "\n";
}
while(counter != peakNumber);
// perform a do... while loop to build triangle from peak to base
do
{
do
{
triangle += printingCharacter;
rowCounter++;
}
while (rowCounter < counter);
counter--;
rowCounter = 0;
triangle += "\n";
}
while (counter != 0);
Console.Clear();
Console.WriteLine(triangle); // display triangle
Display.DoAgain(out result); // see if user wants to do another or quit
triangle = "";
}
while (result != "q");
}
}
This is the Display class
namespace Chapter_6_10
{
// This class displays various outputs required by program
class Display
{
// This method display the instructions for the user
public static void Instructions()
{
Console.WriteLine("\nThis program will ask you to enter a character to be used "
+ " to create triangle."
+ "\nThen you will be asked to enter a number that will represent the"
+ "\ntriangles peak."
+ "\nAfter your values have been received a triangle will be drawn.");
}
// This method displays the choice to continue
public static void Continue()
{
Console.WriteLine("\n\nPress the enter key when you are ready to continue...");
Console.ReadLine();
}
// This method displays an error message
public static void Error(string ErrorType)
{
Console.WriteLine("\nYou have entered \"{0}\", which is a value that is not valid!"
+ "\nThis is not rocket science."
+ "\n\nTry agian...", ErrorType);
}
// This method will ask user to press enter to do again or 'q' to quit
public static void DoAgain(out string Result)
{
string input = " ";
Console.WriteLine("\nPress enter to run program again"
+ "\nor type the letter 'q' to close the application.");
input = Console.ReadLine();
// convert input to lowercase so that only one test needed
Result = input.ToLower();
}
}
This is the Request class
namespace Chapter_6_10
{
// This class is used to get user input
class Request
{
public static void UserInput(out char PrintingCharacter, out int PeakNumber)
{
string input = " ";
char testCharacter = ' ';
int testNumber = 0;
// a do... while loop to get Printing Character from user
// use TryParse() to test for correct input format
do
{
Console.Write("\nPlease enter a character to be used to build triangle : ");
input = Console.ReadLine();
bool result = char.TryParse(input, out testCharacter);
if (result)
{
}
else
{
Console.Clear();
Display.Error(input);
input = " ";
}
}
while (input == " ");
// a do... while loop to get number from user
// use TryParse() to test for correct input format
do
{
Console.Write("\nPlease enter a number <between 1 and 10> for the peak of the triangle : ");
input = Console.ReadLine();
bool result = int.TryParse(input, out testNumber);
if (result)
{
if ((testNumber > 0) && (testNumber < 11))
{
}
else
{
Console.Clear();
Display.Error(testNumber.ToString());
input = " ";
}
}
else
{
Console.Clear();
Display.Error(input);
input = " ";
}
}
while (input == " ");
// assigned received values to 'outs' of method
PrintingCharacter = testCharacter;
PeakNumber = testNumber;
}
}
That is it. Would this be considered an inefficeint way to code? How can I improve it?
Thanks for all the input so far. It is very valuable to me.
Upvotes: 7
Views: 627
Reputation: 84835
That it is poor coding practice and that I should just include all methods within the primary class [...] and only use other class when absolutely needed.
I absolutely disagree. This line of thinking would eventually lead to a few blown-up, kitchen-sink classes that just end up doing everything.
Your colleague would be right if we were talking about structured programming, where you might only have subroutines but no classes — the primary means of organising functionality would be to divide it up into subroutines. But here we're talking object-oriented programming, which also gives you the means of dividing up functionality into different classes. Classes are there to be used, after all, otherwise we wouldn't be calling this OOP!
If I were you, I'd prefer a rather liberal approach of defining new classes when you need them.
P.S.: It goes without saying that there are indeed best practices that help you decide whether you need a new class for something, and how you should design it. (See e.g. Cody Gray's answer.) I merely want to point out here that it definitely doesn't make sense in OOP to actively avoid classes.
Upvotes: 8
Reputation: 245001
A thorough and well-designed class structure is extremely important in adhering to object-oriented design principles.
Here are just a few reasons to consider breaking related code up into separate classes:
It creates a division of labor and segregates differential tasks. This is sometimes explained as the Single Responsibility Principle, which says that every object (class) should have a single responsibility and focus on completing a single task. Encapsulation also quickly becomes an important principle here, basically meaning that data is bundled with the methods that are responsible for operating on that data. This also helps to reduce the opportunities for bugs to creep into your code.
It can help promote code reuse. It's often much easier to take an existing class with code that you've already written and integrate it into another application than if that code was scattered throughout the application. Why rewrite the same code over and over?
A well-designed class structure can create a logical hierarchy that makes your code easier to understand and conceptualize, as well as making your application easier to maintain in the long run. It's the same reason why we organize files on our computer into folders, and everything else in our lives (or at least we try).
Upvotes: 15
Reputation: 2439
In general, if you're typing the same thing multiple times, than something is going wrong, I think. Encapsulating Display routines like that is actually good form. It allows you to easily change the output at multiple instances, especially for things like error messages.
He might be coming from more of a C-style background, whereas C# is more of a java-like than anything. Liberal use of classes is allowed, even encouraged.
Upvotes: 0
Reputation: 133122
Never ever listen to someone who says "This is good practice" or "This is bad practice" if they cannot explain to you why it is good or bad. Just like in every other field, there are many stereotypes in programming, try to avoid them.
For your particular example, which is a bit vague, because I don't actually know what your class does, I don't think separating IO functionality in a separate class is a terribly bad idea. However that really depends on what it does, whether or not it is independent, etc. etc. Also depends on personal taste :)
Upvotes: 6