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”;
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
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值