我需要在我的应用程序中将某些数字限制为有效范围.我创建了代表来处理这个问题.我不知道这是否是正确的做法; 我遇到了一些错误的事情.
public delegate int RestrictInteger(int minimum, int maximum, int value);
public delegate decimal RestrictDecimal(decimal minumum, decimal maximum, decimal value);
class GameMath
{
public static int RestrictNumber(int minimum, int maximum, int value)
{
if (value < minimum) { value = minimum; }
else if (value > maximum) { value = maximum; }
return value;
}
public static decimal RestrictNumber(decimal minimum, decimal maximum, decimal value)
{
if (value < minimum) { value = minimum; }
else if (value > maximum) { …Run Code Online (Sandbox Code Playgroud) 我想在 2 个字段上打印一堆整数作为'0'填充字符。我可以做到,但会导致代码重复。我应该如何更改代码以便消除代码重复?
#include <ctime>
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
string timestamp() {
time_t now = time(0);
tm t = *localtime(&now);
ostringstream ss;
t.tm_mday = 9; // cheat a little to test it
t.tm_hour = 8;
ss << (t.tm_year+1900)
<< setw(2) << setfill('0') << (t.tm_mon+1) // Code duplication
<< setw(2) << setfill('0') << t.tm_mday
<< setw(2) << setfill('0') << t.tm_hour
<< setw(2) << setfill('0') << t.tm_min
<< setw(2) << setfill('0') << t.tm_sec;
return ss.str(); …Run Code Online (Sandbox Code Playgroud) 我有两种方法都可以从Arraylist中获取用户对象.
public User getUser(int userID) {
ListIterator<User> listIterator = listOfLoggedInUsers.listIterator();
User user;
while(listIterator.hasNext()) {
user = listIterator.next();
if (user.getID() == userID) {
return user;
}
}
return null;
}
public User getUser(String username) {
ListIterator<User> listIterator = listOfLoggedInUsers.listIterator();
User user;
while(listIterator.hasNext()) {
user = listIterator.next();
if (user.getUsername().equals(username)) {
return user;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
由于方法只在if语句中有所不同,如何减少代码重复?例如,可以在参数中发送表达式/动态布尔值吗?
当我使用 hibernate 时,我每次必须编写某种代码时都会看到这一点。所以我将它们移到另一种方法作为包装器。哪里会有函数式接口作为参数,以便我可以在这些上下文方法中附加一些代码。
这是我的两种方法。一个返回对象,而另一个返回列表。我怎样才能准确地泛化并将这两种方法合二为一,这样我就可以避免代码重复。
public Object objectReturnContext(Function<Session, Object> function) {
Object object = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession();
transaction = session.beginTransaction();
object = function.apply(session);
transaction.commit();
} catch (NoResultException exception) {
if (transaction != null) transaction.rollback();
return object;
} catch (HibernateException exception) {
if (transaction != null) transaction.rollback();
exception.getStackTrace();
}
return object;
}
public List<T> listReturnContext(Function<Session, List<T>> function) {
List<T> object = null;
Transaction transaction = null;
try {
Session session = HibernateUtil.sessionFactory().getCurrentSession(); …Run Code Online (Sandbox Code Playgroud) 我有一个从左到右打印树节点的函数。
void PrintTree()
{
...
Print(curentNode);
...
}
Run Code Online (Sandbox Code Playgroud)
但是现在我想添加一个函数来打印满足某些条件的节点。例如,只打印这样的节点,其中的字符串以给定的字符串开头。所以它看起来像
void PrintTreeByCondition(string a)
{
...
if(IsPrefix(a,curentNode->stringVar))
Print(curentNode);
...
}
Run Code Online (Sandbox Code Playgroud)
但是后来我有两个具有相同代码的函数,不同之处在于一行。我将如何避免代码重复?
UPD:遍历代码:
void BinTree::TraverseTree()
{
std::stack<TreeNode*> s;
s.push(root);
TreeNode* curentNode = s.top();
while (curentNode != nullptr|| s.empty() == false)
{
while (curentNode != nullptr)
{
s.push(curentNode);
curentNode = curentNode->GetLeft();
}
curentNode = s.top();
s.pop();
// do stuff
curentNode = curentNode->GetRight();
}
}
Run Code Online (Sandbox Code Playgroud) 我想知道在C#中实现正确,灵活和快速Equals的最佳方法,几乎可以用于任何类和情况.我认为性能需要专门的Equals(将实际类的对象作为参数).为了避免代码重复,一般Equals应该调用专门的Equals.即使在继承的类中,也应该只执行一次空检查.
我终于想出了这个设计:
class MyClass
{
public Int32 SomeValue1 = 1;
public Int32 SomeValue2 = 25;
// Ignoring GetHashCode for simplicity.
public override bool Equals(object obj)
{
return Equals (obj as MyClass);
}
public bool Equals(MyClass obj)
{
if (obj == null) {
return false;
}
if (!SomeValue1.Equals (obj.SomeValue1)) {
return false;
}
if (!SomeValue2.Equals (obj.SomeValue2)) {
return false;
}
return true;
}
}
class MyDerivedClass : MyClass
{
public Int32 YetAnotherValue = 2;
public …Run Code Online (Sandbox Code Playgroud) 好吧,我现在正在重构我很久以前制作的一个课程.该类是容器类型.
许多函数可以利用类结构的优点,因此实现为成员函数.然而现在它似乎是很多看似"相同"的功能,即"查找"功能:
iterator find(ITEM)
const_iterator find(ITEM) const;
iterator find_if(ITEM, PRED)
const_iterator find_if(ITEM, PRED) const;
Run Code Online (Sandbox Code Playgroud)
4个"函数"来描述几乎相同(并且每个版本的代码几乎相同).更新课程时这变得非常繁琐,我必须确保每个版本都升级.有没有办法更好地处理这些事情?类CAN中的其他一些函数可能需要2个谓词,这意味着我突然有8个函数需要管理.
我试过调用"常量版本的非常量版本",但这显然不起作用.
那么如何处理这些事情呢?只需咬紧牙关并写下来?
编辑:只是为了通知:我的数据结构类似于"树".每个"对象"包含数据(查找搜索)和带有子树的"列表".find函数在树(和子子树)的所有子树上递归递归. - 就像人们在搜索树时所期望的那样.
由于没有明确的"结束"或"开始"迭代器到这样的树,使用std :: find不会产生正确的功能.
我有一些衍生自基本政策的政策。一些类专门针对派生策略,而另一些类仅专门针对基本策略,并且可以与所有派生策略一起使用。
我遇到的问题是太多的代码重复(主要是类本身的构造函数和一些样板代码)。下面的代码可能会更好地解释我的意思:
struct BasePolicy {};
struct DerivedPolicy1 : public BasePolicy {};
struct DerivedPolicy2 : public BasePolicy {};
//... more policies deriving from BasePolicy (or other BasePolicies)
struct AnotherPolicy {};
template <typename T>
struct Foo;
// This struct can work for all BasePolicy types which includes all derivations
// of it (but doesn't because it is specialized for BasePolicy only)
template<>
struct Foo<BasePolicy>
{
//... many constructors along with code
};
template<>
struct Foo<AnotherPolicy>
{
//... more code
};
/* Would …Run Code Online (Sandbox Code Playgroud) 我一直在研究的Java项目与几个RDBMS集成在一起.我们在处理它们的方式之间减少代码重复的最明显方法是创建类型层次结构,如:
ThirdPartySoftware (superclass)
/|\
/ | \
TPS1 2 3
Run Code Online (Sandbox Code Playgroud)
然而,这种方法最终导致TPS1,TPS2和TPS3的实现非常相似(但并不完全!).如果没有超类基本上意识到某些东西可能会有所不同,那么很难将所有功能都引入超类中,打败封装子类就意味着要购买我们.
我们考虑过的一种方法是通过它们共享的功能来表示数据库,例如"支持功能X"和"不能执行功能Y",但是并不完全清楚代码最终会以这种方式更易于维护,因为:
有没有人有其他建议我们可以减少子类之间的代码重复,也许使用设计模式?
编辑:我已更新下面的代码示例,以更好地说明问题.
假设我有两个不需要任何功能的仅字段结构.
假设它们代表来自数据库的两种类似的数据:
type Boy struct {
Name string
FavoriteColor string
BirthDay time.Time
}
type Girl struct {
Name string
FavoriteFlower string
BirthDay time.Time
}
Run Code Online (Sandbox Code Playgroud)
我为Boy结构编写了一个函数,根据给定的日期和男孩的信息打印问候语.
假设这是一个占位符,用于更复杂的函数,它根据time.Time字段执行某些操作,并返回int将在应用程序的其他位置使用的函数:
func CheckBirthDayBoy(date time.Time, boy Boy) int {
numDays := 0
if date.Before(boy.BirthDay) {
// Greet how many days before birthday
numDays = int(boy.BirthDay.Sub(date).Hours() / 24)
fmt.Println("Hi, " + boy.Name + "! Only " + strconv.Itoa(numDays) + " days until your birthday! I hear your favorite color is …Run Code Online (Sandbox Code Playgroud)