什么是好的代码,好的代码不是简单的可以运行,而应该是简洁美观的,让人很容易就可以看懂的,所以我们在使用循环的时候应尽可能的减少循环的层数。
比较下面两段代码:
代码1:
If Trim(txtUserName.Text = "") Then MsgBox "没有这个用户,请重新输入!",vbOKOnly + vbExclamation,"警告" txtUserName.SetFocus Else txtsql = "select * from user_Info where user_ID= '" & txtUserName.Text & "'" Set mrc = Executesql(txtsql,MsgText) If mrc.EOF = True Then MsgBox "没有这个用户,请重新输入!","警告" txtUserName.SetFocus Else If Trim(mrc.Fields(1)) <> Trim(txtPassword.Text) Then MsgBox "密码错误,请重新输入!","警告" txtPassword.SetFocus txtPassword.Text = "" Else OK = True mrc.Close Me.Hide UserName = Trim(txtUserName.Text) End If End If End If
代码2:
If Trim(txtUserName.Text = "") Then MsgBox "请输入用户名!","警告" txtUserName.SetFocus Exit Sub End If txtsql = "select * from User_Info where userID= '" & txtUserName.Text & "'" Set mrc = Executesql(txtsql,MsgText) If mrc.EOF = True Then MsgBox "没有这个用户,请重新输入!","警告" txtUserName.SetFocus Exit Sub End If If Trim(mrc.Fields(1)) <> Trim(txtPassword.Text) Then MsgBox "密码错误,请重新输入!","警告" txtPassword.SetFocus txtPassword.Text = "" Exit Sub End If OK = True mrc.Close Me.Hide UserName = Trim(txtUserName.Text)代码1和代码2实现的是同样的功能,但是代码1中的if嵌套有三层,而代码2利用Exit Sub把这三层嵌套分成了三个独立的if语句,使得代码变得简单易懂。
初学者,不当之处敬请评指正!
欢迎光临我的网易博客:http://blog.163.com/liu_xiaochun/
原文链接:https://www.f2er.com/vb/258574.html