标签: code-duplication

如何在Spring MVC(3.0)中将两个URL路由映射到相同的处理程序方法?

我有一个userPanel映射到/user/panelURL路由的方法:

@RequestMapping(value = "/user/panel", method = RequestMethod.GET)
public final String userPanel(HttpServletRequest request, ModelMap model)
Run Code Online (Sandbox Code Playgroud)

但是,我还想要这个userPanel方法来处理路由/panel而不创建一个单独的方法,如:

@RequestMapping(value = "/panel", method = RequestMethod.GET)
public final String panel(HttpServletRequest request, ModelMap model)
Run Code Online (Sandbox Code Playgroud)

有没有办法让userPanel方法处理两个路由以避免重复?

java spring spring-mvc code-duplication url-routing

2
推荐指数
1
解决办法
2542
查看次数

避免Python代码中的代码重复

请考虑以下Python代码段:

af=open("a",'r')
bf=open("b", 'w')

for i, line in enumerate(af):
    if i < K:
        bf.write(line)
Run Code Online (Sandbox Code Playgroud)

现在,假设我想处理的情况KNone,所以写入继续到文件的末尾.我现在正在做

if K is None:
    for i, line in enumerate(af):
        bf.write(line)
else:
    for i, line in enumerate(af):            
        bf.write(line)
        if i==K:
            break
Run Code Online (Sandbox Code Playgroud)

这显然不是解决这个问题的最佳方法,因为我正在复制代码.有没有更集成的方式我可以处理这个?if/break如果K不是None,那自然就是让代码只存在,但这涉及到编写动态的Lisp宏语法,而Python实际上并不是这样做的.为了清楚起见,我并不关心特定情况(我选择的部分原因是它的简单性),而不仅仅是学习我可能不熟悉的一般技术.

更新:在阅读了人们发布的答案并进行更多实验之后,这里有更多的评论.

如上所述,我正在寻找可以推广的一般技术,我认为@Paul的答案,即使用takewhilefrom iterrools,最适合.作为奖励,它也比我上面列出的天真方法快得多; 我不知道为什么.itertools虽然我已经看了好几次,但我并不熟悉.从我的角度来看,这是一个功能性编程For The Win!(有趣的是,itertools曾经有人要求提供有关删除的反馈的作者takewhile.请参阅http://mail.python.org/pipermail/python-list/2007-December/522529.html开头的帖子.)我简化了上面的情况,实际情况有点混乱 - 我正在写循环中的两个不同的文件.所以代码看起来更像:

for i, line in enumerate(af):
    if i < K:
        bf.write(line)
        cf.write(line.split(',')[0].strip('"')+'\n')
Run Code Online (Sandbox Code Playgroud)

鉴于我上传的例子,@Jeff合理建议,在情况下,当K …

python code-duplication control-flow

2
推荐指数
1
解决办法
1085
查看次数

避免JSP中的代码重复

我正在使用JSP和Spring框架.在页面中,我想在相应的select元素旁边有五个按钮.我的问题是如何避免重复代码呢?

以下是我对一个按钮选择组合的代码:

       <tr>
            <td>
                <sf:label path="inputFile">Select a file:</sf:label>
            </td>
            <td>
                <sf:select path="inputFile" cssStyle="width: 250px;" onchange="enableLocal(this.selectedIndex,'matButton')">
                    <sf:option value="Upload a Local File" />
                    <sf:option value=" --- Available already: --- " disabled="true" />
                    <sf:options items="${flowData.availableInputs}" />
                </sf:select>
            </td>
            <td>
                <input id="matButton" type="file" name="inputFile"/>
            </td>
        </tr>
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,名称inputFilematButton将被视为参数,即其他按钮将具有不同的名称.

我想到的是类似于具有两个参数的函数,它们将生成上述代码.可能吗?

code-reuse jsp code-duplication

2
推荐指数
1
解决办法
1221
查看次数

如何合并两个具有相同代码但在不同结构上运行的类

我试图通过删除重复的代码来改进现有的C++代码,但无法提出令人信服的方法.来自更有经验的C++同事的任何见解都非常感谢.

所以我有两个结构定义,我无法控制:

struct struct_1
{
...
other_s * s1;
other_s * s2;
other_s * s3;
... //other fields
};

struct struct_2
{
...
other_s * s1;
other_s * s2;
other_s * s3;
... //other fields, different than struct_1, but not that important
};
Run Code Online (Sandbox Code Playgroud)

最后我要改进的代码.我有两个几乎相同的类,它们以相同的方式在相同名称的结构字段上操作,但字段来自不同的结构.这些类不对仅存在于一个结构中的结构字段进行操作.这里(简化):

class class_1
{
    struct_1 * s;

    class_1(){
        s = new struct_1(); //the only practical difference
        ...
    }

    void method()
    {
        ...

        //this is simplification, in reality the code is more complex
        //however the same as in …
Run Code Online (Sandbox Code Playgroud)

c++ refactoring design-patterns code-duplication

2
推荐指数
1
解决办法
2570
查看次数

代码气味 - if/else构造

我有一个9个元素的列表.前三个代表位置,下一个速度,下一个力量.

有时我需要阵列中的力,其他时间速度,以及其他时间位置.

所以我写了一个函数如下:

def Extractor(alist,quantity):

    if quantity=='positions':
        x = alist[0]
        y = alist[1]
        z = alist[2]
        return (x,y,z)

    elif quantity=='velocities':
        vx = alist[3]
        vy = alist[4]
        vz = alist[5]
        tot_v = np.sqrt(vx**2 + vy**2 + vz**2)
        return (vx,vy,vz,tot_v)

    elif quantity=='forces':
        fx = alist[6]
        fy = alist[7]
        fz = alist[8]
        tot_f = np.sqrt(fx**2 + fy**2 + fz**2)
        return (fx,fy,fz,tot_f)
    else:
        print "Do not recognise quantity: not one of positions, velocities, force"
Run Code Online (Sandbox Code Playgroud)

但是,由于代码重复,这似乎是一个巨大的代码味道.是否有更好,更pythonic的方式来做到这一点?我对OOP很新,但是我可以使用某种类继承来利用多态吗?

python oop code-duplication

2
推荐指数
1
解决办法
764
查看次数

在枚举中覆盖抽象方法时避免代码重复

我在Java中使用枚举实现状态机.我在下面有一个玩具示例,我在其中转换X,YZ根据组成员身份进行状态转换.

问题是,过渡规则YZ相同(即,重写的方法是相同的).

有没有办法避免代码重复?在我的现实生活中,它有点严重,因此代码重复的可能性更大.

enum Group {
    A,B,C
}

enum Element {
    X(Group.A) {
        @Override
        public Element getNextElement(Element nextElement) {
            if(nextElement.getGroup() == Group.B) {
                return nextElement;
            } else {
                return this;
            }
        }
    },
    Y(Group.B) {
        @Override
        public Element getNextElement(Element nextElement) {
            if(nextElement.getGroup() == Group.A) {
                return nextElement;
            } else {
                return this;
            }
        }
    },
    Z(Group.C) {
        @Override
        public Element getNextElement(Element nextElement) {
            if(nextElement.getGroup() == Group.A) {
                return nextElement;
            } …
Run Code Online (Sandbox Code Playgroud)

java enums state code-duplication state-machine

2
推荐指数
1
解决办法
184
查看次数

如何从try-catch简化return语句

如何简化以下代码:

try
{
    var metadata = GetMetadata();
    return metadata ?? _provider.GetLatestMetadata(guid);
}
catch (AuthenticationException)
{
    return _provider.GetLatestMetadata(guid);
}
catch (HttpUnauthorizedRequestException)
{
    return _provider.GetLatestMetadata(guid);
}
catch (WebException)
{
    return _provider.GetLatestMetadata(guid);
}
catch (VcenterException)
{
    return _provider.GetLatestMetadata(guid);
}
Run Code Online (Sandbox Code Playgroud)

我想避免代码重复.

可能吗?

c# exception-handling code-duplication

2
推荐指数
1
解决办法
337
查看次数

我能以某种方式不写出完整的合格返回类型名称吗?

我有以下嵌套类的情况:

class PS_OcTree {
public:
  // stuff ...

private:
  struct subdiv_criteria : public octree_type::subdiv_criteria {
    PS_OcTree* tree;
    subdiv_criteria(PS_OcTree* _tree) : tree(_tree) { }
    virtual Element elementInfo(unsigned int const& elem, node const* n) override;
  };
};
Run Code Online (Sandbox Code Playgroud)

为了在.cpp文件中实现这个方法,我写了

PS_OcTree::subdiv_criteria::Element
PS_OcTree::subdiv_criteria::elementInfo(
  unsigned int const& poly_index, node const* n)
{
    // implementation goes here
}
Run Code Online (Sandbox Code Playgroud)

我写这个方法的全名很好,但是我真的还需要写回返类型的全名吗?在参数括号和函数体内,我可以访问subdiv_criteria类的名称,但这似乎不适用于返回类型.

我想写一些类似的东西

Element PS_OcTree::subdiv_criteria::elementInfo(
  unsigned int const& poly_index, node const* n)
{
    // implementation goes here
}

// or

auto PS_OcTree::subdiv_criteria::elementInfo(
  unsigned int const& poly_index, …
Run Code Online (Sandbox Code Playgroud)

c++ code-duplication clang visual-c++ c++11

2
推荐指数
1
解决办法
68
查看次数

如何避免具有语义相等的字段/属性的不同结构的代码重复?

鉴于以下两个结构:

pub struct RectangleRenderer {
    canvas: Canvas,
    origin: Point,
    shape: Rectangle,
}

pub struct CircleRenderer {
    canvas: Canvas,
    center: Point,
    shape: Circle,
}
Run Code Online (Sandbox Code Playgroud)

由于我来自爪哇,我会从中提取基类ShapeRenderer淘汰者和应用领域canvas,并origin到,虽然具体类型将继续把他们的领域shape。在这种情况下,Rust的最佳实践是什么,因为特征仅起到类似于界面的作用,因此不允许属性/字段?

inheritance struct code-duplication rust

2
推荐指数
1
解决办法
567
查看次数

如何删除相似的经过引用限定的成员函数之间的代码重复?

如何删除相似的const和非const成员函数之间的代码重复类似?,我想删除几乎相同的成员函数之间的代码重复,除了ref限定符。

假设我有一个类似这样的课程:

class MyStringBuilder
{
    std::string member;
public:
    // Other functions
    std::string create() const& {
        // Some work
        std::string result = member;
        // More work
        return result;
    }

    std::string create() && {
        // Some work
        std::string result = std::move(member);
        // More work
        return result;
    }
};
Run Code Online (Sandbox Code Playgroud)

我们想对一个构建器对象执行此操作并非不可想象,因为如果使用完成,它将保存一个副本MyStringBuilder

除了使用成员的位置外,const&版本和&&版本之间的代码相同。这两个函数之间的唯一区别是,只要引用了该&&版本std::move的任何成员,该版本就可以。

如何避免此代码重复?

c++ code-duplication c++11 ref-qualifier

2
推荐指数
1
解决办法
97
查看次数