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
Im trying to use a assert stmt to check if a value is greater than 1 but its not working as expected.
public class asserttest {
static void methoda(int i){
assert (i > 1);
System.out.println("This is methoda");
}
public static void main(String[] args){
methoda(-1);
}
}
Output:
This is methoda
Expected output:-
assertionerror
I was able to fix it by enabling the assertions.
My guess is that you're getting confused by assertions not being enabled by default. Use the -enableassertions command line option:
java -enableassertions asserttest
You can also limit assertions to specific packages, and specify packages to disable using -disableassertions too.
Personally I prefer to unconditionally validate parameter values, precisely because of this - I don't like the idea of running the code in a "safe" mode in test, but then letting it loose in production with the safety off. It's like learning to drive with a seatbelt on, but then entering an F1 race without any protection...
You should never use assertions on parameters or any input value in general.
Assertions are meant to describe invariants that ought to be always true. Therefore they can be switched off for performance reasons. You have to enable them, e.g. by using the -ea JVM option.
But inputs to a method should always be checked so use
if(i<=1) throw new IllegalArgumentException("i must be >1");
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 8 months ago.
Improve this question
I want to migrate old Java code to Java 17. Is it a good idea to replace:
Collections.unmodifiableList(Arrays.asList(....)); to List.of("....");
Should I expect code execution error or there should be no impact?
specific answer
Obviously, the best way to figure this out is to try it yourself.
If you want some certainty before you attack this challenge, it is usually a good idea to look at the method signatures in the java API documentation for the different versions.
Java 7 spec of Collections.unmodifiableList: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableList(java.util.List)
Java 17 spec of List.of: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html#of()
As you can see, both return an unmodifiable List<E>. So I would say your update is quite safe.
general approach
In general, if you are going to refactor a common part of your codebase, it is a good practice to first extract all occurrences of this construct in your codebase onto a utility method.
For your case, you could create a simple utility class, like so:
public final class ListUtilWrapper {
public static <E> List<E> listOf(E... elements) {
return Collections.unmodifiableList(Arrays.asList(elements));
}
}
After each call is replaced by ListUtilWrapper.listOf(....), you compile and test your code.
Next up, you replace the implementation of ListUtilWrapper.listOf to be List.of(elements) and rebuild your codebase.
If all works well: inline the utility method after some manual testing. If it fails, you can easily roll back to a stable state.
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 am working with a legacy code, where I see certain DB transaction initiated in try-with-Resources close block. I understand the DB resource will be closed once the code in the try block is executed. Can somebody help me, how can I over-ride or bypass the autoclosing, in this case ? I am working with the legacy code and that too for very short time, so want not to change too much of code, and invite unit tests failures.
Unfortunately you can't hack your way round this by assigning the try-with-resources identifier to null, or a similar technique: Java does not let you do that.
That's a good thing as it would pollute your source code making reversal of the temporary change difficult.
Fortunately there are better ways: If you're able to change the resources class slightly, you could always build a disableClose() method on it, which sets some flag so that the subsequent close() call is benign. If you can't change the resources class then derive a class from it and create an instance of that instead. Despite this potentially requiring boilerplate constructor code, it might be a better approach since then you could build something that tracks the instances that have not been closed correctly.
Adopting either technique means that you can weed out this temporary change quite simply by removing the disableClose() method or the derived class once you're done with it, which will introduce compilation failures that you can fix one by one.
Possible implementation of the derived class approach:
public class Foo extends YourResource
{
// ToDo - add constructors here.
private boolean disable = false;
#Override
public void close()
{
// ToDo - consider maintaining a collection of unclosed instances.
if (!disable){
super.close();
}
}
public void disableClose()
{
disable = true;
}
}
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
Android Studio is, apart from other things, a fairly fancy Java IDE, and it has a bunch of built-in language specific edit features that can perform various code transformations. One of these that surprised me is "Expand Boolean", and its partner "Expand Boolean to multiple ifs". The documentation says that the first will transform this:
public class X {
boolean f(boolean a) {
return a;
}
}
into this:
public class X {
boolean f(boolean a) {
if(a) {
return true;
}
else {
return false;
}
}
}
My question is why you might want to? Is there a performance advantage to be had in Java? The original version seems to be superior in terms of clarity and conciseness.
Intentions are not necessarily quick fixes, sometimes they are just warnings or available macros for micro-refactoring.
The one in question doesn't assume any error with your code since this one also appears with
boolean f(boolean a, boolean b) {
return b&&a;
}
What is trying to provide is a way to move from boolean expression to conditional alternative. Sometimes your condition becomes complex and doesn't fit into a single expression any more and you end up writing an if. So, instead of writing it by hand, it offers you to do so automatically.
Note that, once you apply the intention, other intentions like clean code and simplify appear, and applying them will undo the expansion. And this time they appear as quick fixes, since now it's actually seeing a problem with your code.
In other words, this is just a macro useful as a first step for further changes and probably wasn't created to use it alone.
It doesn't actually suggest you to do the change, but just letting you know that it can be handled automatically if you intend to do it.
On a side note, the user documentation reference this kind of intentions as suggestions, but I find that name misleading for the reasons I stated above.
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 8 years ago.
Improve this question
The reasons I am dissatisfied with assert keyword in Java are
1) it's disabled by default, so it is a headache to make sure it's enabled when I want it to be
2) its behavior is rather rigid (I would want some inversion of control, ideally); but that's not terribly important.
Some of the alternatives I can think about:
JUnit's assertEquals() and such - good for tests, but can't use in main code
Guava's preconditions - great, but no assertion methods per se.
My own assertion library - I wrote it back in 1999, and back at the time it was great, but now I want to standardize.
Anything else?
So.. to sum it up.. how do I assert in production code in a way that is not disabled by default?
(And yes, this may be considered an anti-pattern by some, but I do want at least some assertions in Production, even if assertion failures are just silently logged. I see some room for that even in shrink-wraps, and definitely in websites).
I'd use Spring's Assert class, it includes a fairly extensive range of checks.
I am not sure if this is what you want, but I'm routinely using commons-lang Validate for many years already. Usually in public API methods/constructors to ensure that arguments are passed correctly. Not just notNull (see Lombok's #NotNull for this) but also noNullElements etc.
I especially like the <T> T notNull(T object) signature for immutables:
private final JSCodeModel codeModel;
private final String name;
public FunctionDeclarationImpl(JSCodeModel codeModel, String name,
String[] parameterNames, JSSourceElement[] sourceElements) {
this.codeModel = Validate.notNull(codeModel);
this.name = Validate.notNull(name);
...
}
What are your requirements, actually?
JUnit's assertEquals() and such - good for tests, but can't use in main code
Nothing technically prevents you from using JUnit assetions (and/or Hamcrest matchers) in your main code. Just include the Junit jar in your classpath. It's usually not done but that's more of a convention than any technical limitation.
Java 7 also introduced Objects.requireNotNull(obj, message) and similar methods although not as full featured as JUnit assertions.
but I think if you want to go with a more standardized approach Guava's preconditions is probably best.
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 9 years ago.
Improve this question
In class, we learned about test cases in Java. The professor didn't go over them that well and all the sources I found online weren't helpful as much. I understand that they help to catch any bugs in the porgram, but how does it work? In the example in class, the professor had something like:
#Test
public void test1(){
Webpage n = new Webpage("www.facebook.com");
asssertequals(n.getURL(), "www.facebook.com");
}
Is it okay for getURL and Webpage to be used even though the actual code it hasn't been written yet (she wants us to always write our test cases before we code)? When writing a test case, do we write it as if we have written the whole code before, and test whatever values we think will pass or fail? I have alot of questions, I know.
Also, just to be clear on my understanding, the variable n is set equal to whatever Webpage has between its parentheses, but the new operator creates the object that is supposed to be assigned to n.
Ok so to start of Test cases are especially good and important for larger projects. As this is automated testing it saves developer sh*t loads of time ;).
#Test
public void test1(){
Webpage n = new Webpage("www.facebook.com");
asssertequals(n.getURL(), "www.facebook.com");
}
So first is first:
#Test
this annotations is used so the compiler knows which methods are actual tests.
Webpage n = new Webpage("www.facebook.com");
In here you are simply declaring variable "n" to be url (facebook)
asssertequals(n.getURL(), "www.facebook.com");
This is where the magic happens. assertequals checks if the variable equals to what we expect. If they are equal in this case test passes. but if you had this
Webpage n = new Webpage("www.facebook.co.uk");
asssertequals(n.getURL(), "www.facebook.com");
Then the test will simply fail because expect www.facebook.com but we give co.uk
There are also plenty of other asserts you can use for testing
Also for more info refer to this website: i have found it particularly well organized and written as well as easy to understand
http://www.tutorialspoint.com/junit/junit_overview.htm