方法设计 - 清晰或多功能 [英] Method design - clarity or multifunction

查看:49
本文介绍了方法设计 - 清晰或多功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 和 C# 中创建了一个类,允许我执行 SQL 查询,例如我有一个名为 Delete 的方法,它接受多个参数;

public static int Delete(字符串表,字符串列,字符串操作数,对象值)

我将 value 作为对象类型,因为我可能想删除基于字符串、整数或布尔值的行,这意味着该方法足够灵活以支持不同的类型.然后,我通过使用 Java 中的 instanceof 测试(或 C# 中的 .GetType),根据查询是否是字符串,将额外的'"字符附加到查询中>

粗略的例子:

if (value instanceof String){System.out.println("这是一个字符串");}别的{System.out.println("这不是字符串");}

在实现类的其余部分时,我开始思考前面提到的方法是否是一种理想的方法,或者我是否应该为特定数据类型实现其他方法,一个用于容纳 String,另一个用于 Integer 等等.

如果我开始实现这一点,那么这意味着会有其他方法在逻辑上的差异最小,但是每种方法只有一个目的,使它们易于遵循和记录.另一方面,如果我保持原样,那么需要生成和维护的代码就会少很多,它可以管理任何类型的 Delete 语句(就数据类型而言),并且只需要几个 if 语句确定通过参数传入的对象类型.

从面向对象/最佳代码实践的角度来看,哪种方法最好?

感谢提供信息!

解决方案

都没有.

您必须使用参数化查询.

不过你说得对;你应该把它保存在一个方法中.
在 C# 中,使此类方法通用化有时很有用.

I've made a class in both Java and C# that allows me to perform SQL queries, as an example I have a method called Delete which accepts several parameters;

public static int Delete(String table, String column, String operand, Object value)

I have the value as an Object type as I may want to delete rows based on String, Integers or booleans, this means the method is flexible enough to support the different types. I then append additional " ' " characters to the query depending on whether it is a string or not by using the instanceof test in Java (or .GetType in C#)

Crude example:

if (value instanceof String) 
{   
    System.out.println("It's a String");   
}   
else 
{   
    System.out.println("It's not a String");   
}

When implementing the rest of the class I began to think to myself whether the previously mentioned method is an ideal way or whether I should implement additional methods for specific data types, one to accomodate String, another for Integer and so on.

If I went about implementing this then it would mean that there would be additional methods with mimnimal difference in logic, however each method only has one purpose making them simple to follow and document. On the other hand if I keep it the way it is then there is a lot less code to be produced and maintained, it can manage any type of Delete statement (in terms of data types) and there only needs to be a few if statements to determine the type of object that was passed in via the parameter.

Which is the best approach to follow from a object-orientated / best code practices point of view?

Thanks for the information!

解决方案

Neither.

You must use parameterized queries.

You're right, though; you should keep it in a single method.
In C#, it is sometimes useful to make such methods generic.

这篇关于方法设计 - 清晰或多功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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