2008-10-22 68 views
1

這裏是我的功能(更新):改進VB.NET URL縮短器的建議?

Public Shared Function shortenUrl(ByVal URL As String) As String 
    Return shortenUrl(URL, 32) 
End Function 
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String 
    If URL.Length > maxLength Then 
     String.Format("{0}...{1}", URL.Substring(0, (maxLength/2)), URL.Substring(URL.Length - ((maxLength/2) - 3))) 
    Else 
     Return URL 
    End If 
End Function 

我固定它沒有返回maxLength字符,因爲它沒有考慮到橢圓的問題。


在我看來,它太複雜了;任何建議,意見,關注都是值得歡迎的。

回答

1

爲什麼不這樣做?

Public Shared Function shortenUrl(ByVal URL As String) As String 
    Return shortenUrl(URL, 29) 
End Function 
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String 
    If URL.Length > maxLength Then 
     Return String.Format("{0}...{1}", URL.Substring(0, maxLength/2),URL.Substring(URL.Length - (maxLength/2))) 
    Else 
     Return URL 
    End If 
End Function 

至少擺脫所有tempoary聲明

+0

這就是爲什麼它似乎過於複雜,謝謝! 我把它歸咎於大腦疲勞! – Anders 2008-10-22 20:38:27

+0

它發生了!特別是在一段時間內完成一個項目之後! – 2008-10-22 20:41:41

0
Public Shared Function shortenUrl(ByVal URL As String, Optional ByVal maxLength As Integer = 29) As String 
    If URL.Length > maxLength Then  
     Return String.Format("{0}...{1}", URL.Substring(0, maxLength/2), URL.Substring(URL.Length - (maxLength/2))) 
    Else 
     Return URL 
    End If 
End Function 

的不知道爲什麼人們討厭可選參數這麼多。他們完全相同的事情暴露給用戶什麼值將默認,如果他們不提供一個。

1

嗯,我不知道它是否太複雜......但它是錯誤的。如果我打電話給shortenUrl(URL,29),我希望返回的最大長度爲29個字符。你的代碼會給我31.如果我用30的長度來調用它,我會得到33個字符。您不包括插入的「...」,並且您依靠四捨五入來獲取子字符串長度並刪除剩餘部分。

我想補充一些PARAM驗證,並將其更改爲:

Public Function shortenUrl2(ByVal URL As String, ByVal maxLength As Integer) As String 
    Const middle as String = "..." 
    If maxLength < 0 Then 
     Throw New ArgumentOutOfRangeException("maxLength", "must be greater than or equal to 0") 
    ElseIf String.IsNullOrEmpty(URL) OrElse URL.Length <= maxLength Then 
     Return URL 
    ElseIf maxLength < middle.Length Then 
     Return URL.Substring(0, maxLength) 
    End If 

    Dim left as String = URL.Substring(0, CType(Math.Floor(maxLength/2), Integer)) 
    Dim right as String = URL.Substring(URL.Length - (maxLength - left.Length - middle.Length)) 

    Return left & middle & right 
End Function