diff --git a/src/ByteDecoder.Common.Tests/Fakes/FileStorage.cs b/src/ByteDecoder.Common.Tests/Fakes/FileStorage.cs new file mode 100644 index 0000000..3e584f8 --- /dev/null +++ b/src/ByteDecoder.Common.Tests/Fakes/FileStorage.cs @@ -0,0 +1,44 @@ +using System; +using System.IO; + +namespace ByteDecoder.Common.Tests.Fakes; + +/// +/// Example of usage: +/// var message = fileStorage.Read(49).DefaultIfEmpty("").Single(); +/// This fake is designed under CQS principle (Command Query Separation Principle), +/// Postel's Law, Fail Fast concept and Maybe idiom. +/// +internal class FileStorage +{ + public FileStorage(string workingDirectory) + { + if (workingDirectory is null) + throw new ArgumentNullException(nameof(workingDirectory)); + if (!Directory.Exists(workingDirectory)) + throw new ArgumentException("BOo", nameof(workingDirectory)); + + WorkingDirectory = workingDirectory; + } + + public string WorkingDirectory { get; } + + public void Save(int id, string message) + { + var path = this.GetFileName(id); + File.WriteAllText(path, message); + } + + public Maybe Read(int id) + { + var path = this.GetFileName(id); + if (!File.Exists(path)) + return new Maybe(); + + var message = File.ReadAllText(path); + return new Maybe(message); + } + + public string GetFileName(int id) => + Path.Combine(this.WorkingDirectory, id + ".txt"); +} diff --git a/src/ByteDecoder.Common/Maybe.cs b/src/ByteDecoder.Common/Maybe.cs new file mode 100644 index 0000000..0d739e5 --- /dev/null +++ b/src/ByteDecoder.Common/Maybe.cs @@ -0,0 +1,42 @@ +using System.Collections; + +namespace ByteDecoder.Common; + +/// +/// Alternative to Tester/Doer and TryRead idioms to handle outputs. +/// Internally holds 0 or 1 element. +/// +/// +public class Maybe : IEnumerable +{ + private readonly IEnumerable _values; + + /// + /// + /// + public Maybe() + { + _values = new T[0]; + } + + /// + /// + /// + /// + public Maybe(T value) + { + _values = new[] { value }; + } + + /// + /// + /// + /// + public IEnumerator GetEnumerator() => _values.GetEnumerator(); + + /// + /// + /// + /// + IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); +}