我有一个测试套件,类似于我用以下代码描述的情况.有两种情境可以定义主题.主题是相似的,相同类型的对象,但具有不同的值.
在那个主题上,我进行了两次测试.两个测试完全相同,另一个测试不同.
建议一个可以消除重复的重构,除了显而易见的"将代码移动到一个方法",我不喜欢它,因为它不清楚.
require 'rspec'
describe "tests over numbers" do
context 'big numbers' do
subject { 5000 }
describe "#to_string" do
its(:to_s) {should be_a(String)}
end
describe "#+1" do
it "+1" do
sum = subject+1
sum.should == 5001
end
end
end
context 'small numbers' do
subject { 100 }
describe "#to_string" do
its(:to_s) {should be_a(String)}
end
describe "#+1" do
it "+1" do
sum = subject+1
sum.should == 101
end
end
end
end
Run Code Online (Sandbox Code Playgroud) switch (options.effect) {
case 'h-blinds-fadein':
$('.child').each(function(i) {
$(this).stop().css({
opacity: 0
}).delay(100 * i).animate({
'opacity': 1
}, {
duration: options.speed,
complete: (i !== r * c - 1) ||
function() {
$(this).parent().replaceWith(prev);
options.cp.bind('click', {
effect: options.effect
}, options.ch);
}
});
});
break;
case 'h-blinds-fadein-reverse':
$('.child').each(function(i) {
$(this).stop().css({
opacity: 0
}).delay(100 * (r * c - i)).animate({
'opacity': 1
}, {
duration: options.speed,
complete: (i !== 0) ||
function() {
$(this).parent().replaceWith(prev);
options.cp.bind('click', {
effect: options.effect
}, options.ch);
}
});
});
break;
....more …Run Code Online (Sandbox Code Playgroud) 下面是一个方法,我很难弄清楚如何使用JUnit进行测试.
这种方法很难测试,因为它取决于其他方法的结果(例如getClosestDcoumentCode).
基于我对JUnit的阅读,这表明我应该重构该方法.但是怎么样?如果不需要重构,您如何测试依赖于其他方法的方法?
谢谢,
埃利奥特
private static String findPrincipal(List<DocumentKey> documentkeys_) {
Hashtable<String, Integer> codecounts = new Hashtable<String, Integer>();
for (DocumentKey document : documentkeys_) {
int x = 0;
String closestCode = getClosestDocumentCode(document.candidates);
if (closestCode == null) continue;
int thecount = 0;
if (codecounts.containsKey(closestCode))
thecount = codecounts.get(closestCode);
if (document.hasKey)
thecount += 2;
else
thecount++;
codecounts.put(closestCode, new Integer(thecount));
x++;
}
String closestCode = getClosestCode(codecounts);
return closestCode;
}
Run Code Online (Sandbox Code Playgroud) 嗨我有两种方法,还有三种方法(在这个问题中没有提到)..
我怎么能重构这些..
方法1:
public DataTable GetVisits(System.DateTime startdate , System.DateTime enddate)
{
const string sql = @"SELECT CONCAT(UPPER(SUBSTRING(visit_Status, 1, 1)), SUBSTRING(visit_Status FROM 2)) as Status, COUNT('x') AS Visits
FROM visits
WHERE visit_Date BETWEEN @startdate AND @enddate
GROUP BY visit_Status";
var tblvisits = new DataTable();
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring))
{
conn.Open();
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var ds = new DataSet();
var parameter = new MySql.Data.MySqlClient.MySqlParameter("@startdate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter.Direction = ParameterDirection.Input;
parameter.Value = startdate.ToString(dateformat);
cmd.Parameters.Add(parameter);
var parameter2 = new …Run Code Online (Sandbox Code Playgroud) 我有一个哈希列表,一些哈希包含一个提供数组本身的键.
my @cars = (
{ # empty car
name => "BMW",
},
{ # car with passengers
name => "Mercedes",
passengers => [qw(Paul Willy)],
},
...
)
Run Code Online (Sandbox Code Playgroud)
它几乎就像上面但当然不是以愚蠢的汽车为例:-)
现在我需要从所有哈希中获得所有"乘客"的列表,包括那些甚至不提供乘客阵列的乘客.
在第二步中,我需要从列表中检索唯一条目(实际上乘客是Perl对象引用,我需要列表中的每个对象一次)
目前我这样做:
my (@all, @passengers, %seen);
for(@cars) {
push @all, @{$_->{passengers}} if $_->{passengers};
}
@passengers = grep { ! $seen{$_} ++ } @all;
Run Code Online (Sandbox Code Playgroud)
我想摆脱@all并将所有乘客的名单直接扔进去grep.
有什么建议?
我有这个foreach循环:
var includedElements = new HashSet<int>();
foreach(var e in elements)
{
var include = false;
if(isTable(e.Key))
{
if(tables.ContainsKey(e.Key)
{
if(tables[e.Key].Elements
.Any(subElem => shouldBeIncluded(subElem.Key) ) )
{
include = true;
}
}
}
else if(shouldBeIncluded(e.Key))
{
include = true;
}
if(include){
includedElements.Add(e.Key);
DoSomeMoreStuff(e);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图将其重构为LINQ:
var query =
from e in elements
where
(
isTable(e.Key)
&& tables.ContainsKey(e.Key)
&& tables[e.Key].Elements
.Any(subElem => shouldBeIncluded(subElem.Key) )
) || (
!isTable(e.Key)
&& shouldBeIncluded(e.Key)
)
select e;
foreach(e in query){
includedElements.Add(e.Key);
DoSomeMoreStuff(e);
}
Run Code Online (Sandbox Code Playgroud)
什么我不知道的是或 …
我有一些简单的逻辑来检查字段是否有效:
private boolean isValidIfRequired(Object value) {
return
(required && !isEmpty(value)) || !required;
}
Run Code Online (Sandbox Code Playgroud)
它告诉该字段是有效的,如果它是要求的而不是空的或不需要.
我不喜欢这个必需的|| !必填部分 只需要的东西会更好.如何简化此方法以使其更易读和简单?
我的直觉告诉我,对于以下代码,有一个更好的,也许是单行重构:
if (isset($x))
{
if (isset($y))
{
$z = array_merge($x,$y);
}
else
{
$z = $x;
}
}
else
{
$z = $y;
}
Run Code Online (Sandbox Code Playgroud)
如果我不担心警告错误,一个简单的array_merge($x,$y)工作,但我想知道一个更好的方法来做到这一点.思考?
鉴于以下代码,
你会如何重构这个,以便方法search_word可以访问issueid?
我会说改变函数search_word使得它接受3个参数或者使issueid成为实例变量(@issueid)可以被视为不良实践的一个例子,但老实说我找不到任何其他解决方案.如果除此之外没有其他解决方案,您是否介意解释为什么没有其他解决方案?
请记住它是Ruby on Rails模型.
def search_type_of_relation_in_text(issueid, type_of_causality)
relation_ocurrences = Array.new
keywords_list = {
:C => ['cause', 'causes'],
:I => ['prevent', 'inhibitors'],
:P => ['type','supersets'],
:E => ['effect', 'effects'],
:R => ['reduce', 'inhibited'],
:S => ['example', 'subsets']
}[type_of_causality.to_sym]
for keyword in keywords_list
relation_ocurrences + search_word(keyword, relation_type)
end
return relation_ocurrences
end
def search_word(keyword, relation_type)
relation_ocurrences = Array.new
@buffer.search('//p[text()*= "'+keyword+'"]/a').each { |relation|
relation_suggestion_url = 'http://en.wikipedia.org'+relation.attributes['href']
relation_suggestion_title = URI.unescape(relation.attributes['href'].gsub("_" , " ").gsub(/[\w\W]*\/wiki\//, ""))
if not @current_suggested[relation_type].include?(relation_suggestion_url)
if @accepted[relation_type].include?(relation_suggestion_url)
relation_ocurrences << {:title => …Run Code Online (Sandbox Code Playgroud) 我有一个非常讨厌的代码我想重构但是因为它完全不可读.
for region in feed['config']['regions']:
if region['region'] == region_name:
for instance_type in region['instanceTypes']:
if instance_type['type'] == instance_type_name:
for instance_size in instance_type['sizes']:
if instance_size['size'] == instance_size_name:
for platform in instance_size['valueColumns']:
if platform['name'] == platform_name:
prices = platform['prices']
assert prices.keys() == ['USD']
return decimal.Decimal(prices['USD'])
assert False, "Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" % \
(region_name, instance_type_name, instance_size_name, platform_name)
Run Code Online (Sandbox Code Playgroud)
我已经考虑过在每个循环或if语句中使用函数,但这会给我一大堆函数.有更好的解决方案吗?