Should we contains test statements in code? [closed] - java

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.

Related

Struggling to fix infinite loop [closed]

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.

What is the "proper" form in which to write Java? [closed]

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 6 years ago.
Improve this question
Personally, I write my Java like this:
class xyz {
...
}
OR
if (condition) {
...
}
etcetera...
In so many examples, I see code written like this:
class xyz
{
...
}
OR
if (condition)
{
...
}
etcetera...
To me, my way makes the most sense because not only does it take less lines to write, but (again, in my opinion) looks more proper and professional. I'd love to know people's opinions - and reasoning behind them - as to which form is better and why.
The first one with opening braces on the same line is almost the standard Java programming guideline for years.
The original Sun Java guideline, that was never updated since 1999.
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html
Google Java guideline
https://google.github.io/styleguide/javaguide.html#s4.1-braces
Android style
https://source.android.com/source/code-style.html
On the opposite side, many open source platforms like Apache/maven advocate brace in new line

At what point does writing, maintaining and most importantly the overhead of a function become a viable alternative to repeated code? [closed]

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.

What is the easyest way to transform the In.ReadInts function from Java to C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have the following code:
public class Search
{
public static void main(String[] args)
{
int[] whiteList = In.readInts(args[0]);
while(!StdIn.Empty())
{
int key = StdIn.readIn();
...
}
}
%java Search largeW.txt < largeT.txt
How to transform it to C# ?
Here you are:
Console.WriteLine("Input your number: "); // input 4, press enter
var theVar = Convert.ToInt32(Console.ReadLine()); // theVar is 4
Hope this help.
Java and C# aren't too different. You just need to know how to read STDIN, right? For a console application, use Console.ReadLine() or one of the other methods provided by the Console class.
Also keep in mind when converting:
1. With method names, you capitalize the first letter of EVERY word, i.e. MyMethod(). (important because Main() needs to be capitalzed)
2. All classes are inside a namespace block.
3. All of your type conversion tools are under Convert
4. File is a static class. You don't create instances of it like in Java. I recommend looking at File.ReadAllLines(string name).
Other than that the syntax is very similar and it should be fairly easy to convert between the two languages.

Rearranging GOTO's using ASM [JAVA] [closed]

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 :)

Categories