我的职业生涯始于核心功能范式开发人员(LISP),现在我是核心.net/C#开发人员。当然,我迷上了LINQ。但是,我也相信(1)使用正确的工具完成工作,并且(2)保留KISS原则:在与我合作的60多位工程师中,也许只有20%的人具有LINQ/功能范例经验,而5%有6到12个月的此类经验。简而言之,除非我无法实现一个目标(除非用一行LINQ替换3行O-O代码不是一个“目标”),否则我会感到自己不得不远离LINQ。

但是现在,一位拥有12个月LINQ/功能范例经验的工程师正在生产代码中每个可能的位置使用LINQ来处理对象,或者至少是lambda表达式。我对KISS原则的各种呼吁都没有产生任何结果。所以...

我接下来可以吸引哪些已发表的研究?其他人认为哪些“编码标准”指南取得了成功?我可以指出是否存在已发布的LINQ性能问题?简而言之,我正在尝试通过间接说服实现我的第一个目标-KISS。

当然,这个问题可以扩展到无数其他领域(例如过度使用扩展方法)。也许有一个备受推崇的“ super ”指南(例如,已发表的研究等)在此方面有更广泛的应用。任何事物?

最新编辑:哇!我上学了!我同意我的想法完全是错误的。但为澄清起见,请在下面查看我实际看到的示例代码。它最初是编译和工作的,但是现在它的目的已经不重要了。只是去与它的“感觉”。现在,半年后我将重新审视此样本,我对实际上困扰我的情况有了完全不同的了解。但我想比我发表评论要有更好的眼睛。

//This looks like it was meant to become an extension method...
public class ExtensionOfThreadPool
{
    public static bool QueueUserWorkItem(Action callback)
    {
        return ThreadPool.QueueUserWorkItem((o) => callback());
    }
}

public class LoadBalancer
{
    //other methods and state variables have been stripped...

    void ThreadWorker()
    {
        // The following callbacks give us an easy way to control whether
        // we add additional headers around outbound WCF calls.
        Action<Action> WorkRunner = null;

        // This callback adds headers to each WCF call it scopes
        Action<Action> WorkRunnerAddHeaders = (Action action) =>
        {
            // Add the header to all outbound requests.
            HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty();
            httpRequestMessage.Headers.Add("user-agent", "Endpoint Service");

            // Open an operation scope - any WCF calls in this scope will add the
            // headers above.
            using (OperationContextScope scope = new OperationContextScope(_edsProxy.InnerChannel))
            {
                // Seed the agent id header
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestMessage;

                // Activate
                action();
            }
        };

        // This callback does not add any headers to each WCF call
        Action<Action> WorkRunnerNoHeaders = (Action action) =>
        {
            action();
        };

        // Assign the work runner we want based on the userWCFHeaders
        // flag.
        WorkRunner = _userWCFHeaders ? WorkRunnerAddHeaders : WorkRunnerNoHeaders;

        // This outter try/catch exists simply to dispose of the client connection
        try
        {
            Action Exercise = () =>
            {
                // This worker thread polls a work list
                Action Driver = null;
                Driver = () =>
                {
                    LoadRunnerModel currentModel = null;
                    try
                    {
                        // random starting value, it matters little
                        int minSleepPeriod = 10;
                        int sleepPeriod = minSleepPeriod;

                        // Loop infinitely or until stop signals
                        while (!_workerStopSig)
                        {
                            // Sleep the minimum period of time to service the next element
                            Thread.Sleep(sleepPeriod);

                            // Grab a safe copy of the element list
                            LoadRunnerModel[] elements = null;
                            _pointModelsLock.Read(() => elements = _endpoints);

                            DateTime now = DateTime.Now;
                            var pointsReadyToSend = elements.Where
                                (
                                    point => point.InterlockedRead(() => point.Live && (point.GoLive <= now))
                                ).ToArray();

                            // Get a list of all the points that are not ready to send
                            var pointsNotReadyToSend = elements.Except(pointsReadyToSend).ToArray();

                            // Walk each model - we touch each one inside a lock
                            // since there can be other threads operating on the model
                            // including timeouts and returning WCF calls.
                            pointsReadyToSend.ForEach
                            (
                                model =>
                                {
                                    model.Write
                                    (
                                        () =>
                                        {
                                            // Keep a record of the current model in case
                                            // it throws an exception while we're staging it
                                            currentModel = model;

                                            // Lower the live flag (if we crash calling
                                            // BeginXXX the catch code will re-start us)
                                            model.Live = false;

                                            // Get the step for this model
                                            ScenarioStep step = model.Scenario.Steps.Current;

                                            // This helper enables the scenario watchdog if a
                                            // scenario is just starting
                                            Action StartScenario = () =>
                                            {
                                                if (step.IsFirstStep && !model.Scenario.EnableWatchdog)
                                                {
                                                    model.ScenarioStarted = now;
                                                    model.Scenario.EnableWatchdog = true;
                                                }
                                            };

                                            // make a connection (if needed)
                                            if (step.UseHook && !model.HookAttached)
                                            {
                                                BeginReceiveEventWindow(model, step.HookMode == ScenarioStep.HookType.Polled);
                                                step.RecordHistory("LoadRunner: Staged Harpoon");
                                                StartScenario();
                                            }

                                            // Send/Receive (if needed)
                                            if (step.ReadyToSend)
                                            {
                                                BeginSendLoop(model);
                                                step.RecordHistory("LoadRunner: Staged SendLoop");
                                                StartScenario();
                                            }

                                        }
                                    );
                                }
                                , () => _workerStopSig
                            );

                            // Sleep until the next point goes active. Figure out
                            // the shortest sleep period we have - that's how long
                            // we'll sleep.
                            if (pointsNotReadyToSend.Count() > 0)
                            {
                                var smallest = pointsNotReadyToSend.Min(ping => ping.GoLive);
                                sleepPeriod = (smallest > now) ? (int)(smallest - now).TotalMilliseconds : minSleepPeriod;
                                sleepPeriod = sleepPeriod < 0 ? minSleepPeriod : sleepPeriod;
                            }
                            else
                                sleepPeriod = minSleepPeriod;
                        }
                    }
                    catch (Exception eWorker)
                    {
                        // Don't recover if we're shutting down anyway
                        if (_workerStopSig)
                            return;

                        Action RebootDriver = () =>
                        {
                            // Reset the point SendLoop that barfed
                            Stagepoint(true, currentModel);

                            // Re-boot this thread
                            ExtensionOfThreadPool.QueueUserWorkItem(Driver);
                        };

                        // This means SendLoop barfed
                        if (eWorker is BeginSendLoopException)
                        {
                            Interlocked.Increment(ref _beginHookErrors);
                            currentModel.Write(() => currentModel.HookAttached = false);
                            RebootDriver();
                        }
                        // This means BeginSendAndReceive barfed
                        else if (eWorker is BeginSendLoopException)
                        {
                            Interlocked.Increment(ref _beginSendLoopErrors);
                            RebootDriver();
                        }
                        // The only kind of exceptions we expect are the
                        // BeginXXX type. If we made it here something else bad
                        // happened so allow the worker to die completely.
                        else
                            throw;
                    }
                };

                // Start the driver thread. This thread will poll the point list
                // and keep shoveling them out
                ExtensionOfThreadPool.QueueUserWorkItem(Driver);

                // Wait for the stop signal
                _workerStop.WaitOne();

            };

            // Start
            WorkRunner(Exercise);
        }
        catch(Exception ex){//not shown}
    }
}

最佳答案

好吧,在我看来,您就是想使代码更复杂的人-因为您认为您的同事们并没有采用真正简单的方法。在许多情况下,我发现LINQ to Objects使代码更简单-是的,的确包括将几行更改为一行:

int count = 0;
foreach (Foo f in GenerateFoos())
{
    count++;
}

变得
int count = GenerateFoos().Count();

例如。

在没有使代码更简单的地方,可以尝试使他远离LINQ-但是上面的示例确实避免了LINQ的明显阻碍,但是“KISS”代码显然是LINQ代码。

听起来您的公司可以从对其工程师进行培训以利用LINQ to Objects中受益,而不是始终尝试使用最低公分母来受益。

关于linq - LINQ(对象)何时过度使用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2648626/

10-12 00:27
查看更多