When we talk about any class or object it has two things – Data and Business logic. When it comes to data we have variables. When it comes to Business logic we have some intermediate results and for that again we have variables.
Variables are simply named memory locations where we can store our data or temporary results.
Let’s have a small example about variable.
public class Customer
{
publicstring customerName;
}
.
.
Customer c=new Customer();
c.customerName= “Sukesh Marla”;
Let’s have one more example.
public class Customer
{
publicstring customerName,
publicint age;
}
.
.
Customer c=new Customer();
c.customerName= “Sukesh Marla”;
c.age=55; //Perfect
c.age=555; // Ohh!! No, what the hell is this?
c.age= -5; //What rubbish.
Our data is not protected. It should be validated before it dumped into variable.
Now the question is who will do the validation?
We have two developers with us now – one who have developed the above class (let’s call him creator) and second who will use this class (let’s call him end developer).
If end developer do this validation then,
- It’s strictly a violation of SOC ( separation of concerns)
- It will be difficult to reuse the validation logic.
So the final decision is to put validation in Customer class itself by its creator.
For this we will simply create a function in Customer class which will do the validation and return either true or false. End developer will just call that function before assigning value.
Example
public class Customer
{
publicstring customerName,
publicint age;
publicboolIsValidAge(int _age)
{
If(_age>0 && _age<100)
{
returntrue;
}
else
{
return false;
}
}
}
.
.
Customer c=new Customer();
c.customerName=”Sukesh Marla”;
intTempAge=int.parse(TxtAge.Text);
if(c.IsValidAge(TempAge))
{
c.Age=TempAge;
}
Is there any issue more?
Yes, what if end developer fail to forget to call IsValidAge method before assigning value.
Ultimate solution – Property
Our data should get validated as soon as someone try to put values to it and for that we have properties in C#. It is an encapsulation over our normal variables providing get and set accessory. Get will be executed when someone try to retrieve the value of it and set will be executed when someone try to modify the value of it. Thus it makes our data protected.
Example :
public class Customer
{
public string customerName,
privateint _age;
publicint Age
{
get
{
Return _age;
}
set
{
If(_age>0 && _age<100)
{
_age=Value;
}
else
{
throw new Exception(“Invalid data”);
}
}
}
}
.
.
Customer c=new Customer();
c.customerName=”Sukesh Marla”;
intTempAge=int.parse(TxtAge.Text);
if(c.IsValidAge(TempAge))
{
c.Age=TempAge;
}
Hope you enjoyed reading this article.
Also watch our 6 important
SQL Server interview questions with answer videos