正确使用类?
我是一名大学生(计算机科学),刚刚开始 C# 编程课程。 对于我们的作业,我一直使用一个名为“Display”的类,其中放置了可以在整个项目中多次使用的任何控制台输出。例如,继续或退出程序的请求。我不需要在 Main()
中多次键入它,而是从 Display
类中调用该方法。
另一位高年级的学生告诉我,我不应该这样做。这是糟糕的编码实践,我应该只在主类(包含 Main()
)中包含所有方法,并且仅在绝对需要时才使用其他类。
我只是在寻找一些意见和建议。
我被要求包含代码。我原本打算写这篇文章,但不想让这篇文章太长。我选择了一项相当短的作业。我想澄清一下,我只是在学习,所以代码并不像你们许多人写的那么优雅。非常欢迎建设性的批评。
最终我只是在玩类的使用。我知道 Display 类中的一些方法也可以轻松地位于 Main() 中。
这是包含 Main() 的 Program 类
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");
}
}
这是 Display 类
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();
}
}
这是 Request 类
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;
}
}
就是这样。这会被认为是一种低效的编码方式吗?我该如何改进它?
感谢迄今为止的所有投入。这对我来说非常有价值。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
彻底且设计良好的类结构对于遵守面向对象的设计 原则。
以下是考虑将相关代码分解为单独的类的几个原因:
它创建了劳动分工并隔离了不同的任务。这有时被解释为单一职责原则,它说每个对象(类)都应该有一个单一责任并专注于完成单一任务。 封装也很快成为这里的一个重要原则,基本上意味着数据是捆绑的使用负责操作该数据的方法。这也有助于减少错误潜入代码的机会。
它可以帮助促进代码重用。将现有的类与您已经编写的代码集成到另一个应用程序中通常比该代码分散在整个应用程序中要容易得多。为什么要一遍又一遍地重写相同的代码?
精心设计的类结构可以创建逻辑层次结构,使您的代码更易于理解和概念化,并且从长远来看使您的应用程序更易于维护。这与我们将计算机上的文件组织到文件夹中以及我们生活中的其他一切(或者至少我们尝试过)的原因相同。
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).
我绝对不同意。这种思路最终会导致一些夸大的、厨房水槽类的结果,它们最终会做所有。
如果我们谈论结构化编程,您的同事是对的,您可能只有子例程而没有类 - 组织功能的主要方法是将其划分为子例程。但这里我们谈论的是面向对象编程,它也为您提供了将功能划分为不同类的方法。毕竟,类是用来使用的,否则我们就不会称之为 OOP!
如果我是您,我会更喜欢在需要时定义新类的相当自由的方法。
PS: 不用说,确实有一些最佳实践可以帮助您决定是否需要为某些东西创建一个新类,以及应该如何设计它。 (参见 Cody Gray 的回答。)我只想在这里指出,在 OOP 中主动避免类肯定没有意义。
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.
永远不要听那些无法向您解释原因的人说“这是好的做法”或“这是不好的做法” > 这是好是坏。就像在其他领域一样,编程中也存在许多刻板印象,请尽量避免它们。
对于你的特定示例,这有点模糊,因为我实际上不知道你的类是做什么的,我不认为将 IO 功能分离在一个单独的类中是一个非常糟糕的主意。然而,这实际上取决于它的作用,是否独立等等。也取决于个人品味:)
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 :)
一般来说,如果您多次输入相同的内容,我认为就会出现问题。像这样封装显示例程实际上是一种很好的形式。它允许您轻松更改多个实例的输出,特别是对于错误消息之类的内容。
他可能有更多的 C 风格背景,而 C# 则更像 Java。允许甚至鼓励自由使用类。
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.