using System;
namespace AboutClasses
{
class P2ClassWithOutValidations
{
//Business
rule 1: name should not empty
//Business
rule 2: age should be from 18 to 60
class Person
{
//instance
variables
string name;
int age;
//instance
methods
public Person(string name, int age) //constructor
{
this.name = name;
this.age = age;
}
public void
disDetails() //normal method
{
Console.WriteLine("Name {0}",name);
Console.WriteLine("Age {0}",age);
}
}
static void Main(string[] x)
{
//null value to
name,
Person p1 = new Person("",20); //Rule1 Violated
p1.disDetails();
//Age out of
valid range
Person p2 = new Person("Kumar", 10); //Rule2 Violated
p2.disDetails();
Console.ReadKey();
}
}
}
Name
Age 20
Name Kumar
Age 10
Note:
1. The first output displays the empty value in the name field.
2. The second output displays the age of less than 18.
the Same program can be rewritten like below with validation methods.
using System;
namespace AboutClasses
{
class P2ClassWithValidations
{
class Person
{
//static
methods
static public bool ValidateName(string name)
{
if (name.Equals(string.Empty))
{
Console.WriteLine("Name can't be empty");
return false;
}
return true;
}
static public bool ValidateAge(int age)
{
if (age < 18 || age > 60)
{
Console.WriteLine("Age out of range...");
return false;
}
return true;
}
//instance
variables
string name;
int age;
//instance
methods
public Person(string name, int age) //constructor
{
this.name = name;
this.age = age;
}
public void
disDetails() //normal method
{
Console.WriteLine("Name {0}",name);
Console.WriteLine("Age {0}",age);
}
}
static void Main(string[] x)
{
ReadInputs:
Console.WriteLine("Enter candidate name");
string nm = Console.ReadLine();
Console.WriteLine("Enter candidate age");
int age = int.Parse(Console.ReadLine());
if (Person.ValidateName(nm) && Person.ValidateAge(age))
{
Person p = new Person(nm, age);
p.disDetails();
}
else
{
goto ReadInputs;
}
Console.ReadKey();
}
}
}
Output
Enter candidate name
kumar
Enter candidate age
2
Age out of range...
Enter candidate name
Rajesh
Enter candidate age
15
Age out of range...
Enter candidate name
Chitra
Enter candidate age
20
Name Chitra
Age 20
No comments:
Post a Comment