DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Function composition in C#

Denzel D. user avatar by
Denzel D.
·
Nov. 16, 10 · Interview
Like (0)
Save
Tweet
Share
7.68K Views

Join the DZone community and get the full member experience.

Join For Free

When building complex applications, a certain level of abstraction becomes a necessity. Developers try to make their application as flexible as possible with minimal effort applied to do this by generalizing their code to be built on top of a common reusable structure rather than be made of hard-coded parts.

This also applies to functions that are used across an application. In many cases, the result of a function is returned directly as a parameter to another function. Let’s look at a specific example.

I have a method that generates a MD5 hash based on the string that is passed to it:

public static string GetMD5Hash(string password)
{
byte[] data;
data = Encoding.ASCII.GetBytes(password);
MD5CryptoServiceProvider crypto = new MD5CryptoServiceProvider();
crypto.ComputeHash(data);
data = crypto.Hash;
string c = BitConverter.ToString(data);
return c;
}

The only problem with the returned string is the fact that it contains dashes and is in upper case – but there is a method that can fix that.

public static string RemoveDash (string source)
{
return source.Replace("-", string.Empty).ToLower();
}

In a regular case scenario, you could use something like this:

Console.WriteLine(RemoveDash(GetMD5Hash("YourTextHere")));

Once GetMD5Hash will have a string to return, it will be passed to RemoveDash. But there is one problem with the approach I am using here – the call itself is not flexible.

.NET Framework 3.5 came out with a new type of delegate: Func<T, TResult>, that allows you to encapsulate a method call that will follow the structure defined by the delegate. That way, as you can see the delegate itself doesn’t specify what data it should get – there are no explicit type declarations. Instead, a generic type parameter is used.

In my case, I can use Func this way:

public static Func<T, V> GetData<T,U,V>(Func<T,U> firstFunction, Func<U,V> secondFunction)
{
return n => secondFunction(firstFunction(n));
}

This will combine two other functions passed as parameters into one single call. It is important to mention that these functions can’t be any functions but rather those that abide the structure defined in the delegate.

Initially, I have Func<T,V> - it will be a function that accepts a parameter of type T and will return a result of type V. GetData itself is a function that operates with three types – the same T and V, plus the U and here is why. When the first function is called, the source parameter of type T is passed to it and the result of type U is returned. Then, that result of type U is passed to the second function as a parameter and the returned result of type V is passed to the source function – that will eventually pass that result to the part of the program that invoked it.

Eventually I am taking n, that represents the passed parameter of type T and I am implementing the same nested pattern for function invoking as I did in this article before I started using Func<T,TResult>. However, with the help of Func<T, TResult> I can use the same delegate for a wide variety of other functions that are manipulating data of other types, not only string - now that could be really efficient when it comes to code flexibility and re-use.

In the application itself, I am calling GetData this way:

var result = GetData<string,string,string>(GetMD5Hash, RemoveDash)("YourTextHere");

The returned result type is automatically inferred from the pattern used in GetData - in my case this will be System.String.

Note that although I am using one parameter here, when I am using Func, I can pass as many as 16 parameters to the delegate, so for most of the cases this is more than enough. 

Function composition (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Host Hack Attempt Detection Using ELK
  • Integrate AWS Secrets Manager in Spring Boot Application
  • How To Best Use Java Records as DTOs in Spring Boot 3
  • Java REST API Frameworks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: