Maximum number of nested conditions allowed - nested

Does anyone knows the limit of nested conditions (I mean conditions under another, several times)? In, let's say, Java and Visual Basic.
I remembered when I was beginning with my developing trace, I make, I think 3 nested conditions in VB 6, and the compiler, just didn't enter the third one, now that I remember I never, knew the maximun nested coditions a language can take.

No limit should exist for a REAL programming language. For VB.NET and Java I would be shocked if there is any limit. The limit would NOT be memory, because we are talking about COMPILE TIME constraints, not executing environment constraints.
This works just find in C#: It should be noted that the compiler might optimize this to not even use the IFs.
static void Main(string[] args)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{
if (true)
{ Console.WriteLine("It works"); }
}
}
}
}
}
}
}
}
}
}
}
}
}
}
This should not be optimized too much:
static void Main(string[] args)
{
if (DateTime.Now.Month == 1)
{
if (DateTime.Now.Year == 2011)
{
if (DateTime.Now.Month == 1)
{
if (DateTime.Now.Year == 2011)
{
if (DateTime.Now.Month == 1)
{
if (DateTime.Now.Year == 2011)
{
if (DateTime.Now.Month == 1)
{
if (DateTime.Now.Year == 2011)
{
if (DateTime.Now.Month == 1)
{
if (DateTime.Now.Year == 2011)
{
if (DateTime.Now.Month == 1)
{
if (DateTime.Now.Year == 2011)
{
if (DateTime.Now.Month == 1)
{
if (DateTime.Now.Year == 2011)
{ Console.WriteLine("It works"); }
}
}
}
}
}
}
}
}
}
}
}
}
}
Console.ReadKey();
}

I agree with most of the people here that there is no limit on writing the if blocks. But there is a max limit on the java method size. I believe its 64K.

If you mean nested if blocks then there is no theoretical limit. The only bound is the available disk space to store the source code and/or compiled code. There may also be a runtime limit if each block generates a new stack frame, but again that is just a memory limit.
The only explanation for your empirical result of 3 is either an error in programming or an error in interpreting the results.

I must agree that the limit is purely based on memory limit. If you reached it, I would expect that you would reach some kind of stack overflow limit, however I doubt there is a possibility that you would reach this limit.
I could not find a source of reference to back this up, but a quick test of 40+ nested if statements compiled and ran fine.

The limit to the number of nested conditionals will almost certainly be based upon the size of the compiler's stack and data structures, and not anything to do with the run-time environment except possibly in cases where the code space of the target environment is severely constrained relative to the memory available to the compiler (e.g. using a modern PC to compile a program for a small microcontroller with 512 bytes of flash). Note that no RAM (beyond any used to store the code itself) is required at run-time to evaluate a deeply-nested combination of logical operators, other than whatever would be required by the most complex term thereof (i.e. memory required to compute '(foo() || bar()) && boz()' is the largest of the memory required to compute foo(), bar(), or boz()).
In practical terms, there is no way one would reach a limit using a modern compiler on a modern machine, unless one were writing a "program" for the specific purpose of exceeding it (I'd expect the limit would probably be between 1,000 and 1,000,000 levels of nesting, but even if it's "only" 1,000 there's no reason to nest things that deep).

Logically I would think that the limit would be based on the memory available to the application in Java.

Related

Should the variable value be checked before assigning?

I know this might sound like a silly question but I'm curious should I check my variable value before assigning?
like for example if I'm flipping my skin (Node2D composed of sprite & raycast) based on direction (Vector2) :
func _process(delta):
...
if(direction.x>0):
skin.scale.x=1
elif(direction.x<0):
skin.scale.x=-1
#OR
if(direction.x>0):
if(skin.scale.x!=1):
skin.scale.x=1
elif(direction.x<0):
if(skin.scale.x!=-1):
skin.scale.x=-1
would the skin scale be altered every _process hence consuming more CPU usage
OR
if the value is same will it be ignored?
First of all, given that this is GDScript, so the number of lines will be a performance factor.
We will look at the C++ side…
But before that… Be aware that GDScript does some trickery with properties.
When you say skin.scale Godot will call get_scale on the skin object, which returns a Vector2. And Vector2 is a value type. That Vector2 is not the scale that the object has, but a copy, an snapshot of the value. So, in virtually any other language skin.scale.x=1 is modifying the Vector2 and would have no effect on the scale of the object. Meaning that you should do this:
skin.scale = Vector2(skin.scale.x + 1, skin.scale.y)
Or this:
var skin_scale = skin.scale
skin_scale.x += 1
skin.scale = skin_scale
Which I bet people using C# would find familiar.
But you don't need to do that in GDScript. Godot will call set_scale, which is what most people expect. It is a feature!
So, you set scale, and Godot will call set_scale:
void Node2D::set_scale(const Size2 &p_scale) {
if (_xform_dirty) {
((Node2D *)this)->_update_xform_values();
}
_scale = p_scale;
// Avoid having 0 scale values, can lead to errors in physics and rendering.
if (Math::is_zero_approx(_scale.x)) {
_scale.x = CMP_EPSILON;
}
if (Math::is_zero_approx(_scale.y)) {
_scale.y = CMP_EPSILON;
}
_update_transform();
_change_notify("scale");
}
The method _change_notify only does something in the editor. It is the Godot 3.x instrumentation for undo/redo et.al.
And set_scale will call _update_transform:
void Node2D::_update_transform() {
_mat.set_rotation_and_scale(angle, _scale);
_mat.elements[2] = pos;
VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), _mat);
if (!is_inside_tree()) {
return;
}
_notify_transform();
}
Which, as you can see, will update the Transform2D of the Node2D (_mat). Then it is off to the VisualServer.
And then to _notify_transform. Which is what propagates the change in the scene tree. It is also what calls notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED) if you have enabled it with set_notify_transform. It looks like this (this is from "canvas_item.h"):
_FORCE_INLINE_ void _notify_transform() {
if (!is_inside_tree()) {
return;
}
_notify_transform(this);
if (!block_transform_notify && notify_local_transform) {
notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
}
}
And you can see it delegates to another _notify_transform that looks like this (this is from "canvas_item.cpp"):
void CanvasItem::_notify_transform(CanvasItem *p_node) {
/* This check exists to avoid re-propagating the transform
* notification down the tree on dirty nodes. It provides
* optimization by avoiding redundancy (nodes are dirty, will get the
* notification anyway).
*/
if (/*p_node->xform_change.in_list() &&*/ p_node->global_invalid) {
return; //nothing to do
}
p_node->global_invalid = true;
if (p_node->notify_transform && !p_node->xform_change.in_list()) {
if (!p_node->block_transform_notify) {
if (p_node->is_inside_tree()) {
get_tree()->xform_change_list.add(&p_node->xform_change);
}
}
}
for (CanvasItem *ci : p_node->children_items) {
if (ci->top_level) {
continue;
}
_notify_transform(ci);
}
}
So, no. There is no check to ignore the change if the value is the same.
However, it is worth noting that Godot invalidates the global transform instead of computing it right away (global_invalid). This is does not make multiple updates to the transform in the same frame free, but it makes them cheaper than otherwise.
I also remind you that looking at the source code is no replacement for using a profiler.
Should you check? Perhaps… If there are many children that need to be updated the extra lines are likely cheap enough. If in doubt: measure with a profiler.

Jacoco flagging "StringBuilder" (and other classes) as partially covered [duplicate]

I have a Groovy class with a single static method:
class ResponseUtil {
static String FormatBigDecimalForUI (BigDecimal value){
(value == null || value <= 0) ? '' : roundHalfEven(value)
}
}
It has a test case or few:
#Test
void shouldFormatValidValue () {
assert '1.8' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(1.7992311))
assert '0.9' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(0.872342))
}
#Test
void shouldFormatMissingValue () {
assert '' == ResponseUtil.FormatBigDecimalForUI(null)
}
#Test
void shouldFormatInvalidValue () {
assert '' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(0))
assert '' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(0.0))
assert '' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(-1.0))
}
This results in 6/12 branches covered according to Sonar/JaCoCo:
So I've changed the code to be more...verbose. I don't think the original code is "too clever" or anything like that, but I made it more explicit and clearer. So, here it is:
static String FormatBigDecimalForUI (BigDecimal value) {
if (value == null) {
''
} else if (value <= 0) {
''
} else {
roundHalfEven(value)
}
}
And now, without having changed anything else, Sonar/JaCoCo report it to be fully covered:
Why is this the case?
I don't know if it applies to your concrete example, but keep in mind that code coverage tools typically don't work well for alternative JVM languages unless they support them explicitly. This is because virtually all of those languages generate extra byte code that may only get executed in certain cases. For example, Groovy might generate byte code for a slow path and a fast path, and might decide between them automatically, without the user having a say.
The situation might improve with Groovy 3.0, which will be designed around Java invokedynamic, meaning that less "magic" byte code will have to be generated. Meanwhile, I've heard that Clover has explicit Groovy support, although I don't know how up-to-date it is.
So, as it turns out, the Jacoco plugin for Sonar explicitly looks for Java code. I know this, as I debugged through it. It decodes the jacoco exec file and assumes any file is a JavaFile, which it doesn't find, and then says you have no coverage information.
Because of this, I grabbed the source code to the Jacoco plugin (it vanished from their Subversion repository, and never appeared on Github that I could find) and folded it into a new Groovy plugin. My updated one uses Codenarc 0.18.1 (which increases the Narc's from 32 to 305) and recognizes any kind of Jacoco file - the code in the existing plugin is unnecessarily wrong.
The source is here: https://github.com/rvowles/sonar-groovy - just build it and put it in your extensions/plugins directory.

GarbageCollectionNotificationInfo values look invalid

I'm using GarbageCollectionNotificationInfo notifications to track GC events. It's nice, but looks like the output is invalid. I expect that getGcInfo().getMemoryUsageBeforeGc() -> MemoryUsage.getUsed() will report particular segment usage before running current GC.
But it is always equal to getGcInfo().getMemoryUsageAfterGc() from previous notification. What's wrong here?
Here is the I use and it is working :) I mean I get correct numbers both before and after GC.
public synchronized void handleNotification(Notification notification, Object handback) {
if (GARBAGE_COLLECTION_NOTIFICATION.equals(notification.getType())) {
GarbageCollectionNotificationInfo info = from((CompositeData) notification.getUserData());
com.sun.management.GarbageCollectorMXBean mxBean = (com.sun.management.GarbageCollectorMXBean) handback;
GcInfo gcInfo = mxBean.getLastGcInfo();
if (gcInfo != null) {
//use gcInfo.getMemoryUsageBeforeGc() and gcInfo.getMemoryUsageAfterGc()
}
}
}

Is there a language that breaks out of conditional statements as soon as they become false?

I thought that I had come across this before, but I can't remember when or what language it was.
Basically if I have the following in C#:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond) {
someCondition = false;
continue;
}
// Do Something Else
}
In C# this will break out of the body of the if statement when someCondition changes, meaning that //DO Something Else only gets processed if someCondition doesn't change...
Is there a language that will do the interior if statement checking/continue automatically i.e. be able to write:
someCondition = true
if(someCondition)
{
// Do Something
if(anotherCond){
someCondition = false;
}
// Do Something Else
}
with the same behaviors as the previous? Obviously there are multiple ways to get this behavior in every language conceivable, what I am interested in is if there is a language that by design has this functionality.
Edit: Reduced the examples so hopefully people can see what is happening, when someCondition changes (i.e. the condition that the if statement relied on to begin, we should break out of the remaining if statement. I am not looking for a way to do this in C#, or any particular language, but for a language that does this automatically.
You can create a property in C# that throws an exception on any condition you set, aka truth=true. The exception will break out of the loop to wherever you have your catch.
An example in C#:
public class MyException : Exception { }
public bool truth
{
get { return _truth; }
set
{
_truth = value;
if(value)
throw new MyException();
}
}
bool _truth;
I think you can simulate what you want in C# like so:
void ExecuteWhile( Func<bool> condition,
IEnumerable<Action> executeWhileTrue,
IEnumerable<Action> executeWhileFalse)
{
if (condition())
{
foreach (Action action in executeWhileTrue)
{
action();
if (!condition())
return;
}
}
else
{
foreach (Action action in executeWhileFalse)
{
action();
if (condition())
return;
}
}
}
and then use it as such:
truth = true;
while (true) // loop forever
{
ExecuteWhile( () => truth,
new List<Action> { () => { /* do something that might set truth to false*/},
() => { /* do something else*/}},
new List<Action> { () => { /* do something that might set truth to true*/},
() => { /* do something else*/}});
}
And to answer your question: no, I don't think there is a language with this as a build-in feature.
As far as I understood, the following is wanted:
if (cond) {
A;
B;
C;
}
shall behave as if written thus:
if (cond) {
A;
if (cond) {
B;
if (cond) {
C
}
}
}
IMHO, this would be a silly feature, unlikely to be implemented in any language except maybe in INTERCAL.
Why do I think that?
Well, suppose someone wants to refactor the code and moves B;C to a subroutine.
if (cond) {
A;
BC();
}
subroutine BC() { B;C }
The block - according to our feature - will mean as before:
if (cond) {
A;
if (cond) BC();
}
But what about our subroutine? The language designer has 2 choices here:
Treat the call BC() as atomic, i.e. in the subroutine, the
condition cond is not checked before statement C. This would mean
such a simple refactoring would change the meaning of the program
drastically.
Somehow pass the information that every statement must be guarded
with cond to the subroutine so that the behaviour of our block remains
unchanged. This, of course, leads to the silly situation that the
behaviour of any subroutine would depend upon the context it was
called in. A subroutine with n atomic statements would have n possible ways to behave even if it had no arguments and would not use non local mutable state explicitely, depending on how many of the statements would be actually executed. (Note that nowadays the trend is to minimize the most often harmful effects of shared non-local state. OO languages do it with encapsulation, FP languages by banning mutable state altogether.)
In any case, no matter how the language designer decides, we would have a feature that is the direct contradiction of the principle of the least surprise. It is clear that programs in such a language would be utterly hard to maintain.
If you broke you big bunch if/else statements into succinct little methods which tested each little piece of the puzzle, you could rely on the compilers short circuit boolean evaluation
I'm not sure if that helps as your example is a big vague. You don't say if you're doing any processing or if it's just a bunch of checks. Either way, breaking your code into smaller methods may help you out.
You can use a do..while loop:
do
{
} while (truth == true);
thats if i've understood correctly!
You say while true... but while what is true. I would think your loop will run infinitely regardless of the language used. Assuming true will be a real condition... I would say just set the exit condition in one of the if blocks. You question is a bit hard to understand. Also the continue is unnecessary.

Best pattern for simulating "continue" in Groovy closure

It seems that Groovy does not support break and continue from within a closure. What is the best way to simulate this?
revs.eachLine { line ->
if (line ==~ /-{28}/) {
// continue to next line...
}
}
You can only support continue cleanly, not break. Especially with stuff like eachLine and each. The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method. Here's how to support continue --
Best approach (assuming you don't need the resulting value).
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return // returns from the closure
}
}
If your sample really is that simple, this is good for readability.
revs.eachLine { line ->
if (!(line ==~ /-{28}/)) {
// do what you would normally do
}
}
another option, simulates what a continue would normally do at a bytecode level.
revs.eachLine { line ->
while (true) {
if (line ==~ /-{28}/) {
break
}
// rest of normal code
break
}
}
One possible way to support break is via exceptions:
try {
revs.eachLine { line ->
if (line ==~ /-{28}/) {
throw new Exception("Break")
}
}
} catch (Exception e) { } // just drop the exception
You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.
Closures cannot break or continue because they are not loop/iteration constructs. Instead they are tools used to process/interpret/handle iterative logic. You can ignore given iterations by simply returning from the closure without processing as in:
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return
}
}
Break support does not happen at the closure level but instead is implied by the semantics of the method call accepted the closure. In short that means instead of calling "each" on something like a collection which is intended to process the entire collection you should call find which will process until a certain condition is met. Most (all?) times you feel the need to break from a closure what you really want to do is find a specific condition during your iteration which makes the find method match not only your logical needs but also your intention. Sadly some of the API lack support for a find method... File for example. It's possible that all the time spent arguing wether the language should include break/continue could have been well spent adding the find method to these neglected areas. Something like firstDirMatching(Closure c) or findLineMatching(Closure c) would go a long way and answer 99+% of the "why can't I break from...?" questions that pop up in the mailing lists. That said, it is trivial to add these methods yourself via MetaClass or Categories.
class FileSupport {
public static String findLineMatching(File f, Closure c) {
f.withInputStream {
def r = new BufferedReader(new InputStreamReader(it))
for(def l = r.readLine(); null!=l; l = r.readLine())
if(c.call(l)) return l
return null
}
}
}
using(FileSupport) { new File("/home/me/some.txt").findLineMatching { line ==~ /-{28}/ }
Other hacks involving exceptions and other magic may work but introduce extra overhead in some situations and convolute the readability in others. The true answer is to look at your code and ask if you are truly iterating or searching instead.
If you pre-create a static Exception object in Java and then throw the (static) exception from inside a closure, the run-time cost is minimal. The real cost is incurred in creating the exception, not in throwing it. According to Martin Odersky (inventor of Scala), many JVMs can actually optimize throw instructions to single jumps.
This can be used to simulate a break:
final static BREAK = new Exception();
//...
try {
... { throw BREAK; }
} catch (Exception ex) { /* ignored */ }
Use return to continue and any closure to break.
Example
File content:
1
2
----------------------------
3
4
5
Groovy code:
new FileReader('myfile.txt').any { line ->
if (line =~ /-+/)
return // continue
println line
if (line == "3")
true // break
}
Output:
1
2
3
In this case, you should probably think of the find() method. It stops after the first time the closure passed to it return true.
With rx-java you can transform an iterable in to an observable.
Then you can replace continue with a filter and break with takeWhile
Here is an example:
import rx.Observable
Observable.from(1..100000000000000000)
.filter { it % 2 != 1}
.takeWhile { it<10 }
.forEach {println it}

Resources