Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm new to JUnit testing and I'm struggling to test a method that will search for a specific vehicle registration and output it that it is found
System.out.println("getSpecificVehicle");
CVMQueue instance = new CVMQueue();
VehicleNode newVehicle = new VehicleNode("YBZ5484", "Car", "Ire", 3, 2.2);
instance.enqueue(newVehicle);
String expResult = "YBZ5484";
String result = instance.getSpecificVehicle("YBZ5484");
assertEquals(expResult, result);
This is my code, It keeps looping in the Console.
How can I fix this?
Check your code; if you improve the formatting you find
while (temp != null) {
...
if (reg.equalsIgnoreCase(temp.getRegNum())) {
...
}
}
Your loop is never changing temp. So, why should it ever stop looping upon being entered? So, obviously your problem is that you missed that loop-closing brace; as you put that assignment to temp after that brace.
But the real take-aways here:
Formatting matters. Maybe, if you had put more diligence in writing down your code, you would have spotted this yourself much earlier. And as Gaket points out correctly: any sane IDE (or coding editor) probably has some "auto format" functionality, that well, formats your source code automatically.
Leading to: code readability matters even more. For example, there is the "Single layer of abstraction" principle; which would have told you to not just put that complete if into that loop; instead you would have created a method to do that work. And again, it would have been so much easier to spot this simple problem.
Learn about using a debugger. You see, the real power of unit tests is that they make it also so easy to isolate bugs: you put a breakpoint somewhere; and run your test in the debugger; and you can directly observe what is going on.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I came across the below snippet. But I do not understand if it an example of dead code / duplicate code / temporary field?
public class InterestRateComputer {
public double interest (double amount) {
double interest = 0;
if (balance > MIN_BALANCE) {
//compute the regular interest
return interest;
}else {
//compute interest for below min balance
return interest;
}
return -1;
}
}
It doesn't even compile. Java does not usually allow dead code if its (very basic) analysis shows that there is dead code AND a boolean constant isn't involved (complicated, silly reasons for that last rule). Except, in java, this is more generally called 'unreachable code' (it means the same thing as 'dead code', but that's the term usually used, and what the compiler will be mentioning as it refuses to compile this).
"Temporary Field"? No idea what that's about - it is certainly completely unrelated to the concept of dead code.
It's not duplicate code - duplicate code is not something in any specification. When used without further context, it generally means the notion that somebody's been copy/pasting code all over the place. It works fine, but it's annoying: If there is a bug in this code, you now have to fix it in 50 places, for example (there are more reasons it's a bad idea to copy/paste code all over. Instead, put the code in a library, utility method, or class - and then have all places where you wanted to paste it to use this library/utility/class).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I know the question is not related to technology,is about the code style and standard.
I have just studied programming for 1 year,and so many people tell me that "you should test any single part of your program rather than code all then test".But they forgot to say whether we should delete test statements when officially released?
I hear several different voice:
It makes your code looks bloated,so delete it.
You shouldn't delete it if you want to modify something later.
You can delete it,but you must write some comment if needed.
A simple code contains test just like this:(the real code won't as easy as it,and the example may be a bit bad)
void Function(){
printf("hello,world");
}
int main(){
// Function();
return 0;
}
So my question is should we delete it ?The result is like this:
void Function(){
printf("hello,world");
}
int main(){
return 0;
}
This is not what they mean by testing code though.
Instead you write separate test function for each part of your code, that can run independently of your main code. Then use a test-runner ( pytest, unittest or nose are the most popular) to run your tests.
Example, say your main code has a function like this:
def add_numbers(a,b):
return a+b
and your main is like this:
def main():
x = 4
y = 5
z = add_numbers(x,y)
#print(z) <-- dont do this
instead you create a new function, often in a new file:
def test_add_numbers():
a=200
b=343
res = add_numbers(a,b)
assert res == 543
Test runners will then run all your tests and output if any one of them doesn't work.
When officially released the code base should have unit tests written and everytime you make a change, those unit tests should pass.
Tests should not be written like you are writing, they should use pytest etc.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've been wondering this for a while, and thought I'd pose the question today.
Example code:
private void createLinks(int numUsers) {
for (int i = 1; i <= numUsers; i++) {
String userId = "ID-" + i;
String randomId;
// Generate an ID to link to.
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(userId, randomId); //links the first argument to the second,
//links are not bi-directional.
// Generate 4 more ID's to link to.
for (int j = 1; j <= 4; j++) {
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(userId, randomId);
link(randomId, userId);
}
// Generate another ID to link
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(randomId, userId)
}
}
#createLinks is invoked a lot, and the do...while code snippet is being repeated in the method. Does it make sense to extract these 3 lines of code out to a method called generateRandomId(int i) and incur the function overhead to avoid this repetition? If createLinks gets invoked a 100 times, generateRandomId would get invoked 100*6 = 600 times.
This is more a language agnostic question rather than one specific to java, but it'd be interesting to know if some languages handle function overhead better than others. E.g. JVM does function inlining to optimize function calls, which might mean that a developer need not wonder about things that I mentioned above.
This is definitely opinion-based question, and I expect it will be closed. But I'll try to answer it anyway, because it's quite frequently asked.
If you want simple answer – don't bother about it. It's probably too soon. Really, the manner you ask a question tells me that you have a lack of information about how frequently this code will be called and how slow it really is. And it's ok. We all face this situation when there are just a lot of unknowns in the context of development. The trick is – those unknown will become knowns in operation context (when your code is actually running). You'll get a feedback about performance issues if any. It should be said, getting this feedback is not so simple task by itself and requires some skills and mature toolchain. But it's not the question you asked.
Does I advocate skip any performance optimization while developing? Of course no, it's silly. There are issues which could and should be solved early. I'm just advising to follow simple and straightforward principle:
If you're in doubt – wait for reality to show you the right way.
This principle could be misused as any other. But I hope you get my point – premature optimization is the root of all evil, right?
My opinionated answer is "always." Whenever I find myself writing the same code twice, I make it a function.
The point where this practice ceases to be opinion-based is when two pieces of code doing exactly the same thing is important to the proper operation of the program.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The Boolean array is initialized to true. I need to know how to turn every third value to false and also going through the array over and over. It is essentially duck duck goose without the randomness.
This sounds like a beginners programming exercise, so I'm going to just give you a hint or two:
Go back to your textbook, lecture notes, tutorial and reread the stuff on for loops. Focus on the old style ones.
Think about how to write a for loop that steps through integer index values in the pattern that you require.
Re "... going through the array over and over" - not sure what you mean, but maybe the hint for this is to think about using nested loops; i.e. a loop inside another loop.
But the most important advice is to try and work this out for yourself.
Well I'm really not sure what you mean by going through the array over and over but the following code will turn every third value to false.
for (int i = 0; i < myVar.length; i++) {
if (i % 3 == 0) {
myVar[i] = false;
}
}
Edit: Oops someone beat me to it while I was typing lol.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am looking at an obfuscated application, and the application seems to have a lot of GOTO's which I want to rearrange or remove
The question is, how would I go about doing this?
for(final MethodNode mn : classNode.methods) {
final BIF is = new BIF(mn); //BIF is my bytecode instruction finder
AbstractInsnNode ain;
while ((ain = is.next()) != null) {
if (ain instanceof JumpInsnNode && ain.getOpcode() == GOTO) {
final JumpInsnNode jump = (JumpInsnNode) ain;
mn.instructions.remove(jump);
removed++;
}
}
}
So I've tried just removing them all, but it doesn't seem to work and I don't know how to rearrange them
I don't think you'll be able to solve this easily, it looks like a quite radical obfuscation mechanism. You could try to un-goto it, linearizing the code by defragmenting the chunks between goto jumps. But then, some goto's are legitimate flow control jumps, so you'll need a way to detect this. It looks like a real challenge, one that will take much of your time. But, maybe the challenge is intruguing enough to push forward :)