2013-03-21

Power of Script Language



寫過幾種程式語言,雖然個人不偏好任何一種,但script不那麼嚴謹的特性,寫起來總是特別有種快感。script可以做到一些很特別的事,例如說code已經在runtime才決定自己要做什麼事情,以下用python作一個簡單示範。



開發原由:
dev一定會常常碰到需要把code用try catch封裝的函式,如果是一兩支還好,但如果碰到大量需要被"同樣行為"封裝的code,光copy&paste也會讓人丟了半條命。

callFuncWithExceptionCatch()說明:
參數1:class的function name
參數2:call back的function,就是想做try catch又懶得包的那段
參數3:將參數組成真正跑try catch的code

def callFuncWithExceptionCatch(funcName, returnVal, **params):
   
    # 1. New an instance of the class you want to call
    instance = targetClass()
   
    # 2. Write the script that was generated during runtime
    #    and use params to generate code 'exe'
    exe = 'instance.' + funcName + '('
    for p in params:
        exe += p + ','
    exe += ')'
   
    # 3. Real execute the script 'exe'
    try:
        exe
    except Exception, err:
        throw 'err serviceWithExceptionCatch:', err


    returnVal

懶得解釋了,反正會懂就是會懂...

沒有留言:

張貼留言