2013-04-15 19 views
5

Czysta metoda jest zdefiniowana jako "does not make any visible state changes".Czy metoda zapisująca do rejestratora jest czysta?

Moja metoda zapisuje komunikat dziennika, jeśli jeden argument ma wartość NULL lub zostanie zgłoszony wyjątek. Czy nadal jest czysty? Czy zapisywanie do rejestratora jest widoczną zmianą?

Oto kod:

/// <summary> 
    /// Formats with invariant culture - won't throw an exception. 
    /// </summary> 
    /// <param name="format">A composite format string.</param> 
    /// <param name="args">An object array that contains zero or more objects to format.</param> 
    /// <returns>A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.</returns> 
    [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "CyanCor.Core.Logging.Log.ExceptionPrevent(System.String,System.String,System.Int32,System.String)", Justification = "It is for the logger (riedl)")] 
    [Pure - yes or no?] 
    public static string FormatSafe(this string format, params object[] args) 
    { 
     if (format == null) 
     { 
      Log.ExceptionPrevent("Argument format is null"); 
      return NullFormat; 
     } 

     try 
     { 
      return string.Format(CultureInfo.InvariantCulture, format, args); 
     } 
     catch (ArgumentException exc) 
     { 
      Log.Exception(exc); 
      return format; 
     } 
     catch (FormatException exc) 
     { 
      Log.Exception(exc); 
      return format; 
     } 
    } 
+0

Dlaczego deklarować czystość? Czy chcesz to nazwać z umowy? –

+0

Cóż, możesz argumentować, że jest to czysta funkcja, która daje nieczystą funkcję. – sloth

Odpowiedz

5

Ogólnie, „zmiany stanu” oznacza modyfikację stan obiektu, tj. modyfikowanie zmiennej lub zmiana struktury złożonego obiektu. Zgodnie z tą definicją wydaje się, że twoja metoda jest wciąż czysta.

+1

Zgadzam się. Jest czysty. –

+0

Dziękuję za wyjaśnienia. – ldrdl

+0

Według tej definicji zmiana wartości w bazie danych może nadal być uważana za "czystą", co oczywiście jest błędne. – tster