HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Stack data structure implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationdatastructurestack

Problem

I have implemented in C# a stack data structure, without using any existing C#/.NET containers (data structures). I have used TDD technique to implement this requirements, so you can find tests, too. All my tests are passing, so I guess stack is behaving correctly.

I would be very pleased to have a code review for this implementation.

Please do not recommend a generic implementation :-)

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StackDataStructure;

namespace StackTesting
{
    [TestClass]
    public class Tests
    {
        [TestMethod]
        public void TestEmptyStackSize()
        {
            var stack = new Stack();
            Assert.IsTrue(stack.IsEmpty());
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void EmptyStackPopException()
        {
            var stack = new Stack();
            stack.Pop();
        }

        [TestMethod]
        public void PushingAndPoppintItemsToStack()
        {
            var stack = new Stack();
            stack.Push(1);
            Assert.AreEqual(1, stack.Size);
            stack.Push(2);
            Assert.AreEqual(2, stack.Size);
            Assert.AreEqual(2, stack.Pop());
            Assert.AreEqual(1, stack.Size);
            Assert.AreEqual(1, stack.Pop());
            Assert.IsTrue(stack.IsEmpty());
            Assert.IsTrue(stack.Size == 0);
            stack.Push(10);
            Assert.IsTrue(stack.Size == 1);
            Assert.IsTrue(10 == stack.Pop());
            Assert.IsTrue(stack.IsEmpty());
        }
    }
}


```
using System;

namespace StackDataStructure
{
internal class Node
{
internal int value;
internal Node underTop;
}

public class Stack
{
private int size;
private Node top;

public int Size { get { return size; } }

public bool IsEmpty()
{
return top == null;
}

public int Pop()

Solution

The code and the test look very good. I only found these nit-picks:

  • There's a typo in the method name Poppint.



  • The test sometimes uses Assert.IsTrue(a == b), which should be Assert.IsEqual(a, b).



  • The name underTop does not sound perfect to me, since it refers to a top, which is meaningless for a single node. A single node doesn't have a top, therefore I would call it next or below.



  • The property Size should be renamed to Count to align with the other collection types.



  • I prefer to have the same namespace for the main code and the testing code. But I don't know the official convention for organizing tests.

Context

StackExchange Code Review Q#158823, answer score: 9

Revisions (0)

No revisions yet.