Understanding the pure and impure functions with c# examples

Ravindra Devrani
2 min readAug 1, 2024

--

Pure functions

Pure function is that:

  1. Always returns the same output given the same inputs.
  2. Does not modify the state of object or any external state.
  3. Does not have any side effects such as I/O operations, exceptions or modifying external variables.
  • In other words, a pure function takes input, process it and returns the output without modifying anything else.
  • Pure functions are easy to test and debug.

Examples

  1. Mathematical calculations
public int Add(int a, int b)
{
return a + b;
}

2. String manipulation

public string Concatenate(string a, string b)
{
return a + b;
}

3. Array operations

public int[] SortArray(int[] array)
{
return array.OrderBy(x => x).ToArray();
}

4. Data transformations

public string ConvertToString(int value)
{
return value.ToString();
}

5. Validation

public bool IsValidEmail(string email)
{
return email.Contains("@");
}

Impure Functions

Impure function is that

  1. Modifies the state of the object or any external state.
  2. Has side effects, such as I/O operation, db operations, throwing exceptions, writing to file,db or console etc.
  3. May return different outputs given the same inputs, due to external factors.

Examples of impure functions

  • I/O operations
public void SaveFile(string data)
{
File.WriteAllText("data.txt", data);
}
  • Database operations
public void InsertUser(User user)
{
// database insert operation
}
  • Web service calls
public string GetWeatherData(string city)
{
// web service call
}
  • Modifying external collections
public void AddItem(List<string> list, string item)
{
list.Add(item);
}
public void ValidateInput(string input)
{
if (input == null)
{
throw new ArgumentNullException();
}
}
  • Sending an email
public void SendWelcomeEmail(User user)
{
// send email using SMTP or email service
}
  • Writing to a log file
public void LogError(Exception ex)
{
File.AppendAllText("error.log", ex.Message);
}
  • Printing to console
public void PrintReceipt(Order order)
{
Console.WriteLine("Receipt:");
Console.WriteLine(order.ToString());
}

One clap 👏, 1 share motivates me to write more. Please consider it if this post helped you.

Connect with me

👉 YouTube
👉 Twitter
👉 GitHub

Become a supporter ❣️

You can buy me a coffee 🍵

--

--

Ravindra Devrani
Ravindra Devrani

No responses yet