萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 函數與 Sub 程序:模組化程式設計、參數傳遞與重用最佳實踐

VBScript 程式模組化核心:Function 與 Sub 完整實務指南

將重複邏輯封裝為 Function(有回傳值)與 Sub(無回傳值)是構建可維護 ASP 應用的基石。本文深入解析宣告語法、參數傳遞機制、呼叫慣例、變數作用域與重構模式。

Sub 程序:動作封裝

<%
' 宣告
Sub SubName(param1, param2, ...)
    ' 陳述式
End Sub

' 呼叫兩種方式
Call SubName(arg1, arg2)  ' 有 Call 關鍵字,參數需括號
SubName arg1, arg2        ' 無 Call,參數不加括號

' 實戰範例:記錄系統日誌
Sub LogEvent(eventType, message, userId)
    Dim conn, sql
    Set conn = GetConnection()
    sql = "INSERT INTO SysLog (EventType, Message, UserID, LogTime) VALUES (?, ?, ?, Now())"
    ExecuteNonQuery sql, Array(eventType, message, userId)
    ' 這裡假設 ExecuteNonQuery 為前文定義的封裝函數
End Sub

' 使用
Call LogEvent("LOGIN", "用戶登入", Session("UserID"))
LogEvent "LOGOUT", "用戶登出", Session("UserID")
%>

Function 函數:計算與回傳值

<%
' 宣告:函數名賦值即為回傳值
Function FunctionName(param1, param2, ...)
    ' 計算邏輯
    FunctionName = resultValue  ' 關鍵:將結果賦值給函數名
End Function

' 實戰範例:計算圓面積
Function CircleArea(radius)
    If radius < 0 Then
        CircleArea = -1  ' 錯誤代碼
        Exit Function
    End If
    CircleArea = 3.14159265359 * radius * radius
End Function

' 使用
Dim area : area = CircleArea(5)
Response.Write "面積:" & area  ' 78.5398...

' 進階:多重返回點
Function SafeDivide(dividend, divisor)
    If divisor = 0 Then
        SafeDivide = Null  ' 或 Err.Raise
        Exit Function
    End If
    SafeDivide = dividend / divisor
End Function
%>

參數傳遞機制:ByRef vs ByVal

關鍵字行為預設適用場景
ByRef傳址:程序內修改影響外部變數是需修改引數、大型物件避免複製
ByVal傳值:複製數值,程序內修改不影響外部否輸入參數、基本型別、防止副作用
<%
Sub ModifyByRef(ByRef num)
    num = num * 2
End Sub

Function ModifyByVal(ByVal num)
    num = num * 2
    ModifyByVal = num
End Function

Dim x : x = 10
ModifyByRef x
Response.Write "ByRef 後 x = " & x & "
" ' 20 Dim y : y = 10 Dim z : z = ModifyByVal(y) Response.Write "ByVal 後 y = " & y & ", 回傳 z = " & z & "
" ' y=10, z=20 %>

參數陣列:ParamArray(VBScript 不直接支援,替代方案)

<%
' VBScript 無 ParamArray,使用陣列或 Dictionary 模擬
Function SumValues(values)
    Dim total, i
    total = 0
    If IsArray(values) Then
        For i = 0 To UBound(values)
            If IsNumeric(values(i)) Then total = total + values(i)
        Next
    End If
    SumValues = total
End Function

Response.Write SumValues(Array(1, 2, 3, 4, 5))  ' 15
Response.Write SumValues(Array(10, 20))        ' 30
%>

遞迴函數:階乘與樹狀結構

<%
' 階乘遞迴
Function Factorial(n)
    If n <= 1 Then
        Factorial = 1
    Else
        Factorial = n * Factorial(n - 1)
    End If
End Function

' 樹狀結構遞迴:產生分類路徑
Function GetCategoryPath(catId, separator)
    Dim sql, rs, parentId, parentPath
    sql = "SELECT ParentID FROM Categories WHERE CategoryID = ?"
    Set rs = ExecuteQuery(sql, Array(catId))
    
    If rs.EOF Or rs("ParentID") = 0 Then
        GetCategoryPath = GetCategoryName(catId)
    Else
        parentId = rs("ParentID")
        rs.Close
        parentPath = GetCategoryPath(parentId, separator)
        GetCategoryPath = parentPath & separator & GetCategoryName(catId)
    End If
    If IsObject(rs) Then rs.Close : Set rs = Nothing
End Function
%>

變數作用域規則

  • 模組層級:Dim/Public/Private 在 <% %> 外部或腳本開頭宣告,全腳本可見
  • 程序層級:在 Sub/Function 內宣告,僅該程序可見
  • 隱含宣告:未宣告直接賦值會建立模組層級變數(危險,請加 Option Explicit)
<%
Option Explicit  ' 強制變數宣告,放在最頂端

Dim moduleVar  ' 模組層級

Sub DemoScope()
    Dim localVar  ' 程序層級
    localVar = "區域"
    moduleVar = "模組層級被修改"
End Sub

DemoScope()
Response.Write moduleVar  ' 輸出:模組層級被修改
' Response.Write localVar  ' 錯誤:未宣告
%>

重構模式:從單體腳本到模組化架構

<%
' ===== utils.asp 共用函數庫 =====
Function HTMLEncodeSafe(str)
    If IsNull(str) Then HTMLEncodeSafe = "" : Exit Function
    HTMLEncodeSafe = Server.HTMLEncode(str)
End Function

Function FormatCurrency(amount)
    FormatCurrency = FormatNumber(amount, 2, True, False, True)
End Function

Function IsValidEmail(email)
    Dim regex : Set regex = New RegExp
    regex.Pattern = "^[\w\.-]+@[\w\.-]+\.\w{2,}$"
    regex.IgnoreCase = True
    IsValidEmail = regex.Test(email)
End Function

' ===== 業務邏輯層 =====
Function CreateUser(username, email, password)
    If Not IsValidEmail(email) Then
        CreateUser = "Email 格式錯誤"
        Exit Function
    End If
    ' ... 資料庫操作
    CreateUser = "success"
End Function

' ===== 頁面使用 =====
' <!--#include file="utils.asp"-->
Dim result : result = CreateUser("john", "john@example.com", "pwd123")
%>

最佳實務總結

  1. 單一職責:每個 Function/Sub 只做一件事
  2. 命名規範:動詞開頭 GetUser、CalculateTax、ValidateInput
  3. 參數預設值模擬:If IsMissing(param) Then param = default(VBScript 無 IsMissing,用 If IsEmpty(param) Or param = "" Then)
  4. 錯誤處理:函數回傳錯誤代碼/物件,或使用 Err.Raise 配合 On Error Resume Next
  5. 文件化:每個公開函數加上註解說明用途、參數、回傳值、副作用
copyright © 萬盛學電腦網 all rights reserved