4. What is functional programming?
„In computer science, functional programming is
a programming paradigm—a style of building the structure and
elements of computer programs—that treats computation as
the evaluation of mathematical functions and avoids changing-
state and mutable data. It is a declarative
programming paradigm, which means programming is done
with expressions or declarations instead of statements.”
https://en.wikipedia.org/wiki/Functional_programming
5. Mathematical (pure) functions
„In mathematics, a function is a relation between a set of
inputs and a set of permissible outputs with the property
that each input is related to exactly one output.”
FunctionInput Output
https://en.wikipedia.org/wiki/Function_(mathematics)
11. public void SaveUser(string email, string name)
{
if(email == null)
throw new ArgumentNullException(”email”)
if(EmailValidator.IsValid(email))
throw new InvalidEmailException(email);
…
}
Not a mathematical function
Primitive Obsession
12. public void SaveUser(Email email, string name)
{
if(email == null)
throw new ArgumentNullException(”email”)
…
}
Not a mathematical function
13. public void SaveUser(Email email, string name)
{
if(email == null)
throw new ArgumentNullException(”email”)
…
} „My billion-dollar mistake” …
„simply because it was so
easy to implement”
Tony Hoare
https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/
14. public void SaveUser(
[NotNull] Email email,
[NotNull] string name)
{ ReSharper Code Annotations
Not a mathematical function
15. public Either<Unit, Error> SaveUser(
Email email,
string name)
{
…
return new Either<Error>(Error.AlreadyExists);
…
return new Either<Unit>();
}
≈void
20. var user = userRepository.Get(userId);
if (user?.Document != null)
{
var document = documentRepository.Get(user.Document.Id);
if (document?.LastModiferUser != null)
{
var lastModifier =
userRepository.Get(document.LastModiferUser.Id);
return lastModifier;
}
}
return null;
23. class Person
{
public string Name { get; }
public Person(string name) =>
Name = name ??
throw new ArgumentNullException(name);
public string GetLastName() =>
throw new NotImplementedException();
}
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
24. class Person
{
private static ConcurrentDictionary<int, string> names =
new ConcurrentDictionary<int, string>();
public Person(string name) => names.TryAdd(id, name);
~Person() => names.TryRemove(id, out *);
public string Name
{
get => names[id];
set => names[id] = value;
}
}
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
25. public static Task<int> PerformWorkAsync(int value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("…");
if (value > 100)
throw new ArgumentOutOfRangeException("…");
async Task<int> AsyncPart()
{
await Task.Delay(value * 500);
return value * 500;
}
return AsyncPart();
}
http://thebillwagner.com/Blog/Item/2016-03-02-C7FeatureProposalLocalFunctions
Local functions
26. Currying, partial application
Currying is the technique of translating the evaluation of a function that takes
multiple arguments into evaluating a sequence of functions, each with a single
argument.
public void Log(
string module,
string category,
Level level,
string message)
{
…
}
var logger =
LogMethod("web")("user");
logger(Level.High)("msg1");
logger(Level.Low)("msg2");
https://en.wikipedia.org/wiki/Currying
28. var curriedLog = Curry(log);
var logger = curriedLog("web")("user");
logger(Level.High)("msg1");
// curry vs partial application
partialLogger = ApplyPartial<string, string, Level, string>(
log, "web", "user");
partialLogger(Level.High, "msg1");
29. Func<T1, Func<T2, Func<T3, TResult>>> Curry<T1, T2, T3, TResult>
(Func<T1, T2, T3, TResult> function)
{
return a => b => c => function(a, b, c);
}
https://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application/
30. Tuples (and C# 7)
• When you want to return multiple values, and you don’t
want to create a class for that
Tuple<int, int> t1 = Tuple.Create<int, int>(1, 2);
int value = t1.Item1 + t1.Item2;
31. Tuples (and C# 7)
• When you want to return multiple values, and you don’t
want to create a class for that
private static (int Max, int Min) Range(List<int> numbers)
{
…
return (Max, Min)
}
33. Key takeaways
• Use pure functions wherever you can
• Write side-effect free code
• Prefer immutable structures over mutable
• Type signature as documentation
(avoid Primitive Obession)
• Learn functional programming
34. Start learning functional programming!
Contact me if you have any questions
peter.takacs@windowslive.com
https://www.linkedin.com/in/petertakacs1