Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct use of classes?

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.

like image 750
subcan Avatar asked Nov 21 '10 10:11

subcan


People also ask

Which is correct class or classes?

Many of us think we understand the rules governing plural and possessive forms, but misuse is prevalent. The word “class's” is the singular possessive form of the word “class.” The plural possessive form of the same word is classes'. Class with a single apostrophe at the end, class', is incorrect.

Is it correct to say classes?

"Classes" is a plural noun. The verb must also take a plural form to agree with the noun. One class has started. Two classes have started.

Is classes singular or plural?

Use the singular if you see the class as a group of students. Use the plural if you see the class as single students. In British English the plural is used more often than in American English.

What is the use of classes?

A class is used in object-oriented programming to describe one or more objects. It serves as a template for creating, or instantiating, specific objects within a program. While each object is created from a single class, one class can be used to instantiate multiple objects.


2 Answers

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).

like image 153
Cody Gray Avatar answered Oct 06 '22 20:10

Cody Gray


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.

like image 40
stakx - no longer contributing Avatar answered Oct 06 '22 21:10

stakx - no longer contributing