Let's talk OOP Again

来源:互联网 发布:英文原著 知乎 编辑:程序博客网 时间:2024/06/06 03:40

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”;
public virtual string UserName
        
{
            
get return _userName; }
            
set
            
{
                
if (_userName != value)
                
{
                    
if (value.Length > 16||value.Length<4)
                    
{
                        
throw new Exception("you can input 4-16 characters to UserID only");
                    }

                    
if(...)
                    
{
                        
throw new Exception("... ...")
                    }

                    
if(...)
                    
{
                        
throw new Exception("... ...")
                    }

                    _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:
User objUser=new User();
Users objUser
=new Users();
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:
User objUser=new User();
String strUserName
= TxtUserName.Text.Trim();
String strPassword
=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
 
 
原创粉丝点击