Last active
August 29, 2015 14:26
-
-
Save AlexeyRaga/061ba7f4a3f0c3d79a3e to your computer and use it in GitHub Desktop.
C# with types and options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //This is a weak point of C#: declaring classes is verbose. | |
| //But it can be improved with C# 6 new syntax. | |
| public class Age { | |
| public int Value { get; private set; } | |
| //Age is correct by construction, | |
| //so if you have an Age then it is correct _by definition_ and you don't need to check anymore. | |
| public Age(int value) { | |
| if (!IsValidAge(value) throw new InvalidArgumentException("Age must be between 0 and 100"); | |
| Value = value; | |
| } | |
| //A way to convert incorrect value to Age, but to Optional age! | |
| public static Option<Age> fromInt(int value) { | |
| if (IsValidAge(value)) return value.Some() else return value.None(); | |
| } | |
| private static bool IsValidAge(int age) { return (value > 0 && value < 100); } | |
| } | |
| public static class Main { | |
| //Asking user for his age and trying to convert it to Option | |
| //Return Some(age) if the age is correct, or None if it was not correct. | |
| public static Option<Age> AskUsersAge() { | |
| Age.fromInt(int.Parse(Console.Readline())); | |
| } | |
| //Note that this method normally get's Age and not Option<Age>, | |
| //and it doesn't need to check anyting because Age is correct by construction. | |
| public static void CalculateBio(Age age) { | |
| if (age.Value < 20) return "You are young"; | |
| else if (age.Value < 50) return "You are mid age"; | |
| else return "You are going do die soon"; | |
| } | |
| public static void Main(string[] args) { | |
| AskUserForAge() | |
| .Filter(x => f > 5) //we're not goint to print anything to babies 'cause they can't read. | |
| .Select(x => CalculateBio(x)) //call a function that takes "age" we have within the container if we have it | |
| .Do(x => Console.PrintLine(x)); //print the result if there is a result. | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment