Some low level tricks to increase code compactness

This post aims to explore some tricks to increase code compactness on a low level. Some tricks here may drastically reduce code readability(or even screw code performance and/or the AST), so using any tricks here should be backed up with really solid reasons, otherwise doing so may end up being extremely bad practices(like increasing code compactness for the sake of increasing code compactness).

Whether or not you're going to use any such dirty little tricks, you may want to know them as some other scripts may use some of them and sometimes you may have to read some of those scripts.

Example 1

Spoiler
var_a = true if var_bvar_c = false unless var_dIt assigns true to var_a and false to var_c if var_b is a TrueClass and var_d is a FalseClass respectively.

As long as both var_a and var_c only care if they're TrueClass or FalseClass, the below reduced form will work:

var_a ||= var_bvar_c &&= var_dIf var_b is a TrueClass, var_a will be true as now var_a || var_b returns a TrueClass, otherwise the value of var_a will be unchanged as now var_a || var_b returns the "truth value" of var_a; If var_d is a TrueClass, var_c will be unchanged as now var_c && var_d returns the "truth value" of var_c, otherwise var_c will be false as now var_c && var_d returns a FalseClass.

Note: ||= and &&= are so useful that any scripter should at least know what they do.
Example 2

Spoiler
$imported ||= {}$imported[:script] = verIt first creates a hash for $imported if it's not already done, then maps the key :script to value ver in $imported.

The below is 1 way to make it more compact:

($imported ||= {})[:script] = verAs contents inside (), which are $imported ||= {}, are run first, ($imported ||= {}) return $imported. Then the key :script will be mapped to value ver in $imported, making it a reduced form of the original codes.

Note: This reduced form is so common among custom RGSS3 scripts that any scripter should at least know what it does. I don't know if the same applies to RGSS and/or RGSS2 though 🙂
Example 3

Spoiler
obj_1 ? obj_1 : obj_2It returns obj_1 and obj_2 if obj_1 is a TrueClass and FalseClass respectively.

The below is 1 way to make it more compact:

obj_1 || obj_2If obj_1 is a TrueClass, obj_1 will be returned as now obj_1 || obj_2 is sure to return a TrueClass, otherwise obj_2 will be returned to determine what obj_1 || obj_2 will return. So it's a reduced form of the original code.

Note: The default RMVXA Game_Variables has this method:

#-------------------------------------------------------------------------- # * Get Variable #-------------------------------------------------------------------------- def [](variable_id) @data[variable_id] || 0 endWhich uses this reduction trick.
Example 4

Spoiler
a += bexpr_1 if a > cIt first increases a by b, then runs expr_1 if a is greater than c.

The below is 1 way to make it more compact:

expr_1 if (a += > cAs contents inside (), which are (a += b ), are run first, (a += b ) returns the new value of a. The that new value of a will be checked if it's greater than c to determine if expr_1 should be run, making it a reduced form of the original codes.
Example 5

Spoiler
a = def_1def_2(a)def_3(a)It first assigns the value returned by def_1 to a, then passes a as the argument of def_2 and def_3.

The below is 1 way to make it more compact:

def_2(a = def_1)def_3(a)As the passed arguments are first run before running the methods passing them, a = def_1 is run before calling def_2. As a still exists after calling def_2, when calling def_3, a still holds that value returned by def_1. So it's a reduced form of the original codes.
Example 6

Spoiler
if expr_1 expr_2 expr_3endIt runs expr_2 and expr_3 if expr_1 returns a TrueClass.

As long as expr_2 always returns a TrueClass, the below reduced form will work:

expr_3 if expr_1 && expr_2If expr_1 returns a FalseClass, both expr_2 and expr_3 won't be run as expr_1 && expr_2 are sure to return a FalseClass; If expr_1 returns a TrueClass, expr_2 will be run to determine what expr_1 && expr_2 will return. As expr_2 always return a TrueClass, expr_1 && expr_2 will also return a TrueClass, causing expr_3 to be run.
Example 7

Spoiler
expr_1expr_3 if expr_2First expr_1 is run, then expr_3 will be run if expr_2 returns a TrueClass.

As long as expr_1 always returns a TrueClass, the below reduced form will work:

expr_3 if expr_1 && expr_2First, expr_1 will always be run, causing expr_2 to be run as expr_1 always returns a TrueClass. Then expr_3 will be run if expr_2 returns a TrueClass as now expr_1 && expr_2 returns a TrueClass; Similarly, expr_3 won't be run if expr_2 returns a FalseClass as now expr_1 && expr_2 returns a FalseClass.

As long as expr_1 always returns a FalseClass, the below reduced form will work:

expr_3 if expr_1 || expr_2First, expr_1 will always be run, causing expr_2 to be run as expr_1 always returns a FalseClass. Then expr_3 will be run if expr_2 returns a TrueClass as now expr_1 && expr_2 returns a TrueClass; Similarly, expr_3 won't be run if expr_2 returns a FalseClass as now expr_1 && expr_2 returns a FalseClass.
Example 8

Spoiler
old_var = varvar += var_incrementvar_change = var != old_varIt first uses old_var to store the old value or var, then adds var by var_increment, and finally assigns var_change as the truth value of whether the new value of var is different from its old value.

The below is 1 way to make it more compact:

var_change = var != (var += var_increment)First, var != (var += var_increment) is run, and the left hand side, var, returns the old value of var, while the right hand side, (var += var_increment), returns the new value of var, causing the whole check to be checking if the old value of var is different from its new value. Then, the result of the check will be assigned to var_change, making it a reduced form of the original codes.

Note: This reduced form uses 1 less variable as well.
Example 9

Spoiler
@obj = obj@boolean = trueIt assigns obj to @obj and true to @boolean.

As long as obj is always a TrueClass and @boolean always only cares if it stores a TrueClass or FalseClass, the below reduced form will work:

@boolean = @obj = objIt's because now obj, which is always a TrueClass, is assigned to @boolean, making it a TrueClass.
Again, using any of these tricks should be backed up with very, very solid reasons, or the increased code compactness could be outweighed by far more important factors.

What do you think about code compactness in general? What do you think about these dirty little code reduction tricks? Do you have more such tricks to share here?

Also, feel free to correct me if I made any mistake 😀

Edit 1: The original Example 1 is wrong. It only works when both a and c only care if they're TrueClass or FalseClass. Thanks Galenmereth(#6) for pointing that out 🙂

Edit 2: The edited Example 1 is still not precise enough. All a, b, c and d are just variables and I should've stated that explicitly. Now they've changed to be var_a, var_b, var_c and var_d respectively. Thanks KilloZapit(#5 in the VXAN version of this topic) for pointing that out 😀
For others reading this, I just want to expand on what DoubleX said in the opening post:

Code readability needs to take precedent when it can. Things become different when you are trying to maximize performance (So, sure, if this is being ran for every event every frame), but in general saving one line of code is not worth it.
 
Look at example 7. Although expr_3 if expr_1 || expr_2 does run expr_1, and then expr_3 only if expr_2, but that's not what that statement means. And this means that when some programmer who isn't you is trying to write their cool little addon to your script or program they will see something which says:

deal_damage(10) if spend_ammo() && attack_hits()And will think to themselves "Oh, I see, if there is not sufficient ammo for the weapon it won't fire", when all "Spend Ammo" does is remove the ammo from the inventory.

So we hinder fellow scripters from supporting code (And make working in a team a lot more difficult), just so we can save a few nanoseconds of runtime and a line of code. As I said, certainly good tricks to know, but far from the most important thing to keep in mind.

Hope none of that came across as agressive, just trying to avoid someone using these 100% of the time and having entirely unreadable code.

/Kai ♫
Similar note: For example 5, if you've reached this point in trying to make your code more compact, would you not be as well condensing it even further into

def_3(a = def_2(a = def_1))

?
Why not compact your whole code by replacing every line break with a semicolon?
Similar note: For example 5, if you've reached this point in trying to make your code more compact, would you not be as well condensing it even further into

def_3(a = def_2(a = def_1))

?
Expanding your code should end up with this:

a = def_1a = def_2(a)def_3(a)But yeah, the level of compactness in Example 5, unless backed up with solid reasons in particular use cases, can just be bad practice(compactness for the sake of compactness).

1 possible solid reason in some use cases is to obfuscate the scripts to increase the cost and difficulty of deciphering it to reduce the chance of subtle plagiarisms. Of course blatant plagiarisms won't be hindered by this, and scripters will only obfuscate the released version while the private version will still have excellent readability  🙂

P.S.: A better way of obfuscations is to use cryptic variable, method and class names. But those ill-compacted code can also obfuscate scripts, and both ways can be used together to make the codes even more cryptic 😀
Ok so there's a lot of problems with the original post here which I need to address first, and this is important:

Example 1:

Spoiler
a = true if bis not the same as

a ||= bWhy is this? "||=" sets variable a to the value of variable b only if variable a returns a "false" value or is undefined. Meanwhile, "a = true if b" sets variable a to true if variable b evaluates to true. These two are completely different.
Example 2 is fine.

Just be careful about a lot of brackets/parentheses/curly brackets chained in sequence on one line; it gets very unreadable very fast. While the example here is ok, I'd say any more than that warrants a multiline approach. It has absolutely no measurable impact on performance, either.

Example 3:

Spoiler
This has two different uses. You wouldn't use the first line where you'd use the second. Here's how you'd use the ? modifier:

a = b ? c : dWhen setting variable a, you check if variable b evaluates to true; if it does, you set variable a to the value of variable c. If not, you set variable a to the value of variable d.
Example 4:

Spoiler
expr_1 if (a += > cI don't consider this good code practice, for the simple reason that you're setting a variable inside a conditional check. The decrease of one line of code makes this way more error prone. If you want to increase variable a by the value of variable b, the first example is way more readable and concise. If you want to only check if a + b > c, then it's less error prone to just write it as such:

expr_1 if (a + > c
Example 5:

You're setting yourself up for a lot of potential headaches later down the line if you do this. While method chaining is often used in Ruby and to great effect, setting a variable to the return value of a method within the argument space of another method is not very readable and error prone. I would not recommend making that a habit whatsoever.

Example 6:

Spoiler
if expr_1 expr_2 expr_3endSurely the intended behavior of this conditional check is to run both expr_2 and expr_3 if expr_1 is true, right? This is readable and makes sense right away. But this:

expr_3 if expr_1 && expr_2This runs expr_3 if expr_1 and expr_2 return a value that can be evaluated to true. That's not the same logic as the above at all. Actually, in this latter part, if expr_1 returns a value evaluated to true, it also runs expr_2, but potentially not expr_3 if expr_2 returns a false value. So these are not the same. It's not bad form, but it's not the same as the first example. I know you said "if expr_2 always returns a true value", but then why confuse readers of your code by checking for expr_2's value at all? The first example is much more readable, in that case. And again, there's no performance gain anyway.
Example 7:

Just like example 6, the first example in this one is entirely different than the others...

Example 8: This one I agree with.

Example 9: This one is fine too.

---

When it comes to code compactness, in general the only question you should ask yourself is "does this make the code easier or harder to read when I come back to it after a month of not working on it?". The wonderful thing about Ruby's expressiveness is that you can reduce the need for comments to a much higher degree by having the ability to make each line of code more self-explainable than most other languages. Code compactness can often help with readability, but when it doesn't it's a waste of time. It hardly improves performance in any measurable way in almost all instances, and if it also confuses the reader of the code (or just makes it hard to figure out what's going on), it's a bad idea.

It's also important to really understand what all the different parts of the language actually do before you attempt to compact your code.
Ok so there's a lot of problems with the original post here which I need to address first, and this is important:

Example 1:

Spoiler
a = true if bis not the same as

a ||= bWhy is this? "||=" sets variable a to the value of variable b only if variable a returns a "false" value or is undefined. Meanwhile, "a = true if b" sets variable a to true if variable b evaluates to true. These two are completely different.
Spoiler
Example 2 is fine.

Just be careful about a lot of brackets/parentheses/curly brackets chained in sequence on one line; it gets very unreadable very fast. While the example here is ok, I'd say any more than that warrants a multiline approach. It has absolutely no measurable impact on performance, either.

Example 3:

This has two different uses. You wouldn't use the first line where you'd use the second. Here's how you'd use the ? modifier:

a = b ? c : dWhen setting variable a, you check if variable b evaluates to true; if it does, you set variable a to the value of variable c. If not, you set variable a to the value of variable d.
Example 4:

Spoiler
expr_1 if (a += > cI don't consider this good code practice, for the simple reason that you're setting a variable inside a conditional check. The decrease of one line of code makes this way more error prone. If you want to increase variable a by the value of variable b, the first example is way more readable and concise. If you want to only check if a + b > c, then it's less error prone to just write it as such:

expr_1 if (a + > c
Example 5:

You're setting yourself up for a lot of potential headaches later down the line if you do this. While method chaining is often used in Ruby and to great effect, setting a variable to the return value of a method within the argument space of another method is not very readable and error prone. I would not recommend making that a habit whatsoever.

Example 6:

Spoiler
if expr_1 expr_2 expr_3endSurely the intended behavior of this conditional check is to run both expr_2 and expr_3 if expr_1 is true, right? This is readable and makes sense right away. But this:

expr_3 if expr_1 && expr_2This runs expr_3 if expr_1 and expr_2 return a value that can be evaluated to true. That's not the same logic as the above at all. Actually, in this latter part, if expr_1 returns a value evaluated to true, it also runs expr_2, but potentially not expr_3 if expr_2 returns a false value. So these are not the same. It's not bad form, but it's not the same as the first example. I know you said "if expr_2 always returns a true value", but then why confuse readers of your code by checking for expr_2's value at all? The first example is much more readable, in that case. And again, there's no performance gain anyway.
Example 7:

Just like example 6, the first example in this one is entirely different than the others...

Example 8: This one I agree with.

Example 9: This one is fine too.

---

When it comes to code compactness, in general the only question you should ask yourself is "does this make the code easier or harder to read when I come back to it after a month of not working on it?". The wonderful thing about Ruby's expressiveness is that you can reduce the need for comments to a much higher degree by having the ability to make each line of code more self-explainable than most other languages. Code compactness can often help with readability, but when it doesn't it's a waste of time. It hardly improves performance in any measurable way in almost all instances, and if it also confuses the reader of the code (or just makes it hard to figure out what's going on), it's a bad idea.

It's also important to really understand what all the different parts of the language actually do before you attempt to compact your code.

You're right on Example 1, I forgot to mention both a and c only care if they're TrueClass or FalseClass. I just fixed that 🙂

So the key of using Example 1 is whether both a and c are crystal clear that they only care if they're TrueClass or FalseClass. If that's the case(like the variable is named @is_visible), I think using it won't hurt readability much(but that doesn't mean it alone is a solid reason of using it); Otherwise it can be used to purposefully obfuscate the released versions(although I think it'd be deciphered quickly).

P.S.: For those not knowing what ||= and/or &&= is, a ||= b is the same as a = a || b and a &&= b is the same as a = a && b.

For Example 3, yeah, that's how ternary operators are meant to be used. Neverthelsss, this does work:

expr_1 ? expr_2 : expr_3And some scripters perfer this over the below one:

if expr_1 expr_2else expr_3endOf course I won't say using ternary operators that way has absolutely no problems though  🙂

Example 4 is, yeah, extremely error prone, as the reduced form has to guarantee (a += b ) will always run just before checking against the value of c. When these facts are forgotten, the codes can easily be screwed 😀

I think Example 5 is situational. Those being familiar with reading(but not necessarily using) this reduction trick should be able to read such codes just fine, while it could be headaches for most of the others. Again, using this reduced form needs to be backed up with very, very solid reasons(and of course users really need to know what they're doing at all times).

Example 6 and 7 will likely kill readability in most cases, as they're irreversible reductions that only work when some conditions are met, making readers reading the reduced form need to know if those conditions are met in order to judge if that's the reduced form of the original codes they actually want to read. Of course, there are some exceptions like this:

expr_3 if (a = false) || expr_2As it's obvious that (a = false) always returns a FalseClass, readers being familiar with reading(but not necessarily using) this reduction trick should be able to read that just fine. Again, it alone doesn't mean it's a solid reason to use this trick.

For those wanting to purposefully obfuscate the released versions, I think this trick will likely work like a charm if the return value of expr_1 itself is cryptic lol

Well, I think I've to stress again that, using any of such reduction tricks should always be backed up with very, very solid reasons. Users should also always know what they're doing.
Example 10

Spoiler
def def_1 if long_expr_1 if long_expr_2 long_expr_3 elsif long_expr_4 long_expr_5 else long_expr_6 end endendAll long_expr_x has roughly 30 characters.

If long_expr_1 returns a FalseClass, no other long_expr_x will run; Otherwise if long_expr_2 returns a TrueClass, only long_expr_3 will run; Otherwise if long_expr_4 returns a TrueClass, only long_expr_5 will run; Otherwise only long_expr_6 will run.

Besides this obvious "reduction" that would exceed the 80 character line limit:

long_expr_1 ? long_expr_2 ? long_expr_3 : long_expr_4 ? long_expr_5 : long_expr_6 : returnThe below is another way to make it more compact:

def def_1 return unless long_expr_1 return long_expr_3 if long_expr_2 return long_expr_5 if long_expr_4 long_expr_6endIt should be obvious and crystal clear that this reduced form does the exact same thing 🙂

Note: This reduction trick can also be used on a (at least)slightly higher level. For instance:

def def_1 some_def_1_codes if long_expr_1 if long_expr_2 long_expr_3 elsif long_expr_4 long_expr_5 else long_expr_6 end end some_other_def_1_codesendThe below is 1 way to make it more "compact":

def def_1 some_def_1_codes def_2 if long_expr_1 some_other_def_1_codesenddef def_2 return long_expr_3 if long_expr_2 return long_expr_5 if long_expr_4 long_expr_6endIf the def_2 contents themselves aren't crystal clear enough and the def_2 name's nicely named, this reduction trick can also increase readability for both the def_2 contents(for using the def_2 name to describe what they does) and the def_1 contents(for hiding lower level contents and showing higher level ones).

In some cases, this reduction trick can increase compatibility as well.

Bear in mind that the added method call does have its costs even though they're mostly just way too trivial to even mean anything in nearly all cases.

Original thread: https://forums.rpgmakerweb.com/threads/some-low-level-tricks-to-increase-code-compactness.41942/