Let's talk OOP Again
Let’s talk OOP again
You will encounter same problem, no matter what kind of software products you design or develop:
how to design “User Object”?
I usually design “User Object” like this (The following is a simple example):
I think most of us design “User Object” like this.
En , looked as if there is no problems , Moreover ,it had became some people's habit
We do like design “Add method” like “Add(xxx,xxx,xxx,xxx,xxx,xxx)”
But, when I review some base OOP knowledge recently; I found there is something wrong.
So, I change my old design(The following is sample example too):
If you can see I mind? Why “Example1” change to “Example2”?
Two important changes at there:
1, I use “Property” replace “public variable”;
publicvirtualstringUserName
...{
get...{return_userName;}
set
...{
if(_userName!=value)
...{
if(value.Length>16||value.Length<4)
...{
thrownewException("youcaninput4-16characterstoUserIDonly");
}
if(...)
...{
thrownewException("......")
}
if(...)
...{
thrownewException("......")
}
_userName=value;
}
}
}
...{
get...{return_userName;}
set
...{
if(_userName!=value)
...{
if(value.Length>16||value.Length<4)
...{
thrownewException("youcaninput4-16characterstoUserIDonly");
}
if(...)
...{
thrownewException("......")
}
if(...)
...{
thrownewException("......")
}
_userName=value;
}
}
}
2, I use “Add (User xxx)” replace “Add (XXX,XXX,XXX)”;
Do you know why?
First, Use Property can get more control, the following code will show it:
You can code like this:
UserobjUser=newUser();
UsersobjUser=newUsers();
User.userName=TxtUserName.Text.Trim();
User.Password=TxtPassword.Text;
objUser.Add(objUser);
UsersobjUser=newUsers();
User.userName=TxtUserName.Text.Trim();
User.Password=TxtPassword.Text;
objUser.Add(objUser);
Attention, if username is too long or short, “User Object” will throw a Exception, we can catch this exception.
If you use old design,your code maybe like this:
UserobjUser=newUser();
StringstrUserName=TxtUserName.Text.Trim();
StringstrPassword=TxtPassword.Text;
If(strUserName>16||strUserName<4)
...{
……
}
objUser.Add(strUserName,strPassword);
StringstrUserName=TxtUserName.Text.Trim();
StringstrPassword=TxtPassword.Text;
If(strUserName>16||strUserName<4)
...{
……
}
objUser.Add(strUserName,strPassword);
Which one more easy ?
Second, Like those method:”add”, “update” etc, use Object as parameter better than variable, It is more easy. You can see it from above code.
Third, it is most important thing: “Add”, "Update” methods not belong to “User Object”, they should belong to “Users Object” or belong to “Dept Object”
I don’t know if you can understand the third. but you should try do it.
In this world, much thing we don’t know, but if when we try, we will get it