Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/ByteDecoder.Common.Tests/Fakes/FileStorage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.IO;

namespace ByteDecoder.Common.Tests.Fakes;

/// <summary>
/// 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.
/// </summary>
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<string> Read(int id)
{
var path = this.GetFileName(id);
if (!File.Exists(path))
return new Maybe<string>();

var message = File.ReadAllText(path);
return new Maybe<string>(message);
}

public string GetFileName(int id) =>
Path.Combine(this.WorkingDirectory, id + ".txt");
}
42 changes: 42 additions & 0 deletions src/ByteDecoder.Common/Maybe.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Collections;

namespace ByteDecoder.Common;

/// <summary>
/// Alternative to Tester/Doer and TryRead idioms to handle outputs.
/// Internally holds 0 or 1 element.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Maybe<T> : IEnumerable<T>
{
private readonly IEnumerable<T> _values;

/// <summary>
///
/// </summary>
public Maybe()
{
_values = new T[0];
}

/// <summary>
///
/// </summary>
/// <param name="value"></param>
public Maybe(T value)
{
_values = new[] { value };
}

/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator() => _values.GetEnumerator();

/// <summary>
///
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}