public static void PositionShip(IArrayBoardObject board, IShip battleship, Position battleshipPosition, Orientation battleshipOrientation) { // collate positional information Position shipEndPosition = battleship.CalculateEndPosition(battleshipPosition, battleshipOrientation); // traverse in reverse order, to immediately throw an exception if the ship is not entirely on the board List <ILocation> shipLocations = new List <ILocation>(); List <ILocation> occupiedLocations = new List <ILocation>(); try { for (int r = shipEndPosition.RowIndex; r >= battleshipPosition.RowIndex; r--) { for (int c = shipEndPosition.ColumnIndex; c >= battleshipPosition.ColumnIndex; c--) { ILocation foundLocation = GetLocationOnArrayBoard.GetLocation(board, new Position(r, c)); shipLocations.Add(foundLocation); if (foundLocation.IsOccupied()) { occupiedLocations.Add(foundLocation); } } } } catch (LocationOffBoardException ex) { throw new ShipPlacedOffBoardException("Ship is not entirely on the board.", ex); } // if any of the Locations are already occupied, we cannot place the ship on the board if (occupiedLocations.Count > 0) { ThrowOverlappingShipException(occupiedLocations); } // occupy each of the Locations where the ship belongs foreach (ILocation locations in shipLocations) { locations.Occupy(battleship); } }