functional-csharp-code-2 icon indicating copy to clipboard operation
functional-csharp-code-2 copied to clipboard

Is DateNotPastValidator still considered pure function, although it has been revamped to become testable

Open hannah23280 opened this issue 1 year ago • 1 comments

Hi, in chapter 3, why function purity matters, under 3.4.2 Testability without so much boilerplat, under INJECTING FUNCTIONS AS DEPENDENCIES, the sample code below is one of the solution to ensure the validator function become testable. However, can i clarify that this function although become testable, it is still not considered pure function? Cos if i repeatedly call the same DateNotPastValidator function with the same Clock argument (which internally get the current date time), the DateNotPastValidator function might return different arguments, hence breaking one of the rule of pure function. Pure function which calls an impure function (in this case, the Clock function) is itself become impure.

public record DateNotPastValidator(Func<DataTime> Clock):IValidator<MakerTransfer>{
     public bool IsValid(MakerTransfer transfer)=>Clock().Date<= Transfer.Date.Date

}

Hence my query is

  1. Is my above understanding correct about it being impure?
  2. if my understanding is correct, is there a way to make it testable and at same time pure?

hannah23280 avatar Aug 17 '24 12:08 hannah23280

Hello, yes your understanding is correct: if a function calls an impure function, it is itself impure. The point, here, is to try to write a function that has no side effects other than those of the functions it depends upon. This makes it testable, by injecting a pure function.

On Sat, Aug 17, 2024 at 2:47 PM Hanster @.***> wrote:

Hi, in chapter 3, why function purity matters, under 3.4.2 Testability without so much boilerplat, under INJECTING FUNCTIONS AS DEPENDENCIES, the sample code below is one of the solution to ensure the validator function become testable. However, can i clarify that this function although become testable, it is still not considered pure function? Cos if i repeatedly call the same DateNotPastValidator function with the same Clock argument (which internally get the current date time), the DateNotPastValidator function might return different arguments, hence breaking one of the rule of pure function. Pure function which calls an impure function is itself become impure. Is my understanding correct?

public record DateNotPastValidator(Func<DataTime> Clock):IValidator<MakerTransfer>{ public bool IsValid(MakerTransfer transfer)=>Clock().Date<= Transfer.Date.Date

}

— Reply to this email directly, view it on GitHub https://github.com/la-yumba/functional-csharp-code-2/issues/15, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABUEO2C27GCWQIRPUHMUAADZR5A47AVCNFSM6AAAAABMVMUZW2VHI2DSMVQWIX3LMV43ASLTON2WKOZSGQ3TCNJRGIYTCMI . You are receiving this because you are subscribed to this thread.Message ID: @.***>

la-yumba avatar Aug 22 '24 14:08 la-yumba