FP vs. OOP
InVoid-Safety Context
@STeplyakov & @AntyaDev
С чего все началось?
• Интервью с Бертраном Мейером (http://bit.ly/IntervewWithMeyer)
• Борьба с «нулевыми» ссылками в C# (http://bit.ly/VoidSafetyCSharp)
Ошибка на миллиард долларов
«Я называю это своей ошибкой на миллиард долларов. Речь идет о
изобретении нулевых ссылок (null reference) в 1965 году.»
http://bit.ly/BillionDollarMistake
[CanBeNull]
public static IClrTypeName GetCallSiteTypeNaive(IInvocationExpression invocationExpression)
{
Contract.Requires(invocationExpression != null);
if (invocationExpression.InvokedExpression != null)
{
var referenceExpression = invocationExpression.InvokedExpression as IReferenceExpression;
if (referenceExpression != null)
{
var resolved = referenceExpression.Reference.Resolve();
if (resolved.DeclaredElement != null)
{
var declared = resolved.DeclaredElement as IClrDeclaredElement;
if (declared != null)
{
var containingType = declared.GetContainingType();
if (containingType != null)
{
return containingType.GetClrName();
}
}
}
}
}
return null;
}
Void-Safety. Подходы
• ОО-подходы
• Not-nullable reference types: Eiffel, Swift (*), Spec#, C++ (**)
• Contracts
• ФП-подходы
• Maybe<T>
• Отсутствие литерала null (***)
Void-Safety в C#
• Not-nullable reference types in C# (*)
• null-propagating operator (C# 6.0)
• Code Contracts
• Explicit Maybe types
• Implicit maybe type + extension methods
http://bit.ly/VoidSafetyCSharp
Not-nullable reference types
// Где-то в идеальном мире
// s – not-nullable переменная
public void Foo(string s)
{
// Никакие проверки, контркты, атрибуты не нужны
Console.WriteLine(s.Length);
}
// str – nullable (detached) переменная.
//string! аналогичен типу Option<string>
public void Boo(string! str)
{
// Ошибка компиляции!
// Нельзя обращаться к членам "detached" строки!
// Console.WriteLine(str.Length);
str.IfAttached((string s) => Console.WriteLine(s));
// Или
if (str != null)
Console.WriteLine(str.Length);
}
public void Doo(string! str)
{
Contract.Requires(str != null);
// Наличие предусловия позволяет безопасным образом
// обращаться к объекте string через ссылку str!
Console.WriteLine(str.Length);
}
No non-nullable reference types in C# 
In theory, theory and practice are the same, but in practice, they’re
different.This is no exception.There are many pragmatic objections to
adding non-nullable reference types now.
Eric Lippert
http://blog.coverity.com/2013/11/20/c-non-nullable-reference-types/
Альтернатива по Липперту?
Code Contracts!
Let the fight begin
Как функциональные программисты заменяют лампочки?
Они не заменяют лампочки, а покупают новую розетку,
новую электропроводку и новую лампочку.
Бертран Мейер
NoException?!
Let’s review this: http://ericlippert.com/2013/03/21/monads-part-nine/
А что Эрик думает по этому поводу?
[1.This technique can be dangerous, in that it can delay the production of an
exception until long after the exception handlers designed to deal with it are
no longer on the stack.Worse, it can delay the production of an exception
indefinitely, leading to programs that should have crashed continuing to
corrupt user data. Use with extreme caution.]
http://ericlippert.com/2013/03/21/monads-part-nine/
В чем проблема с Maybe<T>?
• Оптимизация на corner case
• Lack of DogFooding!
• Какую проблему мы решаем?
• Void-safety или упрощение control flow?
• Дополнительные затраты на обучение
• Отсутствие паттерн-матчинга
• Подход не универсален! (*)
• Чем не подходит implicit monads + CanBeNull/Postconditions?
Оптимизация на corner case-е!
• Источники:
• “Declaring and Checking Non-nullTypes” by Manuel Fahndrich, K. Rustan M. Leino,
Microsoft Research
• “Avoid aVoid:The eradication of null dereferencing” by Bertrand Meyer et al
Так какую проблему мы решаем?
• Void Safety vs. Control Flow simplification
• Как выразить non-nullable с помощью Monad?
public static class MaybeExtensions
{
public static A Match<T, A>(this Maybe<T> maybe, Func<A> none, Func<T, A> some)
{
return maybe == null || maybe.IsNone ? none() : some(maybe.Value);
}
public static Maybe<A> Bind<T, A>(this Maybe<T> maybe, Func<T, A> func)
{
return func == null || maybe == null || maybe.IsNone
? new Maybe<A>()
: func(maybe.Value).ToMaybe();
}
}
Семантика NRE?
I don't need Maybe,
I need non-nullable reference
types!
Мой подход?
Code Contracts + Annotations + Extension methods for reference types!
(+ R# plugin - https://resharper-
plugins.jetbrains.com/packages/ReSharper.ContractExtensions/)
Контракты? Нет, не слышали!
• Assert-ы на стероидах!
• Выражают смысл (семантику) кода
• Выразительность, бла, бла, бла…
• Pet Project: https://github.com/SergeyTeplyakov/ReSharperContractExtensions
var contractFunction = GetContractFunction();
if (contractFunction == null)
{
AddContractClass();
contractFunction = GetContractFunction();
Contract.Assert(contractFunction != null);
}
AddRequiresTo(contractFunction);
...
[CanBeNull, System.Diagnostics.Contracts.Pure]
private ICSharpFunctionDeclaration GetContractFunction()
{
return _availability.SelectedFunction.GetContractFunction();
}
Maybe + Contracts?
[CanBeNull]
public static IClrTypeName GetCallSiteTypeNaive(IInvocationExpression invocationExpression)
{
Contract.Requires(invocationExpression != null);
if (invocationExpression.InvokedExpression != null)
{
var referenceExpression = invocationExpression.InvokedExpression as IReferenceExpression;
if (referenceExpression != null)
{
var resolved = referenceExpression.Reference.Resolve();
if (resolved.DeclaredElement != null)
{
var declared = resolved.DeclaredElement as IClrDeclaredElement;
if (declared != null)
{
var containingType = declared.GetContainingType();
if (containingType != null)
{
return containingType.GetClrName();
}
}
}
}
}
return null;
}
Implicit monads
[CanBeNull]
public static IClrTypeName GetCallSiteType(this IInvocationExpression invocationExpression)
{
Contract.Requires(invocationExpression != null);
var type = invocationExpression
.With(x => x.InvokedExpression)
.With(x => x as IReferenceExpression)
.With(x => x.Reference)
.With(x => x.Resolve())
.With(x => x.DeclaredElement)
.With(x => x as IClrDeclaredElement)
.With(x => x.GetContainingType())
.Return(x => x.GetClrName());
return type;
}
Caveats!
var hashCode = invocationExpression
.With(x => x.InvokedExpression)
.With(x => x as IReferenceExpression)
.With(x => x.Reference)
.With(x => x.Resolve())
.With(x => x.GetHashCode());
var hashCode = invocationExpression
.With(x => x.InvokedExpression)
.With(x => x as IReferenceExpression)
.With(x => x.Reference)
.With(x => x.Resolve())
.ReturnStruct(x => x.GetHashCode());
Compile-time error!
hachCode – это int?
Null-propagating operator ?. (C# 6.0)
https://roslyn.codeplex.com/discussions/540883
Void safety on Kiev ALT.NET

Void safety on Kiev ALT.NET

  • 1.
    FP vs. OOP InVoid-SafetyContext @STeplyakov & @AntyaDev
  • 2.
    С чего всеначалось? • Интервью с Бертраном Мейером (http://bit.ly/IntervewWithMeyer) • Борьба с «нулевыми» ссылками в C# (http://bit.ly/VoidSafetyCSharp)
  • 4.
    Ошибка на миллиарддолларов «Я называю это своей ошибкой на миллиард долларов. Речь идет о изобретении нулевых ссылок (null reference) в 1965 году.» http://bit.ly/BillionDollarMistake
  • 7.
    [CanBeNull] public static IClrTypeNameGetCallSiteTypeNaive(IInvocationExpression invocationExpression) { Contract.Requires(invocationExpression != null); if (invocationExpression.InvokedExpression != null) { var referenceExpression = invocationExpression.InvokedExpression as IReferenceExpression; if (referenceExpression != null) { var resolved = referenceExpression.Reference.Resolve(); if (resolved.DeclaredElement != null) { var declared = resolved.DeclaredElement as IClrDeclaredElement; if (declared != null) { var containingType = declared.GetContainingType(); if (containingType != null) { return containingType.GetClrName(); } } } } } return null; }
  • 9.
    Void-Safety. Подходы • ОО-подходы •Not-nullable reference types: Eiffel, Swift (*), Spec#, C++ (**) • Contracts • ФП-подходы • Maybe<T> • Отсутствие литерала null (***)
  • 10.
    Void-Safety в C# •Not-nullable reference types in C# (*) • null-propagating operator (C# 6.0) • Code Contracts • Explicit Maybe types • Implicit maybe type + extension methods http://bit.ly/VoidSafetyCSharp
  • 11.
    Not-nullable reference types //Где-то в идеальном мире // s – not-nullable переменная public void Foo(string s) { // Никакие проверки, контркты, атрибуты не нужны Console.WriteLine(s.Length); } // str – nullable (detached) переменная. //string! аналогичен типу Option<string> public void Boo(string! str) { // Ошибка компиляции! // Нельзя обращаться к членам "detached" строки! // Console.WriteLine(str.Length); str.IfAttached((string s) => Console.WriteLine(s)); // Или if (str != null) Console.WriteLine(str.Length); } public void Doo(string! str) { Contract.Requires(str != null); // Наличие предусловия позволяет безопасным образом // обращаться к объекте string через ссылку str! Console.WriteLine(str.Length); }
  • 12.
    No non-nullable referencetypes in C#  In theory, theory and practice are the same, but in practice, they’re different.This is no exception.There are many pragmatic objections to adding non-nullable reference types now. Eric Lippert http://blog.coverity.com/2013/11/20/c-non-nullable-reference-types/
  • 13.
  • 14.
  • 15.
    Как функциональные программистызаменяют лампочки? Они не заменяют лампочки, а покупают новую розетку, новую электропроводку и новую лампочку. Бертран Мейер
  • 16.
    NoException?! Let’s review this:http://ericlippert.com/2013/03/21/monads-part-nine/
  • 18.
    А что Эрикдумает по этому поводу? [1.This technique can be dangerous, in that it can delay the production of an exception until long after the exception handlers designed to deal with it are no longer on the stack.Worse, it can delay the production of an exception indefinitely, leading to programs that should have crashed continuing to corrupt user data. Use with extreme caution.] http://ericlippert.com/2013/03/21/monads-part-nine/
  • 19.
    В чем проблемас Maybe<T>? • Оптимизация на corner case • Lack of DogFooding! • Какую проблему мы решаем? • Void-safety или упрощение control flow? • Дополнительные затраты на обучение • Отсутствие паттерн-матчинга • Подход не универсален! (*) • Чем не подходит implicit monads + CanBeNull/Postconditions?
  • 20.
    Оптимизация на cornercase-е! • Источники: • “Declaring and Checking Non-nullTypes” by Manuel Fahndrich, K. Rustan M. Leino, Microsoft Research • “Avoid aVoid:The eradication of null dereferencing” by Bertrand Meyer et al
  • 21.
    Так какую проблемумы решаем? • Void Safety vs. Control Flow simplification • Как выразить non-nullable с помощью Monad?
  • 22.
    public static classMaybeExtensions { public static A Match<T, A>(this Maybe<T> maybe, Func<A> none, Func<T, A> some) { return maybe == null || maybe.IsNone ? none() : some(maybe.Value); } public static Maybe<A> Bind<T, A>(this Maybe<T> maybe, Func<T, A> func) { return func == null || maybe == null || maybe.IsNone ? new Maybe<A>() : func(maybe.Value).ToMaybe(); } }
  • 23.
  • 24.
    I don't needMaybe, I need non-nullable reference types!
  • 25.
    Мой подход? Code Contracts+ Annotations + Extension methods for reference types! (+ R# plugin - https://resharper- plugins.jetbrains.com/packages/ReSharper.ContractExtensions/)
  • 26.
    Контракты? Нет, неслышали! • Assert-ы на стероидах! • Выражают смысл (семантику) кода • Выразительность, бла, бла, бла… • Pet Project: https://github.com/SergeyTeplyakov/ReSharperContractExtensions
  • 27.
    var contractFunction =GetContractFunction(); if (contractFunction == null) { AddContractClass(); contractFunction = GetContractFunction(); Contract.Assert(contractFunction != null); } AddRequiresTo(contractFunction); ... [CanBeNull, System.Diagnostics.Contracts.Pure] private ICSharpFunctionDeclaration GetContractFunction() { return _availability.SelectedFunction.GetContractFunction(); }
  • 29.
  • 30.
    [CanBeNull] public static IClrTypeNameGetCallSiteTypeNaive(IInvocationExpression invocationExpression) { Contract.Requires(invocationExpression != null); if (invocationExpression.InvokedExpression != null) { var referenceExpression = invocationExpression.InvokedExpression as IReferenceExpression; if (referenceExpression != null) { var resolved = referenceExpression.Reference.Resolve(); if (resolved.DeclaredElement != null) { var declared = resolved.DeclaredElement as IClrDeclaredElement; if (declared != null) { var containingType = declared.GetContainingType(); if (containingType != null) { return containingType.GetClrName(); } } } } } return null; }
  • 31.
    Implicit monads [CanBeNull] public staticIClrTypeName GetCallSiteType(this IInvocationExpression invocationExpression) { Contract.Requires(invocationExpression != null); var type = invocationExpression .With(x => x.InvokedExpression) .With(x => x as IReferenceExpression) .With(x => x.Reference) .With(x => x.Resolve()) .With(x => x.DeclaredElement) .With(x => x as IClrDeclaredElement) .With(x => x.GetContainingType()) .Return(x => x.GetClrName()); return type; }
  • 32.
    Caveats! var hashCode =invocationExpression .With(x => x.InvokedExpression) .With(x => x as IReferenceExpression) .With(x => x.Reference) .With(x => x.Resolve()) .With(x => x.GetHashCode()); var hashCode = invocationExpression .With(x => x.InvokedExpression) .With(x => x as IReferenceExpression) .With(x => x.Reference) .With(x => x.Resolve()) .ReturnStruct(x => x.GetHashCode()); Compile-time error! hachCode – это int?
  • 35.
    Null-propagating operator ?.(C# 6.0) https://roslyn.codeplex.com/discussions/540883

Editor's Notes

  • #20 (*) Подходит все же для control flow, но не для ловли багов!