Improve change item status method, you can replace but not remove just a single word from the status

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

The current Method

The current method for changing the status is this:

        private static void ChangeStatusOfItem(List<Item> items, int indexOfItem, string newStatus)
        {
            Item thisItem = items[indexOfItem];
            thisItem.Status = newStatus;
            items[indexOfItem] = thisItem;
        }

This will work for changing the status of a door from locked to unlocked, however many of the items have multiple words in the status. For example the Flask has a status of "gettable, container, small", and we would like to record if the container was empty or full. So we would need to check for the word empty in the status, and replace it with the word full.

A new Method

You can have two methods called the same thing as long as they take different parameters. So leaving the current method add the following:

        private static void ChangeStatusOfItem(List<Item> items, int indexOfItem, string oldStatus, string newStatus)
        {
            string thisItemStatus = items[indexOfItem].Status;
            if(thisItemStatus.Contains(oldStatus))
            {
                int pos = thisItemStatus.IndexOf(oldStatus);
                thisItemStatus = thisItemStatus.Remove(pos, oldStatus.Length);
                thisItemStatus = thisItemStatus.Insert(pos, newStatus);
            }

            items[indexOfItem].Status = thisItemStatus;
        }

The method accepts both the oldStatus to change and the newStatus to replace it. The method firstly gets the full status of the current item. It then checks to see if the entire status contains the oldStatus, if it does it finds the position within the entire status. It then removes the oldStatus from the entire status, and then inserts the newStatus.