Understanding the pure and impure functions with c# examples
2 min readAug 1, 2024
Pure functions
Pure function is that:
- Always returns the same output given the same inputs.
- Does not modify the state of object or any external state.
- 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
- 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
- Modifies the state of the object or any external state.
- Has side effects, such as I/O operation, db operations, throwing exceptions, writing to file,db or console etc.
- 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
Become a supporter ❣️
You can buy me a coffee 🍵