首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >库存编码采访练习

库存编码采访练习
EN

Code Review用户
提问于 2019-10-19 04:02:16
回答 1查看 765关注 0票数 7

在过去的一周里,我进行了一次编码面试,在面试中我失败了。我从招聘人员那里得到的反馈是,我的代码让团队想起了用C#编写代码的旧方法。这使他们相信,我对新版本的框架没有多少经验。

这让我非常困惑,因为我真的不知道我应该更改什么,这样我的代码看起来就更现代化了。

是关于表演吗?我的解决办法没有利用最佳做法吗?任何帮助都将不胜感激。

首先,这是一个问题。

至于订单文件,如下所示:

代码语言:javascript
复制
{
    "order-001": {
        "destination" : "YYZ"
    },
    "order-002": {
        "destination" : "YYZ"
    },
    "order-003": {
        "destination" : "YYZ"
    },
    "order-004": {
        "destination" : "YYZ"
    },
...
}

我没有为日程创建一个大的常量文件,而是决定从我使用上述场景填充的JSON文件中读取它们。

代码语言:javascript
复制
{
    "1": {
        "departure": "YUL",
        "arrival": "YYZ",
        "day": 1
    },
    "2": {
        "departure": "YUL",
        "arrival": "YYC",
        "day": 1
    },
    "3": {
        "departure": "YUL",
        "arrival": "YVR",
        "day": 1
    },
    "4": {
        "departure": "YUL",
        "arrival": "YYZ",
        "day": 2
    },
    "5": {
        "departure": "YUL",
        "arrival": "YYC",
        "day": 2
    },
    "6": {
        "departure": "YUL",
        "arrival": "YVR",
        "day": 2
    }
}

下面是我编写的代码,以便解决这个问题:

首先,我有一个名为Loader的类,它允许我将JSON文件的所有元素加载到对象中

Loader.cs

代码语言:javascript
复制
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Transport.ly
{
    public static class Loader
    {

        public static List<Order> LoadOrders()
        {

            List<Order> data;

            using (StreamReader r = new StreamReader(Constants.Path.JsonPath))
            {
                string json = r.ReadToEnd();
                data = JsonConvert.DeserializeObject<Dictionary<string, Order>>(json).Select(p => 
                new Order { Code = p.Key, Destination = p.Value.Destination, Priority = Int32.Parse( p.Key.Substring(p.Key.LastIndexOf('-') + 1))
            }).ToList();
            }

            return data;
        }

        public static Dictionary<int, Schedule> LoadScenarioSchedule()
        {

            Dictionary<int, Schedule> data;

            using (StreamReader r = new StreamReader(Constants.Path.ScenarioPath))
            {
                string json = r.ReadToEnd();
                data = JsonConvert.DeserializeObject<Dictionary<int, Schedule>>(json);
            }

            return data;
        }
    }
}

订单类

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Text;

namespace Transport.ly
{
    /// <summary>
    /// Represent an order
    /// </summary>
    public class Order
    {

        public Order()
        {
            _loaded = false;
        }

        public Order(string destination, string code, bool loaded, int priority)
        {
            _priority = priority;
            _loaded = loaded;
            _code = code;
            _destination = destination;
        }

        private string _destination;
        private string _code;
        private int _priority;
        private bool _loaded;

        public string Destination { get => _destination; set => _destination = value; }
        public string Code { get => _code; set => _code = value; }
        public bool Loaded { get => _loaded; set => _loaded = value; }
        public int Priority { get => _priority; set => _priority = value; }
    }
}

表示时间表的类

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Text;

namespace Transport.ly
{
    /// <summary>
    /// Represent a schedule
    /// </summary>
    public class Schedule
    {

        public Schedule()
        {
            _loaded = false;
        }

        public Schedule(int day, string departure, string arrival)
        {

            _day = day;
            _departure = departure;
            _arrival = arrival;
        }

        private int _day;
        private string _departure;
        private string _arrival;
        private bool _loaded;

        public bool Loaded { get => _loaded; set => _loaded = value; }
        public string Arrival { get => _arrival; set => _arrival = value; }
        public string Departure { get => _departure; set => _departure = value; }
        public int Day { get => _day; set => _day = value; }
    }
}

代表飞行的一类

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Text;

namespace Transport.ly
{
    /// <summary>
    /// This class represent a flight
    /// </summary>
    public class Flight
    {

        public Flight()
        {
            _orders = new List<Order>();
        }

        public Flight(int number, Schedule schedule, List<Order> orders)
        {
            _orders = orders;
            _schedule = schedule;
            _number = number;
        }

        private int _number;
        private Schedule _schedule;
        private List<Order> _orders;

        public List<Order> Orders { get => _orders; }
        public Schedule Schedule { get => _schedule; }
        public int Number { get => _number; }
    }
}

Inventory.cs

代码语言:javascript
复制
using System.Collections.Generic;
using System.Linq;

namespace Transport.ly
{
    public class Inventory
    {
        public Inventory() {

            _schedules = new Dictionary<int, Schedule>();
            _orders = new List<Order>();
            _flights = new List<Flight>();

        }

        public Inventory(string name, Dictionary<int, Schedule> schedules, List<Order> orders)
        {
            _name = name;
            _schedules = schedules;
            _orders = orders;

            _flights = new List<Flight>();
        }

        public void LoadSchedule( int key) {

            _schedules[key].Loaded = true;
        }

        /// <summary>
        /// this function returns schedules that are loaded 
        /// </summary>
        /// <returns></returns>
        public Dictionary<int ,Schedule> GetLoadedSchedules() {

            return _schedules.Where(s => s.Value.Loaded)
                        .ToDictionary(dict => dict.Key, dict => dict.Value);
        }

        /// <summary>
        /// this function returns schedules that are not loaded yet
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, Schedule> GetAvailableSchedules()
        {
            return _schedules.Where(s => s.Value.Loaded == false)
                        .ToDictionary(dict => dict.Key, dict => dict.Value);
        }

        public List<Order> GetOrders() {

            return _orders;
        }

        public Dictionary<int, Schedule> GetSchedules()
        {
            return _schedules;
        }

        /// <summary>
        /// Generate Flight itineraries and return what hasbeen generate.
        /// This function return only orders that are loaded. In other words,
        /// Orders that have scedule. associated to them.
        /// </summary>
        /// <returns></returns>
        public List<Flight> GenerateFlights() {

            var loadedSchedules = GetLoadedSchedules();

            List<Schedule> sortedSchedule = new List<Schedule>();

            sortedSchedule = loadedSchedules.Values.ToList();

            sortedSchedule.Sort((emp1, emp2) => emp1.Day.CompareTo(emp2.Day));

            int flightNumber = 1;


            List<Order> ordersByPriority = _orders.OrderBy(o => o.Priority).ToList();


            foreach (Schedule schedule in sortedSchedule)
            {
                //if the schedule is already assigned to a flight, no need to add it
                if (_flights.Any(item => item.Schedule.Day == schedule.Day &&
                item.Schedule.Arrival == schedule.Arrival && item.Schedule.Departure == schedule.Departure))
                {
                    flightNumber++;
                    continue;
                }

                List<Order> orders = new List<Order>();

                //get 20 orders that has the same destination
                for (int i = 0; i < ordersByPriority.Count; i++)
                {
                    //Check if the order has the same destination as the scedule and if the order is not
                    //already loaded on a previous flights
                    if (schedule.Arrival == ordersByPriority[i].Destination && !ordersByPriority[i].Loaded)
                    {
                        orders.Add(ordersByPriority[i]);

                        ordersByPriority[i].Loaded = true;


                        if (orders.Count == Constants.Rule.PlaneBoxCountLimit)
                        {
                            break;
                        }
                    }
                }


                _flights.Add(new Flight(flightNumber, schedule, orders));

                flightNumber++;
            }

            return _flights;
        }

        private string _name;
        private List<Order> _orders;
        private Dictionary<int, Schedule> _schedules;
        private List<Flight> _flights;
    }








}

包含srting常量的类。

代码语言:javascript
复制
using System.IO;



namespace Transport.ly
{
    public static class Constants
    {
        public static class Messages
        {
            public const string ChooseDeparture = "Choose departure Location";
            public const string PressAnyKey = "\nPress any key to go to the main menu...";
            public const string QuiApplicationMenu = "[ 0 ] Quit application\n";
            public const string ReturnToMainMenu = "[ 0 ] Return to main menu\n";
            public const string Tryagain = "Try again!!";

        }

        public static class Header
        {
            public const string MainMenu = "========= Transport.ly ============";
            public const string ChooseScheduleToLoad = "========= Choose a schedule to Load ============";
            public const string LoadedSchedules = "=========Loaded schedules ============";
            public const string BatchOfOrders = "========= Bathch of Orders ===========";

        }

        public static class MenuOptions
        {
            public static readonly string[] MainMenu = { "1. Load a schedule", "2. List out the schedules", "3. Generate flight itineraries ",
            "5. Exit"};
        }

        public static class Path {

            public readonly static string JsonPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Files\\coding-assigment-orders.json");

            public readonly static string ScenarioPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Files\\scheduledFlights.json");
        }

        public static class Rule {

            public const int PlaneCount = 2;
            public const int DepartureHour = 12;
            public const int ArrivalHour = 0;
            public const int PlaneBoxCountLimit = 20;
        }
    }
}

最后,主要

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;



namespace Transport.ly
{
    class Program
    {
        static void Main(string[] args)
        {
            Inventory transportLy = new Inventory("Transport.ly", Loader.LoadScenarioSchedule(), Loader.LoadOrders());

            MainMenu(transportLy);
        }

         static void MainMenu(Inventory inventory) {

            while (true)
            {
                int userChoice;

                do
                {
                    Console.Clear();
                    DisplayMAinMenu();
                    Console.WriteLine(Constants.Messages.QuiApplicationMenu);

                } while (!int.TryParse(Console.ReadLine(), out userChoice) || userChoice < 0 || userChoice > 3);

                Console.Clear();

                switch (userChoice)
                {
                    case 1:
                        MenuLoadSchedules(inventory);
                        break;
                    case 2:
                        DisplayLoadedSchedules(inventory.GetLoadedSchedules());
                        Console.WriteLine();
                        Console.WriteLine(Constants.Messages.PressAnyKey);
                        Console.ReadKey();
                        break;
                    case 3: DisplayFlights(inventory.GenerateFlights(), inventory.GetOrders());
                        Console.WriteLine(Constants.Messages.PressAnyKey);
                        Console.ReadKey();
                        break;
                    case 0:
                        Environment.Exit(0);
                        break;
                    default:
                        Console.WriteLine(Constants.Messages.Tryagain);
                        break;
                }
            }
        }


        static void MenuLoadSchedules(Inventory inventory)
        {
            while (true)
            {
                int option;

                do
                {
                    Console.Clear();

                    DisplayAvailableSchedules(inventory.GetAvailableSchedules());
                    Console.WriteLine(Constants.Messages.ReturnToMainMenu);

                } while (!int.TryParse(Console.ReadLine(), out option) || option < 0 || !inventory.GetAvailableSchedules().ContainsKey(option) && option != 0);

                if (option != 0)
                {
                    inventory.LoadSchedule(option);
                    Console.Clear();
                    Console.WriteLine("Schedule : " + option + " loaded");
                    Console.WriteLine(Constants.Messages.PressAnyKey);
                    Console.ReadKey();

                }
                else {

                    return;
                }

                Console.Clear();   
            }
        }



        static public void DisplayMAinMenu()
        {
            Console.WriteLine(Constants.Header.MainMenu);
            Console.WriteLine();
            foreach (string option in Constants.MenuOptions.MainMenu)
                Console.WriteLine(option);

        }

        static public void DisplayAvailableSchedules(Dictionary<int, Schedule> availableSchedules) {

            Console.WriteLine(Constants.Header.ChooseScheduleToLoad);
            Console.WriteLine();

            foreach (KeyValuePair<int, Schedule> entry in availableSchedules)
            {
                Console.WriteLine(entry.Key+ ". Departure: " + entry.Value.Departure + " Arrival: " + entry.Value.Arrival + " Day: " + entry.Value.Day);
            }
        }

        static public void DisplayLoadedSchedules(Dictionary<int, Schedule> schedules)
        {

            Console.WriteLine(Constants.Header.LoadedSchedules);
            Console.WriteLine();
            foreach (KeyValuePair<int, Schedule> entry in schedules)
            {
                Console.WriteLine(entry.Key + ". Departure: " + entry.Value.Departure + " Arrival: " + entry.Value.Arrival + " Day: " + entry.Value.Day);
            }
        }

        static public void DisplayFlights(List<Flight> flights, List<Order> AllOrder) {

            foreach (Order order in AllOrder)
            {

                Console.WriteLine(Constants.Header.BatchOfOrders);
                Console.WriteLine();


                if (order.Loaded)
                {
                    //get other informations

                    foreach (Flight flight in flights)
                    {
                        if (flight.Orders.FirstOrDefault(item => item.Code == order.Code && item.Destination == order.Destination) != null) {

                            Console.WriteLine("order: "+ order.Code+ ", flightNumber: "+flight.Number + ", departure: "+flight.Schedule.Departure+
                                ", arrival: "+flight.Schedule.Arrival+", day: "+flight.Schedule.Day);

                        }
                    }
                }
                else {

                    Console.WriteLine("order: "+order.Code+", flightNumber: not scheduled");

                }
            }
        }


    }
}
EN

回答 1

Code Review用户

发布于 2019-10-20 13:02:04

可以被认为是初级开发人员代码的主要事情是,将来对代码支持的可能性很低。要归档这一点,您需要使用一些常见的体系结构模式。首先,应该测试代码并处理错误。此外,还要求您提供可靠的代码,这同样意味着一堆模式(IoC作为DI在开发周期中是必须的)。例如,Loader类根本不可靠。为此目的尝试使用微服务体系结构。此外,我还可以看到一个奇怪的代码,如:

代码语言:javascript
复制
return _schedules.Where(s => s.Value.Loaded == false)
                        .ToDictionary(dict => dict.Key, dict => dict.Value);

我是说为什么:

代码语言:javascript
复制
s.Value.Loaded == false

而不仅仅是

代码语言:javascript
复制
s=>!s.Value.Loaded

实际上,在这一行代码之后,我将拒绝您对中间开发人员角色的候选资格。

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/230982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档