Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created January 21, 2016 14:20
Show Gist options
  • Save DominicFinn/d5bd50393c034e31d8b2 to your computer and use it in GitHub Desktop.
Save DominicFinn/d5bd50393c034e31d8b2 to your computer and use it in GitHub Desktop.
Trying to stop a domain being abused
using System;
using ImmutableDomain.Commands;
using ImmutableDomain.Entities;
using ImmutableDomain.Help;
namespace ImmutableDomain.Other
{
public class CallingClass
{
private readonly IRepository repository;
public CallingClass(IRepository repository)
{
this.repository = repository;
}
public void DoSomething()
{
var command = new CreateEmployeeCommand(new Guid(), "Jim", "Smith");
// command.FirstName = ""; YAY we can't mess with it.
// we can't create this in the wrong assembly
// var employee = new Employee(new Guid(), "", "");
var employee = this.repository.Get<Employee>(Guid.Parse("F3E11CF0-89E6-44AD-B557-B32A0832D6E1"));
// we can't overwrite the name
// employee.FirstName = "";
// we need to use the IEditableEmployee to update the employee
// but it's internal so it must be used in the right assembly
//(employee as IEditableEmployee).Update("Jim", "Hoff");
}
}
}
using System;
using ImmutableDomain.Commands;
using ImmutableDomain.Entities;
using ImmutableDomain.Help;
namespace ImmutableDomain.Help
{
public interface ICommandHandler<T>
{
void Handle(T command);
}
public interface IRepository
{
void Save<T>(T entity);
T Get<T>(Guid id);
}
}
namespace ImmutableDomain.Commands
{
public sealed class CreateEmployeeCommand
{
public readonly Guid Id;
public readonly string FirstName;
public readonly string LastName;
public CreateEmployeeCommand(Guid id, string firstName, string lastName)
{
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
}
}
}
namespace ImmutableDomain.Entities
{
public sealed class Employee
{
public Guid Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
internal Employee(Guid id, string firstName, string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
}
internal interface IEditableEmployee
{
void Update(string firstName, string lastName);
}
}
namespace ImmutableDomain.CommandProcessors
{
internal sealed class CreateEmployeeCommandHandler : ICommandHandler<CreateEmployeeCommand>
{
private readonly IRepository repository;
internal CreateEmployeeCommandHandler(IRepository repository)
{
this.repository = repository;
}
public void Handle(CreateEmployeeCommand command)
{
var employee = new Employee(command.Id, command.FirstName, command.LastName);
this.repository.Save(employee);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment