2. С чего все началось?
• Интервью с Бертраном Мейером (http://bit.ly/IntervewWithMeyer)
• Борьба с «нулевыми» ссылками в C# (http://bit.ly/VoidSafetyCSharp)
3.
4. Ошибка на миллиард долларов
«Я называю это своей ошибкой на миллиард долларов. Речь идет о
изобретении нулевых ссылок (null reference) в 1965 году.»
http://bit.ly/BillionDollarMistake
5.
6.
7. [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;
}
8.
9. Void-Safety. Подходы
• ОО-подходы
• Not-nullable reference types: Eiffel, Swift (*), Spec#, C++ (**)
• Contracts
• ФП-подходы
• Maybe<T>
• Отсутствие литерала null (***)
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 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/
15. Как функциональные программисты заменяют лампочки?
Они не заменяют лампочки, а покупают новую розетку,
новую электропроводку и новую лампочку.
Бертран Мейер
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. Оптимизация на 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
21. Так какую проблему мы решаем?
• Void Safety vs. Control Flow simplification
• Как выразить non-nullable с помощью Monad?
22. 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();
}
}