如果只使用一次局部功能,那有什么用呢? [英] Is there any point in using local functions if to only use them once?

查看:67
本文介绍了如果只使用一次局部功能,那有什么用呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有以下代码:

Imagine I have this code:

public void Foo()
{
    // Do bar work
    // Do baz work
    // Do foobar work
}

我意识到我可以(并且应该因为它做的不止一件事情)将其重构为:

And I realize I can (and should because it was doing more than one thing) refactor it into:

public void Foo()
{
    bar();
    baz();
    foobar();
}

private void bar()    { /* do bar work */ }
private void baz()    { /* do baz work */ }
private void foobar() { /* do foobar work */ }

但是后来我意识到我将永远不会在Foo()之外使用这些功能,因此这些功能只会使主页混乱和自动完成.我可以摆脱这个:

But then I realize I will never use these functions outside of Foo(), so those functions are just cluttering the main page and the auto-complete. I could get away with this:

public void Foo()
{
    bar();
    baz();
    foobar();

    void bar()    { /* do bar work */ }
    void baz()    { /* do baz work */ }
    void foobar() { /* do foobar work */ }
}

这会使事情变得更整洁,更混乱,但是我现在真正要做的就是使该方法更长而不是更短.

Which would make things neater and less clutter, but all I've really done now is made the method even longer instead of shorter.

推荐答案

这会使事情变得更整洁,更混乱,但是我现在真正要做的就是使该方法更长而不是更短.

Which would make things neater and less clutter, but all I've really done now is made the method even longer instead of shorter.

不,您没有.基本上,您说的是类似于在一个类中使用一个方法处理大量工作的类与一个类中执行相同工作但具有多个更短且更易于维护的方法之间没有什么区别.

No, you haven’t. You are basically saying something similar to not being any difference between a class with one method that does a whole lot of stuff and a class that does the same job but with multiple shorter and easier to mantain methods.

您的局部函数就像方法一样,它们包含在另一个方法中并不排除整体易于维护;功能封装在明确定义的范围内.

Your local functions are just like methods, the fact that they are contained within another method doesn’t preclude that the whole is much easier to maintain; functionality is encapsulated in clearly defined scopes.

这篇关于如果只使用一次局部功能,那有什么用呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆