A
A
Alexey FRZ2018-09-10 16:01:46
C++ / C#
Alexey FRZ, 2018-09-10 16:01:46

How to check the values ​​of variables in a constructor?

The class has default values ​​for variables:

int topA = 95;
int topB = 1;
int topC = 89;

Implemented properties with logic:
public int TopA
        {
            get
            {
                return topA;
            }
            set
            {
                if (value > 0)
                    topA = value;
            }
        }
        public int TopB
        {
            get
            {
                return topB;
            }
            set
            {
                if (value > 0)
                    topB = value;
            }
        }
        public int TopC
        {
            get
            {
                return topC;
            }
            set
            {
                if (value > 0)
                    topC = value;
            }
        }

And there is a method:
public bool CheckingAngle()
        {
            bool check = true;
            if ((TopA + TopB + TopC) < 180 || (TopA + TopB + TopC) > 180)
                check = false;
            return check;
        }

It is necessary that when initializing the object (that is, calling the constructor), the method checks the sum of these variables and either asks for values ​​again or aborts with an error.
In general, what practice is considered good in this case? Exception, console message or something else?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#, 2018-09-10
@leshqow

It is necessary that when initializing the object (that is, calling the constructor), the method checks the sum of these variables and either requests the values ​​again or aborts with an error.

what are the difficulties?
you didn't provide the full syntax of the class. but in general it is enough
int topA = 95;
int topB = 1;
int topC = 89;
After creating the class, there is no need to check anything. but after the manipulations - yes, perhaps it is necessary. but this is already the level of your responsibility when writing logic (realize your goal, that's all)

N
Namynnuz, 2018-09-10
@Naminnuz

It is necessary that when initializing the object (that is, calling the constructor), the method checks the sum of these variables and either requests the values ​​again or aborts with an error.

What for?
If you need to do everything in a single class, then it is enough to write a static method and check in it, and then create an object. Throwing exceptions in a constructor is a bad idea. Throwing exceptions in principle is not a bad idea, but they should all be caught by try-catch blocks, with a log entry or somewhere else.
If the task is to write a console application that would initialize the class with the correct values, then it might look, for example, like this:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Toster.Q561594 {
    public static class Extentions {
        public static string Join<T>( this IEnumerable<T> list, string separator = "," )
            => string.Join( separator, list );
        public static int[] ConvertConsoleInput( this string input, params char[] separators )
            => input.Split( separators, StringSplitOptions.RemoveEmptyEntries )
                        .Select( int.Parse )
                        .ToArray();
    }

    public class Triangle {
        public readonly int A;
        public readonly int B;
        public readonly int Y;

        public Triangle(int a, int b, int y) {
            A = a; B = b; Y = y;
        }

        public static bool IsValidAngles( int a, int b, int y )
            => a > 0 && b > 0 && y > 0 && ( a + b + y ) == 180;

        public override string ToString()
            => $"( {nameof( A )}: {A}, {nameof( B )}: {B}, {nameof( Y )}: {Y} )";
    }

    class Program {
        static void Main( string[] args ) {
            int[] temp;

            while ( true ) {
                Console.Write( "Enter three valid space separated angles and press Enter: " );
                try {
                    temp = Console.ReadLine().ConvertConsoleInput( ' ' );
                    if ( temp.Length != 3 )
                        throw new IndexOutOfRangeException($"Incorrect number of angles: {temp.Length}");
                    if ( Triangle.IsValidAngles( temp[0], temp[1], temp[2] ) )
                        break;
                    else
                        throw new InvalidOperationException( $"Incorrect angles: ( {temp.Join( ", " )} )" );
                    
                } catch ( Exception ex ) {
                    Console.WriteLine( "Error. " + ex.Message + Environment.NewLine );
                }
            }

            var triangle = new Triangle( temp[0], temp[1], temp[2] );

            Console.WriteLine( $"Valid triangle object was created: {triangle.ToString()}" );
            Console.ReadLine();
        }
    }
}

When running in the console, it will look something like this:
Enter three valid space separated angles and press Enter: i'm typing
Error. Input string was not in a correct format.

Enter three valid space separated angles and press Enter: 1 2 3
Error. Incorrect angles: ( 1, 2, 3 )

Enter three valid space separated angles and press Enter: 100 10000
Error. Incorrect number of angles: 2

Enter three valid space separated angles and press Enter:    5  100    75
Valid triangle object was created: ( A: 5, B: 100, Y: 75 )

Pay attention to the static class Extentions, whose static methods have this as the first argument. These are extension methods, they allow existing classes to be extended as if they had these methods. StringSplitOptions.RemoveEmptyEntries in ConvertConsoleInput discards the resulting empty strings, so you can enter at least "__4____152______24___", it will first turn it into string[] { "4", "152", "24" }, and then it will parse and return int[] { 4 , 152, 24};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question