The Daily Parker

Politics, Weather, Photography, and the Dog

E is for Encapsulation

Blogging A to ZWelcome to day 5 of the Blogging A-to-Z challenge.

In object-oriented design, we talk about a number of basic concepts that make code easier for humans to read and maintain. Encapsulation is fundamental, by hiding the internal data of a class so that only the class can use it. To access data within the class, you can't just reach in and grab it; you need to use the public properties and methods of the class.

Here's a stupid class:

#region Copyright ©2018 Inner Drive Technology

using System;
using System.Collections.Generic;

#endregion

namespace InnerDrive.DailyParkerAtoZ.WeekOne
{
	public class Encapsulation
	{
		public string Name { get; private set; }

		public void ChangeName(string newName)
		{
			if (string.IsNullOrWhiteSpace(newName))
			{
				throw new ArgumentException("Name must have a value", nameof(newName));
			}
			Name = newName;
			_names.Add(newName);
		}

		internal void Clear()
		{
			Name = string.Empty;
		}

		public IEnumerable<string> NameList => new List<string>(_names);

		private readonly List<string> _names = new List<string>();
	}
}

Seriously, this is dumb. But it demonstrates some of the ways C# encapsulates data.

Line 12 creates a property called Name that any code anywhere can call, because it's public. But it also declares a setter method that is private, meaning only the Encapsulation class itself can set the value of Name.

Lines 14-22 show how this works. The ChangeName method first makes sure you are giving it a real value, then changes Name and adds the new name to a list of names that is itself private. So the only way to change Name is to use the ChangeName method. (There's another way to do this in the property setter, but I wanted to show how this works exactly.)

Lines 24-27 provide you a way of clearing Name, but the method is marked internal. That means only classes in the same assembly can use this method, which has consequences for our unit tests, below.

Line 29 does a nifty trick where, instead of actually giving outside code access to its private list of _names (line 31), it creates a copy of the list and sends that out. Otherwise, anyone would be able to change the contents of _names just by using the NameList property.

Now here's the unit test code:

#region Copyright ©2018 Inner Drive Technology

using System.Linq;
using InnerDrive.DailyParkerAtoZ.WeekOne;
using Microsoft.VisualStudio.TestTools.UnitTesting;

#endregion

namespace InnerDrive.DailyParkerAtoZ.UnitTests
{
	[TestClass]
	public class EncapsulationTests
	{
		[TestMethod]
		public void CanSetNameOfObject()
		{
			var thing = new Encapsulation();
			//thing.Name = "This won't compile";
			//thing._names.Add("This won't compile either");
			thing.ChangeName("Ernie");
			Assert.AreEqual("Ernie", thing.Name);
			Assert.AreEqual(1, thing.NameList.Count());
		}

		[TestMethod]
		public void CanClearNames()
		{
			var thing = new Encapsulation();
			thing.ChangeName("Ernie");
			Assert.AreEqual("Ernie", thing.Name);
			Assert.AreEqual(1, thing.NameList.Count());

			// thing.Clear(); // oops—won't compile!

			// Assertions fail!
			Assert.IsTrue(string.IsNullOrWhiteSpace(thing.Name));
			Assert.AreEqual(1, thing.NameList.Count());
		}
	}
}

The comments explain what's going on.

So how can we test the Encapsulation.Clear() method? By adding this line to the InnerDrive.DailyParkerAtoZ.WeekOne.AssemblyInfo.cs file:

[assembly: InternalsVisibleTo("InnerDrive.DailyParkerAtoZ.UnitTests")]

Now all of the objects, properties, and methods in the WeekOne assembly marked internal are visible to the unit test class, and the tests pass.

Cool, right?

As always, the growing Visual Studio solution is here. The ZIP file contains the complete Git log of the project, by the way. Enjoy.

Comments are closed