Now let's talk about
II. ATB System Code Qualities.
Note that:
- Most of these are unique to ATB system plugins. Instead, they can be applied to most plugins.
The point of this reply is to show how these global knowledge can be applied to ATB system plugins.
-
None of these should be treated as dogmas without thinking about them all beforehand.
Invariants
Spoiler
Definition
From
Wikipedia:
- An
invariant is a condition that can be relied upon to be true during execution of a program, or during some portion of it. It is a
logical assertion that is held to always be true during a certain phase of execution.
In other words, there are 2 types of invariants:
Global Invariants -
Assumptions that are supposed to be always 100% held across the entire codebase under any possible circumstances
Contextual Invariants -
Assumptions that are supposed to be always 100% held under some situations involving some parts of the codebase
For example, the below is a
Global Invariant:
-
The ATB Wait Condition must be run before running the ATB Frame Update at the exact same frame
Because:
1. It must be always 100% held, otherwise the
ATB Frame Update might be run at a frame before running the
ATB Wait Condition at the same frame, with the latter informing that the former shouldn't run at that frame.
2. It applies to the entire codebase, as everything unique to ATB systems(except the
ATB Wait Condition itself of course) must be triggered by the
ATB Frame Update.
3. It applies to any possible circumstances, as it's just outright impossible for the
ATB Frame Update to be always run per frame(even when messages are showing, which can lead to nontrivial bugs), and the only thing stopping the ATB Frame Update from running per frame is
ATB Wait Condition.
Whereas the below is a
Contextual Invariant:
-
The party escape attempt must be disabled when an action invoked by or targeting a party member's executing
Because:
1. It must always be 100% held, otherwise the action invoker or target might become a hidden battler, which can sometimes crash the game
2. It only applies when the
ATB Wait Condition won't be met just because of some actors being inputable, as players won't be able to input anything, including the party escape attempt, when an action's executing in that case
3. It only applies to the party escape command parts of the codebase, as it's the only part that can trigger a party escape attempt, and normally, the rest of the codebase has nothing to do with party escapes
Interinvariant Dependency
Spoiler
A Broken Invariant is one that isn't indeed always 100% held for its designated scopes.
For example:
- A Broken Global Invariant is one that isn't indeed always 100% held across the entire codebase under any possible circumstances.
- A Broken Contextual Invariant is one that isn't indeed always 100% held under all the situations involving all those parts of the codebase that are supposed to have it being always 100% held.
Invariant A is said to be depending on invariant B if the former will become a Broken Invariant when the latter becomes one.
The codebase is said to have Interinvariant Dependency if it's any such invariants.
For example, the below Global Invariant:
- The ATB Frame Update can only be run at a frame if the ATB Wait Condition lets it be run at the exact same frame
Depends on te below Global Invariant(Which is already mentioned):
- The ATB Wait Condition must be run before running the ATB Frame Update at the exact same frame
Because:
- The former invariant can be rephrased as The ATB Frame Update must not be run at a frame if the ATB Wait Condition doesn't let it be run at the exact same frame
- The only way for the ATB Wait Condition to stop an ATB Frame Update from being run is to return a result notifying the codebase that the latter won't be run.
- The only way for the ATB Wait Condition to return a result is to be called.
- For that result to be able to notify the codebase that the latter won't be run, that result must be informed to the codebase before the latter's run.
- But if the latter invariant becomes a Broken Invariant, the ATB Wait Condition might be run after running the ATB Frame Update at the exact same frame.
- So the codebase might not be informed by the result returned by the ATB Wait Condition before the ATB Frame Update is being run.
- It means that the codebase might not be able to stop the ATB Frame Update from being run even when the ATB Wait Condition doesn't let it be run.
Therefore the former invariant will become a Broken Invariant if the latter invariant becomes one.
On a side note: The above example implies that every ATB system always has at least 1 Interinvariant Dependencies.
Correctness
Spoiler
Behavioral Requirements
Simply put, a correct codebase is one having no nontrivial bugs, so correctness of a codebase is a measure of the number of nontrivial bugs of the codebase, and the impacts of each of them to the codebase.
From
Wikipedia:
- A
software bug is an error, flaw,
failure or
fault in a computer program or
system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways.
To avoid
circular definitions, the definition of a nontrivial bug can be simplified as:
A nontrivial bug in a codebase is an unexpected result and/or intended behavior that has nontrivial inconsistencies with the behavioral requirements of the codebase.
Therefore, to measure the correctness of a codebase, one must first know all the behavioral requirements of that codebase.
Usually, many, albeit hardly all, of the behavioral requirements of a codebase can already be found just by reading the user configuration and documentation parts of that codebase.
For example, the below are some behavioral requirements of
DoubleX RMMV Minimalized ATB(MATB; same below):
* @param max_turn_unit
* @desc Sets the maximum battle turn clock unit as max_turn_unit
* max_turn_unit must return a Number and should return a positive one
* @default 5
*
* @param actor_name_w
* @desc Sets the maximum width allocated for actor name display on the status
* window as actor_name_w
* actor_name_w must return a positive Number
* @default 123
*
* @param actor_icon_ox
* @desc Sets the actor icon display area x offset relative to the actor name
* display area on the status window as actor_icon_ox
* actor_icon_ox must return a positive Number
* @default 6
*
* @param hp_bar_ox
* @desc Sets the actor hp bar display area x offset relative to the actor icon
* display area on the status window as hp_bar_ox
* hp_bar_ox must return a positive Number
* @default 6
*
* @param hp_bar_w
* @desc Sets the maximum width allocated for actor hp bar display on the status
* window as hp_bar_w
* hp_bar_w must return a positive Number
* @default 87
*
* @param mp_bar_ox
* @desc Sets the actor mp bar display area x offset relative to the actor hp
* bar display area on the status window as mp_bar_ox
* mp_bar_ox must return a positive Number
* @default 6
*
* @param mp_bar_w
* @desc Sets the maximum width allocated for actor mp bar display on the status
* window as mp_bar_w
* mp_bar_w must return a positive Number
* @default 87
*
* @param tp_bar_ox
* @desc Sets the actor tp bar display area x offset relative to the actor mp
* bar display area on the status window as tp_bar_ox
* tp_bar_ox must return a positive Number
* @default 6
*
* @param tp_bar_w
* @desc Sets the maximum width allocated for actor tp bar display on the status
* window as tp_bar_w
* tp_bar_w must return a positive Number
* @default 87
*
* @param atb_bar_ox
* @desc Sets the actor atb bar display area x offset relative to the actor
* mp/tp bar display area on the status window as atb_bar_ox
* atb_bar_ox must return a positive Number
* @default 6
*
* @param atb_bar_w
* @desc Sets the maximum width allocated for actor atb bar display on the
* status window as atb_bar_w
* atb_bar_w must return a positive Number
* @default 87
*
* @param atb_c1
* @desc Sets the 1st atb bar color as text color atb_c1
* atb_c1 must return a valid text color code
* atb_c1 should return the same value during the same battle to ensure
* proper atb bar color displays
* @default 7
*
* @param atb_c2
* @desc Sets the 2nd atb bar color as text color atb_c2
* atb_c2 must return a valid text color code
* atb_c2 should return the same value during the same battle to ensure
* proper atb bar color displays
* @default 8
Code:
* # Configuration manipulations
* 1. $gameSystem.matb.param
* - Returns the value of param listed in the plugin manager
* 2. $gameSystem.matb.param = val
* - Sets the value of param listed in the plugin manager as val
* - All $gameSystem.matb.param changes will be saved
* # Battler manipulations
* 1. matb_val
* - Returns the battler's atb value
* 2. reset_matb()
* - Clears all battler's actions and resets the battler's atb value
Bug Hunting
Spoiler
As mentioned, correctness is a measure of both the number of nontrivial bugs and the impacts of each of those bugs.
From my experience and observation as both a plugin developer and user, even 1 serious bug generally means a lot more than tons of barely nontrivial bugs combined.
Also, applying the Pareto principle, as stated by
Wikipedia, to the correctness of the codebase:
- The
Pareto principle (also known as the
80–20 rule, the
law of the vital few, and the
principle of factor sparsity)
[1] states that, for many events, roughly 80% of the effects come from 20% of the causes.
For many plugins, roughly 80% of the compromise of the behavioral requirements come from 20% of the nontrivial bugs.
On the other hand, sometimes invariant A becoming a
Broken Invariant is the sole reason for the existence of bug A, and invariant B becoming a
Broken Invariant is the sole reason for the existence of bug B.
If invariant B becoming a
Broken Invariant is also the sole reason for invariant A to become a
Broken Invariant, then fixing bug B will automatically fix bug A as well, because:
- The only way to fix bug B is to fix invariant B(by making it not a
Broken Invariant anymore; same below).
- This will lead to invariant A also being fixed.
- This means that bug A will be fixed too.
This can lead to an illusion that, if bug A is an extremely serious bug but bug B is just a barely nontrivial one, then fixing bug B first will actually be more productive than fixing bug A first, as the former will directly lead to the latter, while doing the latter first can demand a lot more costs.
But luck asides, the only way to know that fixing bug B will lead to fixing bug A is to investigate the root cause of bug A. So we'll still want to focus on the known major bugs first.
Of course, it doesn't mean that barely nontrivial bugs can be safely ignored, as they can still hurt the codebase, and sometimes, they can become
technical debts that can eventually lead to technical bankruptcy.
Usually, the major bugs of an ATB system comes from its core functionalities, like:
-
ATB Wait Condition
-
ATB Frame Update
-
Battle Turn Clock
-
Battler ATB Clock
Invariants also play an important role in correctness, and the below definition will come into handy:
A Nontrivial Invariant is one that, once become a Broken Invariant, will lead to nontrivial bugs.
So it's useful to hunt for all Nontrivial Invariants of a codebase and check whether any of them are Broken Invariants in order to hunt for bugs and fix them.
On a side note: All the aforementioned invariants are
Nontrivial Invariants.
Robustness
Spoiler
Definition
From
Wikipedia:
- In
computer science,
robustness is the ability of a computer system to cope with errors during execution
[1][2] and cope with erroneous input.
For users, usually the most important measure of such ability is the correctness of the codebase under such cases.
In most cases, the codebase can become somehow incorrect in this manner due to some
Nontrivial Invariants becoming
Broken Invariants.
To generalize all such cases, a codebase will have a certain average chance for at least 1
Nontrivial Invariants to become
Broken Invariants.
Also, as some
Nontrivial Invariants will lead to more serious bugs than others when becoming
Broken invariants, the seriousness of such impacts also has to be measured.
This lead to the below simplified measure of robustness:
The robustness of a codebase can be roughly measured by the chance of its Nontrivial Invariants to become Broken Invariants and the seriousness of the manifested nontrivial bugs.
Using this simplified measurement:
1.
A 100% robust codebase is one that is always 100% correct under any possible circumstances.
2.
A 0% robust codebase is one that is never 100% correct under any possible circumstances.
3.
A x% robust codebase, where 0 < x < 100, is one that is always 100% correct under some circumstances but not always 100% correct under some other circumstances.
From my experience and observation:
1. It's simply unrealistic, if even possible at all, to have a 100% robustness codebase.
2. A x% robustness codebase, where 0 < x < 100, is always 100% correct under its targeted situations but not always 100% correct when there are compatibility issues with some other codebases.
3. Almost no one can accurately measure that value of x, although we can still have a vague impression of how robust a codebase is.
So to increase robustness, you'll want to refactor the codebase so that it'll need less and less Nontrivial Invariants, especially those that are likely to become Broken Invariants, those having Interinvariant Dependencies, and/or will really wreck havoc when they do, while still preserving correctness, and preferably all the other important code qualities.
Fault Isolation
Spoiler
While it's impractical to have a codebase that will never have any fault under any possible circumstances, we still don't want a single fault to compromise the whole codebase when it comes.
This is what fault isolation is about - To ensure a fault within a component won't propagate to any other components.
To implement fault isolation, a codebase should be so modular that it's compartmentalized into independent but interrelated components so that no single faulty component can compromise the entire codebase.
Of course, in practice, some faults in some components are simply too severe to be separated from the rest of the codebase.
For instance, if the component implementing the ATB Wait Condition is so faulty that the ATB Wait Condition is always met, the ATB Frame Update will never run, thus compromising the whole ATB system, even when the codebase is so well-written that that faulty component does nothing other than implementing the ATB Wait Condition, no other component does the same job, and the only effect to the other component is whether the ATB Frame Update will be run.
These are some example faults in some example components that can compromise the whole ATB system:
Component implementing ATB Wait Condition
- The ATB Wait Condition is always met, leading to the ATB Frame Update never being run
- The ATB Wait Condition is always not met, leading to crashes when displaying messages
Component implementing ATB Frame Update
- No battler's Battler ATB Clock are ever updated, leading to no battler being able to do anything
Component implementing Battler ATB Clock
- The Battler ATB Clock is always reset to be completely empty, leading to no battler being able to do anything
Therefore, it's useful to mark all such possible faults in all such potential components, and keep a close eye to them, in order to prevent them from being real issues and fix them immediately in case they do.
On a side note: In general, the more InterInvariant Dependencies a codebase have, the less able it can perform fault isolation, as such codebases can have a chain of Broken Invariants with just 1 of them due to the single original fault.
Performance
Spoiler
Memory And Time
When talking about
code performance, it's mainly about memory usage and time spent for executing some operations.
1 using tool to measure code performance is the
big O notation.
Some ways to come up with less performant algorithms demonstrated some usages of the big O notation, and you're highly encouraged and recommended to read that
In RMMV, what most users care about is the time performance, which is directly illustrated by the average and minimum fps.
What we, as RMMV plugin developers, want to void, is writing plugins leading to constant severe lag and fps drop, even on machines barely meeting the RMMV system requirements.
On the other hand, the RMMV minimum requirements on RAM is 2GB, which is quite abundant for most RMMV plugin developers.
At least, from my experience and observation, an ATB system hardly demands so many RAM to impose nontrivial memory usage issues.
So I'll focus mainly on time consumption rather then memory usage when talking about code performance, although the latter won't be completely ignored.
FPS Meter
Spoiler
When optimizing for time performance, we've to measure it, and a meter showing the FPS and/or the number of ms spent on executing operations at a frame will come into handy.
Fortunately, RMMV already has a built in FPS meter, which can be shown by pressing F2, or some other keys doing the same thing(usually implemented by some plugins).
We also know it has 2 modes, with 1 showing the FPS, and 1 showing the number of ms spent on executing operations at a frame.
As RMMV is hardcoded to have 60 FPS(unless the load is too heavy to even achieve this), the conversion from the ms mode to the FPS mode is this:
Number of FPS = 1000 / Math.max(16.666...6, number of ms spent on executing operations at a frame)
On the other hand, when the number of FPS shown by the FPS mode is 60, you won't know the exact number of ms spent on executing operations at a frame, you just know that it must be smaller than 17.
So I personally find the ms mode more useful when measuring the plugin time performance, even although the FPS mode is what most users care more.
Hotspots
Spoiler
From
Wikipedia:
- A
hot spot in
computer science is most usually defined as a region of a
computer program where a high proportion of executed instructions occur or where most time is spent during the program's execution (not necessarily the same thing since some instructions are faster than others).
As few, if any at all, operations unique to ATB systems will demand such a large amount of resources that, even being executed sparsely(absolutely/relatively), will still have a significant impact on code performance, the below simplified definition can be applied to ATB systems instead:
A hotspot in ATB system plugins is a section of code that is run extremely frequently.
From my experience and observation, under this definition, a simplified criterion can be used to judge whether a section of code is a hotspot:
If a section of code is run at least nearly once per frame on average, then it's a hotspot; If a section of code is run no where close by once per frame on average, then it's not a hotspot.
For instance, the below sections of codes are most likely hotspots:
-
ATB Wait Condition
-
ATB Frame Update
-
Battle Turn Clock
-
Battler ATB Clock
Sometimes though, a section of code can run extremely frequently or sparsely on average, and both behaviors can be considered normal and/or common, depending on how the users use the ATB system plugins. This leads to the below definition:
A Potential Hotspot is a section of code that can become a hotspot or not a hotspot depending on normal and/or common use cases.
For instance, Game_Battler.prototype.set_patb_colors is marked as a
Potential Hotspot(PATB Core v101a):
// type: The current atb type
Game_Battler.prototype.set_patb_colors = function(type) {
// New; Potential Hotspot
this._patb_colors[type] = this.set_patb_notes("p" + type + "_colors");
if (this._patb_colors[type]) { return; }
var patb = $gameSystem.patb;
this._patb_colors[type] = [patb[type + "_c1"], patb[type + "_c2"]];
}; // Game_Battler.prototype.set_patb_colors
It's because it'll only be called when Game_Battler.prototype.are_patb_battler_changed returns true with the color notetag change notification flags raised(PATB Core v101a; check
Change Notification Flags for this):
Spoiler
/*----------------------------------------------------------------------------
* Checks if the effective notetag list or any of their values changed
*----------------------------------------------------------------------------*/
// note: The notetags to be checked for changes
Game_Battler.prototype.are_patb_battler_changed = function(note) {
// New; Hotspot
var ch = this._patb_battler_change[note] || this._patb_note_change[note];
this._patb_battler_change[note] = this._patb_note_change[note] = false;
return ch;
}; // Game_Battler.prototype.are_patb_battler_changed
Game_Battler.prototype._patb_battler_change won't return true frequently, and Game_Battler.prototype._patb_note_change will only return true if users use this plugin call(PATB Core v101a):
Spoiler
* 8. patb_note_change.note = true
* - Notifies that the values of at least 1 notetag instance of
* notetag note or the corresponding configuration value has changed
* - Note can be max_atb_val, atb_color or atb_overlay_color,
* referring to <operator max patb val: val>,
* <patb colors: text color 1, text color 2>, and
* <patb overlay colors: text color 1, text color 2> respectively
So Game_Battler.prototype.set_patb_colors will only become a hotspot if the above plugin calls are used extremely frequently, meaning that Game_Battler.prototype.set_patb_colors is a
Potential Hotspot.
The point of marking functions as hotspots and/or Potential Hotspots is to know which functions should optimize for code performance.
You may feel/think that all functions should be optimized, perhaps maximally, for code performance, as it's extremely important for the user experience, especially for ATB systems which demands exceptionally large amount of computing resources.
While it's true in most cases, it's also quite hard to optimize for code performance without sacrificing any other important code qualities, so there's a need to balance and prioritize them(which is too advanced to be covered here), as illustrated by some well-written plugins.
So we'll want to know which sections of code really warrants performance optimizations, and usually most hotspots/Potential Hotspots do.
Reasons To Change
Spoiler
Consider Game_Battler.prototype.update_max_patb_val, which is a hotspot(PATB Core v101a):
/*----------------------------------------------------------------------------
* Rereads the effective max atb val notetag only if its values can change
*----------------------------------------------------------------------------*/
Game_Battler.prototype.update_max_patb_val = function() { // New; Hotspot
if (!this.are_patb_battler_changed("max_patb_val")) { return; }
var f = this._patb_val.atb >= this._max_patb_val;
var max = $gameSystem.patb.max_atb_val;
this._max_patb_val = this.set_multi_patb_notes(max, "max_patb_val");
// Multiplies the difference by 10000 to work with very small max atb value
if (this._max_patb_val < Number.EPSILON * 10000) {
console.log("Max atb value of " + this.name() + " is too small");
}
//
this._max_patb_val_change = true;
if ($gameSystem.patb.atb_fill_code !== "delay") { this.corr_patb(f); }
this.mark_patb_val_change();
}; // Game_Battler.prototype.update_max_patb_val
It checks if the
Maximum ATB Value change notification flag's raised, and reevaluates the
Maximum ATB Value if it does.
As
DoubleX RMMV Popularized ATB Core(PATB Core; same below) lets users change the
Maximum ATB Value per frame, you might think that the plugin should simply reevaluate it per frame to ensure 100% correctness.
However, this could lead to a noticeable, if not significant, constant lag and fps drop, especially if users uses dozens, or even hundreds, of <operator max patb val: val> notetags, as shown by Game_Battler.prototype.set_multi_patb_notes(PATB Core v101a):
Spoiler
/* val: The configuration value as the initial notetag value
* note: The notetag type with its values to be set
*/
Game_Battler.prototype.set_multi_patb_notes = function(val, note) {
// New; Potential Hotspot
// Loosens the coupling among the core, delay, rate and start plugins
this.patb_note_data().forEach(function(type) {
type.forEach(function(data) {
data.meta[note].forEach(function(vals) {
val = this.operate_patb_notes(val, vals[0], vals[1]);
}, this);
}, this);
}, this);
return val;
//
}; // Game_Battler.prototype.set_multi_patb_notes
Where Game_Battler.prototype.patb_note_data is this(PATB Core v101a):
Spoiler
Game_Battler.prototype.patb_note_data = function() {
// v0.00e+; New; Potential Hotspot
// Increases the chance for this plugin to work when the battler's neither
if (this.isEnemy()) {
return [this.states(), [this.enemy()]];
} else if (this.isActor()) {
var d = [this.states()];
d.push(this.equips().filter(function(equip) { return equip; }));
return d.concat([[this.currentClass()], [this.actor()]]);
}
return [this.states()];
//
}; // Game_Battler.prototype.patb_note_data
And Game_Battler.prototype.operate_patb_notes is this(PATB Core v101a):
Spoiler
/* current: The current value to be operated
* operator: The notetag operator
* val: The notetag value to be operated with the current one
*/
Game_Battler.prototype.operate_patb_notes = function(current, operator, val) {
// New; Potential Hotspot
switch (operator) {
case "=": return val;
case "+": return current + val;
case "-": return current - val;
case "*": return current * val;
case "/": return current / val;
case "%": return current % val;
default:
console.log("Invalid operator " + operator + " as notetag values");
return current;
}
}; // Game_Battler.prototype.operate_patb_notes
Instead, we should realize that every change of everything has some reasons behind it, and these reasons are called Reasons To Change.
In this example, there are 3
Reasons To Change:
1. The value of $gameSystem.patb.max_atb_val has changed
2. The effective <operator max patb val: val> notetag list has changed(changed some notetag orderings, added some new notetags, removed some existing notetags)
3. The value of some effective <operator max patb val: val> notetags has changed
As both 1st and 3rd one must be triggered by plugin calls, they can be grouped as 1
Reason To Change: The users have used relevant plugin calls.
On the other hand, the 2nd one is typically triggered by equip/state(with these notetags) add/removal and/or class change/enemy transform, although users can still use plugin calls to explicitly add new notetags to/remove existing notetags to some database items(actor/class/equip/state/enemy). So the 2nd
Reason To Change has to be checked by the plugin implementation itself.
The 1st and 3rd
Reasons To Change will be reflected by the Game_Battler.prototype._patb_note_change part of the
Maximum ATB Value change notification flag, while the 2nd one will be reflected by Game_Battler.prototype._patb_battler_change part as well.
While Game_Battler.prototype._patb_note_change is directly raised by plugin calls meaning it's a deterministic indication that a
Reason To Change is definitely triggered, Game_Battler.prototype._patb_battler_change is raised when Game_Battler.prototype.set_patb_refresh, which is called by Game_Battler.prototype.refresh(and some other functions as well), is called(PATB Core v101a):
Spoiler
Game_Battler.prototype.set_patb_refresh = function() { // New
Object.keys(this._patb_battler_change).forEach(function(note) {
this._patb_battler_change[note] = true;
}, this);
BattleManager.need_patb_refresh = true;
}; // Game_Battler.prototype.set_patb_refresh
When the 2nd
Reason To Change is triggered, Game_Battler.prototype.set_patb_refresh will definitely be called.
On the other hand, just because Game_Battler.prototype.set_patb_refresh is called doesn't mean the 2nd
Reason To Change is triggered.
So the use of Game_Battler.prototype.set_patb_refresh is this:
- When it's called, a
Reason To Change might be triggered; When it's not called, a
Reason To Change is definitely not triggered.
This leads to the below definitions:
A Deterministic Reasons To Change Detector is a component that can accurately tell whether all Reasons To Change it's monitoring have triggered or not triggered.
A Probabilistic Reasons To Change Detector is a component that can accurate tell that all Reasons To Changes it's monitoring have not triggered but can't accurately tell that they've triggered.
At the 1st glance a
Deterministic Reasons To Change Detector seems to be more useful than a
Probabilistic Reasons To Change Detector.
In some cases, however, the latter's more suitable, as sometimes just 1 of the latter can already replace several, and sometimes even dozens, of the former.
For example, Game_Battler.prototype.set_patb_refresh is a
Probabilistic Reasons To Change Detector that can detect all
Reasons To Change the effective <operator max patb val: val> notetag list.
If it's to be replaced by
Deterministic Reasons To Change Detectors, the below ones will be needed:
1. Actor class change detector - Detecting whether the effective <operator max patb val: val> notetag list is indeed changed due to a class change, by checking the effective <operator max patb val: val> notetag list of the old class against that of the new class
2. Actor equip change detector - Detecting whether the effective <operator max patb val: val> notetag list is indeed changed due to an equip change, by checking the effective <operator max patb val: val> notetag list of the old equip against that of the new equip
3. Battler state change detector - Detecting whether the effective <operator max patb val: val> notetag list is indeed changed due to a state change, by checking the effective <operator max patb val: val> notetag list of the old state against that of the new state
4. Enemy transformation detector - Detecting whether the effective <operator max patb val: val> notetag list is indeed changed due to the enemy transformation, by checking the effective <operator max patb val: val> notetag list of the old form against that of the new form
Obviously, it'd lead to much more complicated and convoluted codes, and can even be less performant than the original
Probabilistic Reasons To Change Detector, especially when those effect <operator max patb val: val> notetag lists are long.
On a side note: Without comparing the old and new effective <operator max patb val: val> notetag list, those
Deterministic Reasons To Change Detectors will become
Probabilistic Reasons To Change Detectors, which are only marginally more performant than the original one but will lead to much more codes.
If a single
Deterministic Reasons To Change Detector is used on Game_Battler.prototype.set_patb_refresh, it will be checking the whole old effective <operator max patb val: val> notetag list against the whole new one, which is likely so unperformant that doing so will probably defeat the purpose of using change notification flags in the first place.
Therefore, in this case, I'll prefer to use a single
Probabilistic Reasons To Change Detector to have a better balance between code performance and simplicity(balancing and prioritizing important code qualities are too advanced to be covered here).
Applying Nontrivial Invariants
Spoiler
Recalling the aforementioned Maximum ATB Value example, there are 3 Reasons To Change the Maximum ATB Value:
1. The value of $gameSystem.patb.max_atb_val has changed
2. The effective <operator max patb val: val> notetag list has changed(changed some notetag orderings, added some new notetags, removed some existing notetags)
3. The value of some effective <operator max patb val: val> notetags has changed
If one can't be absolutely sure that there won't be any other Reasons To Change, one won't be sure that the whole Maximum ATB Value change notification flag will never be not raised even when it's to be raised. If such cases do happen, the codebase will have nontrivial bugs.
It means that to use this performance optimization trick in this example, one has to treat the below as a Nontrivial Invariant:
- The aforementioned 3 Reasons To Change will always be the only Reasons To Change the Maximum ATB Value.
In general, any performance optimization using Reasons To Change will have to ensure that "Those Reasons To Change will always be the only Reasons To Change" is a Nontrivial Invariant.
But as mentioned in Robustness, adding Nontrivial Invariants will make a codebase less robust, unless those Nontrivial Invariants will indeed never become Broken Invariants under any possible circumstances, which is clearly nearly impossible just by considering all the possible compatibility issues(provided that one doesn't ignore them).
So in essence, such performance optimization tricks are actually trading robustness for performance. How to make such trades are too advanced to be covered here.
In practice, new Reasons To Change mainly come from a plugin interacting with some other plugins, and these new Reasons To Change are some of the causes of compatibility issues among these plugins. Therefore it's desirable to implement the performance optimizations in ways that it's extremely unlikely to have new Reasons To Change under almost all circumstances.
For instance, if, for some reasons, a battler changes class/equip/state/transforms without calling Game_Battler.prototype.refresh, due to the interaction of some other plugins, the optimization tricks used on Maximum ATB Value will lead to bugs. As this should never happen, or be at least extremely rare(at least with a decent plugin having decent code qualities; it's determined by experience and observation), this source for having new Reasons To Change should be unlikely enough to not to be a reason to stop using the optimization trick.
Change Notification Flags
Spoiler
The application of change notification flags on optimizing code performance is to inform hotspots/Potential Hotspots that some resource demanding operations has/might need to be executed. Those operations will only be executed when the corresponding change notification flags are raised.
So the relationship between Reasons To Change and change notification flags should now be 100% crystal clear and obvious to you:
A change notification flag will be raised when a Reasons To Change has indeed triggered or might be triggered.
The former cases are reported by Deterministic Reasons To Change Detectors and the latter cases are reported by Probabilistic Reasons To Change Detectors.
To sum up, the goal of change notification flags is to ensure all resource demanding operations executed by hotspots/Potential Hotspots will be called if and only if at least 1 corresponding Reasons To Change might be triggered.
Using the Notifications of this forum as an analogy:
- If this function didn't exist, members would have to periodically check for all topics they wish to follow in order to know whether new replies are added.
- With this function, members don't have to do so, as such events will be notified by this function, thus saving members tons of resources(effort, time, etc).
To ensure the Notifications of this forum to work correctly for each user:
- Each member has to have his/her/its own separate instance of the Notifications, so that no such instance will depend on any other such instance.
- If the Notifications of this forum doesn't work this way, but rather only having a single instance shared by all members, then after that instance is checked by a member for the 1st time, it'll be reset to be the state indicating there are no new replies, leading to subsequent members using that instance falsely thinking that there are no new replies.
Applying the above analogy to the change notification flags:
- Every Reason To Change is analogous to a topic in this forum, so every Reason To Change needs its own change notification flag, unless the members concerned only cares whether there are any new replies from any of their followed topics, in which just 1 change notification flag will suffice.
- Every component being affected by a Reason To Change is analogous a member following a topic in this forum, so every component being affected by a Reason To Change needs its own separate instance of the change notification flag raised by that Reason To Change.
Going back to DoubleX RMMV Popularized ATB(PATB; same below), almost all notetags needing change notification flags have the below 2 Reasons To Change:
1. The effective notetag list have changed
2. Relevant plugin calls are used
The 1st one is reflected by the change notification flag Game_Battler.prototype._patb_battler_change and the 2nd one is recflected by the change notification flag Game_Battler.prototype._patb_note_change.
Each notetag having these 2 Reasons To Change will have a separate change notification flag instance for each Reason To Change. For instance:
- The Maximum ATB Value change notification flag instances are Game_Battler.prototype._patb_battler_change.max_patb_val and Game_Battler.prototype._patb_noter_change.max_patb_val
- The ATB bar color change notification flag instances are Game_Battler.prototype._patb_battler_change.atb_color and Game_Battler.prototype._patb_noter_change.atb_color
- The ATB bar overlay color change notification flag instances are Game_Battler.prototype._patb_battler_change.atb_overlay_color and Game_Battler.prototype._patb_noter_change.atb_overlay_color
However, as those components only care whether any of the Reasons To Change might be triggered, those 2 change notification flags for each component can actually be combined. I didn't do this as I feel/think that the existing design is more readable 😛
Coupling
Spoiler
From
Wikipedia:
- In
software engineering,
coupling is the manner and degree of interdependence between software modules; a measure of how closely connected two routines or modules are;
[1] the strength of the relationships between modules.
That site also lists the below types of coupling(its application to the higher levels, like the plugin level, is too advanced to be covered here):
Content Coupling
From
Wikipedia:
- Content coupling (also known as
Pathological coupling) occurs when one module modifies or relies on the internal workings of another module (e.g., accessing local data of another module). Therefore changing the way the second module produces data (location, type, timing) will lead to changing the dependent module.
For example, if the component implementing the
ATB Frame Update also implements every last details of the
Battler ATB Clock, then content coupling exists between
ATB Frame Update and
Battler ATB Clock, as the former directly determines the content of the latter.
The relevent codes can be something like this:
BattleManager.runAtbFrameUpdate = function() {
this.someUnrelatedCodes();
var allMovableMembers = $gameParty.movableMembers(), index, lastAtbVal;
allMovableMembers = allMovableMembers.concat($gameTroop.movableMembers());
// Directly implements every last detail of the Battler ATB Clock
allMovableMembers.forEach(function(mem) {
if (mem.battlerATBClock >= this.maxATBVal) { return; }
mem.battlerATBClock += mem.agi * this.maxATBVal / 60 / this.atbFillTime;
if (mem.battlerATBClock < this.maxATBVal) { return; }
mem.battlerATBClock = this.maxATBVal;
mem.makeActions();
}, this);
// Content Coupling
this.someOtherUnrelatedCodes();
}; // BattleManager.runAtbFrameUpdate
Note that the name of this function, BattleManager.runAtbFrameUpdate, doesn't indicate that it also implements the
Battler ATB Clock.
Only those having a thorough comprehension of ATB systems can immediately grasp what BattleManager.atbFrameUpdate is really doing, and the
Battler ATB Clock is actually implemented by the component implmenting the
ATB Frame Update. For those not being that capable yet, changing the component implmenting the
ATB Frame Update can unknowingly change the implementation of the
Battler ATB Clock as well.
This type of coupling is generally considered to be 1 of the most destructive antipatterns as it manifests an extremely high and the highest coupling.
Common Coupling
Spoiler
From
Wikipedia:
- Common coupling (also known as
Global coupling) occurs when two modules share the same global data (e.g., a global variable). Changing the shared resource implies changing all the modules using it.
For example, if more than 1 components are using the same change notification flag instance(as mentioned in
Change Notification Flags), then common coupling exists among all these components, as that single change notification flag instance is read from and written by all components using it.
This type of coupling is generally considered to be a severe antipattern as it manifests a lower coupling than content coupling but still quite a high coupling.
External Coupling
Spoiler
From
Wikipedia:
- External coupling occurs when two modules share an externally imposed data format, communication protocol, or device interface. This is basically related to the communication to external tools and devices.
For example, if more than 1 notetags must always use the same particular
Abstract Notetag Reader, then external coupling exists among all components using these notetags, as changing that
Abstract Notetag Reader can change the final values of those notetags which is used by those components.
On a side note:
In practice, there's no need to restirct a notetag to always use the same Abstract Notetag Reader. When that Abstract Notetag Reader is no longer appropriate for that notetag, a different/new Abstract Notetag Reader can be used by that notetag instead. If this lead to some Abstract Notetag Readers to be no longer used by more than 1 notetags, then simply throw away those Abstract Notetag Readers.
This type of coupling is generally considered to be a moderate antipattern as it manifests a lower coupling then common coupling but still slightly high coupling.
Control Coupling
Spoiler
From
Wikipedia:
- Control coupling is one module controlling the flow of another, by passing it information on what to do (e.g., passing a what-to-do flag).
For example, control coupling exists among Game_Battler.prototype.reset_patb and its callers(PATB Core v100a):
/* reset: The battler action reset flag
* val: The atb reset value
*/
Game_Battler.prototype.reset_patb = function(reset, val) { // New
if (reset) { this.reset_patb_val(val); }
this.clearActions();
var index = BattleManager.action_battlers.indexOf(this);
if (index >= 0) { BattleManager.action_battlers.splice(index, 1); }
if (BattleManager.actor() === this) { BattleManager.clearActor(); }
this.set_patb_refresh();
}; // Game_Battler.prototype.reset_patb
Because its callers are passing reset to it informing whether the
Battler ATB Clock needs to be reset as well.
If the meaning of reset is reserved in Game_Battler.prototype.reset_patb, then the reset argument of all its caller will have to be reversed as well.
This type of coupling is generally considered to be a severe code smell as it manifests a medium coupling but a lower coupling then external coupling.
Stamp Coupling
Spoiler
From
Wikipedia:
- Stamp coupling occurs when modules share a composite data structure and use only a part of it, possibly a different part (e.g., passing a whole record to a function that only needs one field of it). This may lead to changing the way a module reads a record because a field that the module does not need has been modified.
For example, stamp coupling exists among Window_BattleStatus.prototype.draw_actor_matb and its callers(MATB v100a):
/* actor: The actor using the atb bar
* x: The atb bar x position
* y: The atb bar y position
*/
Window_BattleStatus.prototype.draw_actor_matb = function(actor, x, y) {
// New; Hotspot
var w = $gameSystem.matb.atb_bar_w;
var color_0 = this.textColor($gameSystem.matb.atb_c1);
var color_1 = this.textColor($gameSystem.matb.atb_c2);
this.drawGauge(x, y, w, actor.matb_val / 100, color_0, color_1);
this.changeTextColor(this.systemColor());
this.drawText("AP", x, y, this.textWidth("AP"));
}; // Window_BattleStatus.prototype.draw_actor_matb
Because only the actor's
Battler ATB Clock, but rather than the whole actor, is used.
If the variable storing the
Battler ATB Clock changes, Window_BattleStatus.prototype.draw_actor_matb will also have to change.
This type of coupling is generally considered to be a moderate code smell as it manifests a slightly low coupling and a lower coupling then control coupling.
Data Coupling
Spoiler
From
Wikipedia:
- Data coupling occurs when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data shared (e.g., passing an integer to a function that computes a square root).
For example, data coupling exists among Game_Battler.prototype.are_patb_battler_changed and its callers(PATB v101a):
/*----------------------------------------------------------------------------
* Checks if the effective notetag list or any of their values changed
*----------------------------------------------------------------------------*/
// note: The notetags to be checked for changes
Game_Battler.prototype.are_patb_battler_changed = function(note) {
// New; Hotspot
var ch = this._patb_battler_change[note] || this._patb_note_change[note];
this._patb_battler_change[note] = this._patb_note_change[note] = false;
return ch;
}; // Game_Battler.prototype.are_patb_battler_changed
Because note is just a String, which is an elementary piece of data in Javascript ES5.
Sometimes it's necessary to pass simple data as arguments. In this case, that's the only way for this function to know which change notification flag's queried without inducing higher coupling(and reset afterwards).
This type of coupling is generally considered to be acceptable and sometimes necessary, as it manifests quite a low coupling and a lower coupling then stamp coupling.
Message Coupling
Spoiler
From
Wikipedia:
- This is the loosest type of coupling. It can be achieved by state decentralization (as in objects) and component communication is done via parameters or message passing (see
Message passing).
For example, message coupling exists among BattleManager.start_matb_battle and its callers(MATB v100a):
BattleManager.start_matb_battle = function() { // New
var start;
this._phase = 'turn';
start = this._preemptive ? "preempt" : this._surprise ? "surprise" : "norm";
$gameParty.battleMembers().forEach(function(mem) {
mem.set_start_matb_val(start);
});
$gameTroop.members().forEach(function(m) { m.set_start_matb_val(start); });
}; // BattleManager.start_matb_battle
Because its callers just need to know its function name(signature).
This type of coupling is generally considered to be ideal although not always possible as it manifests an extremely low coupling and the lowest coupling as long as coupling's inevitable.
No coupling
Spoiler
From
Wikipedia:
- Modules do not communicate at all with one another.
For example, no coupling exists between BattleManager.start_matb_battle and BattleManager.can_update_matb(MATB v100a):
BattleManager.start_matb_battle = function() { // New
var start;
this._phase = 'turn';
start = this._preemptive ? "preempt" : this._surprise ? "surprise" : "norm";
$gameParty.battleMembers().forEach(function(mem) {
mem.set_start_matb_val(start);
});
$gameTroop.members().forEach(function(m) { m.set_start_matb_val(start); });
}; // BattleManager.start_matb_battle
BattleManager.can_update_matb = function() { // New; Hotspot
return this._phase && this._phase !== 'init' && this._phase !== 'action';
}; // BattleManager.can_update_matb
Because the former's only called before the battle's completely ready to start, while the latter's only called after the battle's started, and neither needs to know anything about the other.
This type of coupling is generally considered to be the best, but only when it's possible and indeed called for, as sometimes some components are inherently coupled(as illustrated in III. ATB System Addons).
Temporal coupling
Spoiler
Simply put, temporal coupling exists among some components when those components must be called under some particular timing/ordering rules.
For example, this already mentioned
Nontrivial Invariant demonstrates that temporal coupling exists between
ATB Wait Condition and
ATB Frame Update:
-
The ATB Wait Condition must be run before running the ATB Frame Update at the exact same frame
In practice, temporal coupling can be further divided into
Explicit Temporal Coupling and
Implicit Temporal Coupling:
-
Explicit Temporal Coupling is a temportal coupling where those particular timing/ordering rules are extremely crystal clear and obvious.
-
Implicit Temporal Coupling is a temporal coupling where those particular timing/ordering rules are extremely elusive.
Clearly, whether a temporal coupling's a Explicit Temporal Coupling or Implicit Temporal Coupling is relative to the codebase readers.
For instance, the above
Nontrivial Invariant probably should exhibit an
Explicit Temporal Coupling for those having at least a
Basic knowledge on writing ATB(Active Time Battle) system plugins, but will probably exhibit an
Implicit Temporal Coupling for some of the others.
However, that doesn't mean that categorization's 100% subjective. For instance, if an ATB system plugin codebase explicitly demands its readers to have the aforementioned capability then the above
Nontrivial Invariant in that codebase can be objectively judging as exhibiting an
Explicit Temporal Coupling, as it's just ATB system 101 for them.
On a side note:
The above Nontrivial Invariant implies that some Explicit Temporal Coupling are inevitable for any ATB system plugin. However, we can still stirve for eliminating all Implicit Temporal Coupling for those meeting the capability requirements for codebase readers stated by the codebase.
Cohesion
Spoiler
From
Wikipedia:
- In
computer programming,
cohesion refers to the
degree to which the elements of a module belong together.
[1] Thus, cohesion measures the strength of relationship between pieces of functionality within a given module.
That site also lists the below types of cohesion(its application to the higher levels, like the plugin level, is too advanced to be covered here):
Coincidental Cohesion
From
Wikipedia:
- Coincidental cohesion is when parts of a module are grouped arbitrarily; the only relationship between the parts is that they have been grouped together (e.g. a “Utilities” class).
For example, if the component implementing the
Battler ATB Clock also implements every last detail of the ATB bar colors, then this component will exhibit coincidental cohesion, as the only remote commonality they have is that they're both battler functionalities, and this commonality is so meaningless, pointless and useless that it doesn't even warrant a logical cohesion(check
Logical Cohesion for details).
The relevent codes can be something like this:
Game_Battler.prototype.updateBattlerATBClock = function() {
var maxVal = BattleManager.maxATBVal;
if (this.battlerATBClock < maxVal) {
this.battlerATBClock += this.agi * maxVal / 60 / this.atbFillTime;
if (this.battlerATBClock >= maxVal) {
this.battlerATBClock = maxVal;
this.makeActions();
}
}
// Implements every last detail of the ATB bar colors here as well
this.atbBarColor = this.abstractNotetagReaderType1("atbBarColor");
// Coincidental Cohesion
}; // Game_Battler.prototype.updateBattlerATBClock
Note that the function name, Game_Battler.prototype.updateBattlerATBClock, doesn't indicate that it also updates the ATB bar color.
To accurately describe its functionalities, its name probably needs to be changed as something like:
- Game_Battler.prototype.updateBattlerATBClockAndATBBarColor
- Game_Battler.prototype.updateSomeBattlerData
- Game_Battler.prototype.updateAllBattlerData
On a side note: The above function also indicates that content coupling exists between the
Battler ATB Clock and ATB bar color(check
Content Coupling).
Other than the 100% crystal clear and obvious effect that even those having a thorough comprehension on writing ATB system plugins will likely be utterly confused by this function at the 1st glance, another immediately noticeable problem of this function is that, if the plugin currently/later supports hiding the battler ATB bars, then each of those battlers not showing their ATB bars will be doing a noticeable amount of redundant works per frame, due to the fact that those results won't be even used at all.
The
Battler ATB Clock and ATB bar colors have to be implemented by 2 separate components in order to solve this problem, meaning that that function can no longer have coincidental cohesion.
This type of cohesion is generally considered to be 1 of the most destructive antipatterns as it manifests an extremely bad and the worst cohesion.
Logical Cohesion
Spoiler
From
Wikipedia:
- Logical cohesion is when parts of a module are grouped because they are logically categorized to do the same thing even though they are different by nature (e.g. grouping all mouse and keyboard input handling routines).
For example, suppose an ATB system lets users set some skills/items to need to be charged(wait for a while with the battler not being able to do anything)before being executed, and some others to need their users to have to cooldown(wait for a while with the battler not being able to do anything)after using them but before refilling the atb bars(These 2 addons will be covered in
III. ATB System Addons).
If the
Battler ATB Clock for all
Refilling ATB,
Charging ATB, and
Cooling Down ATB phases(These latter 2 phases will be covered in
III. ATB System Addons) are implemented in a single component and the implementation of all those 3 phases are independent of each other, then that component will exhibit logical cohesion, as while they're all
Battler ATB Clocks, their nature are significantly different from each other, and a battler can only be in exact 1 of the
Refilling ATB,
Charging ATB and
Cooling Down ATB phase when updating the
Battler ATB Clock, meaning that only exactly 1 of the 3 implementations will be used per
Battler ATB Clock component call.
The relevent codes can be something like this:
Game_Battler.prototype.updateBattlerATBClock = function(type) {
// Implements all the 3 Battler ATB Clock types in the same function
var maxVal = BattleManager.maxATBVal;
var rate = this.agi * maxVal / 60 / this.atbFillTime;
if (type === "atb") {
if (this.battlerATBClock < maxVal) {
this.battlerATBClock += rate;
if (this.battlerATBClock >= maxVal) {
this.battlerATBClock = maxVal;
this.makeActions();
}
}
} else if (type === "charge") {
if (this.battlerChargeClock < maxVal) {
rate *= this.currentAction().item().meta.chargeRate;
this.battlerChargeClock += rate;
if (this.battlerChargeClock >= maxVal) {
this.battlerChargeClock = maxVal;
}
}
} else if (type === "cooldown") {
if (this.battlerCooldownClock < maxVal) {
rate *= this.currentAction().item().meta.cooldownRate;
this.battlerCooldownClock -= rate;
if (this.battlerCooldownClock <= 0) {
this.battlerCooldownClock = 0;
}
}
} else {
console.log("Invalid type " + type + "passed to Game_Battler.prototype.updateBattlerATBClock");
}
// Logical Cohesion
}; // Game_Battler.prototype.updateBattlerATBClock
On a side note: Control coupling also exists among the above function and its callers(check
Control Coupling).
It should be 100% crystal clear and obvious to those experienced with compatibility issues that, if even just a small part of the implementation of only 1 of the 3
Battler ATB Clock type has to undergo a minor change, the whole function will have to be rewritten, which can eventually lead to compatibility nightmares.
To avoid this, the implementations of the 3 Battler ATB Clock types have to be separated into 3 independent components, so that editing the implementation of 1 component won't affect the compatibility of any other components, meaning that this function can no longer have logical cohesion.
This type of cohesion is generally considered to be a severe antipattern as it manifests a better cohesion than coincidental cohesion but still quite a bad cohesion.
Temporal Cohesion
Spoiler
From
Wikipedia:
- Temporal cohesion is when parts of a module are grouped by when they are processed - the parts are processed at a particular time in program execution (e.g. a function which is called after catching an exception which closes open files, creates an error log, and notifies the user).
For example, suppose an ATB system plugin supports 2 ATB reset modes - the one just cancelling the charging skill/item, and the one resetting the ATB value to be completely empty as well.
If both cancelling the charging skill/item and resetting the ATB value to be completely empty are bundled into the same function, then that function will have temporal cohesion, as they're actually 2 different functionalities although they must be called at the same time for the latter ATB reset mode.
The relevent codes can be something like this:
Game_Battler.prototype.resetBattlerATBClock = function() {
// Implements both reset functionalities in the same function
this.battlerATBClock = 0;
this.clearActions();
var index = BattleManager.action_battlers.indexOf(this);
if (index >= 0) { BattleManager.action_battlers.splice(index, 1); }
if (BattleManager.actor() === this) { BattleManager.clearActor(); }
// Temporal Cohesion
}; // Game_Battler.prototype.resetBattlerATBClock
It should be 100% crystal clear and obvious that the 1st ATB reset mode can't use this function due to the presence of the 1st line, but could use it without that line. Such practices can eventually lead to a wet(write everything twice) codebase.
To
dry up the codebase, either the 1st line should become a new function, or moved directly to the function triggering the 1st ATB reset mode, meaning that the function can no longer have temporal cohesion.
This type of cohesion is generally considered to be a moderate antipattern as it manifests a better cohesion than logical cohesion but still a slightly bad cohesion.
Procedural Cohesion
Spoiler
From
Wikipedia:
Procedural cohesion is when parts of a module are grouped because they always follow a certain sequence of execution (e.g. a function which checks file permissions and then opens the file).
For example, the example function in
Content Coupling also exhibits procedural cohesion, as the
ATB Frame Update must (perhaps immediately)update the
Battler ATB Clock.
An immediate problem is that, the component implementing the
ATB Frame Update does/knows too much, which is a direct result of breaking
encapsulation.
This can be solved by implementing the
Battler ATB Clock in a separate component instead, meaning that the function can no longer have procedural cohesion.
This type of cohesion is generally considered to be a severe code smell as it manifests a better cohesion than temporal cohesion and a moderate cohesion.
Communicational Cohesion
Spoiler
From
Wikipedia:
- Communicational cohesion is when parts of a module are grouped because they operate on the same data (e.g. a module which operates on the same record of information).
For example, any decent ATB system won't redraw the whole status window per
ATB Frame Update just to ensure all the ATB bars are up to date. Instead, a new function just redrawing the ATB bars will be called per
ATB Frame Update instead.
The function implementing the ATB bar redraws, with the aforementioned checkig, can be something like this:
Window_BattleStatus.prototype.refreshATBBars = function() { // New; Hotspot
var barText = this.getATBBarText();
var color0 = this.getATBColor0(), color1 = this.getATBColor1();
var actor, ox = this.getATBBarOx(), rect, x, y, w = this.getATBBarW();
for (var index = 0, max = this.maxItems(); index < max; index++) {
actor = $gameParty.battleMembers()[index];
rect = this.gaugeAreaRect(index);
x = rect.x;
y = rect.y;
this.drawGauge(x, y, w, actor.atbFillRatio(), color_0, color_1);
this.changeTextColor(this.systemColor());
this.drawText(barText, x, y, this.textWidth(barText));
}
}; // Window_BattleStatus.prototype.refreshATBBars
Note that only the codes inside the for loop are actually redrawing the actor ATB bars.
These codes can actually be reused by Window_BattleStatus.prototype.drawGaugeAreaWithTp and Window_BattleStatus.prototype.drawGaugeAreaWithoutTp, which is called when the whole status window's redrawn, which will also redraw the ATB bars, which are parts of the status window.
So to
dry up the codebase, the aforementioned section of codes should be inside a separate function which is called by both Window_BattleStatus.prototype.refreshATBBars and functions redrawing the whole status window, meaning that Window_BattleStatus.prototype.refreshATBBars can no longer have communication cohesion.
This type of cohesion is generally considered to be a moderate code smell as it manifests a better cohesion than procedural cohesion and a slightly good cohesion.
Sequential Cohesion
Spoiler
From
Wikipedia:
- Sequential cohesion is when parts of a module are grouped because the output from one part is the input to another part like an assembly line (e.g. a function which reads data from a file and processes the data).
For example, suppose an ATB system plugin lets users to set some skills/items to need to be charged before being executed, with the charge rate based on the
Battler ATB Rate.
If both the
Battler ATB Rate and charge rate are implemented in the same component, that component will exhibit sequential cohesion, as the evaluated
Battler ATB Rate from the former implementation is immediately passed to the latter implementation to evaluate the charge rate.
The function implementing both functionalities can be something like this:
Game_Battler.prototype.setATBRates = function() {
// Both the Battler ATB Rate and charge rate are evaluated here
this.battlerATBRate = this.abstractNotetagReaderType2("battlerATBRate");
if (this.currentAction() && this.currentAction().item()) {
this.battlerChargeRate = this.battlerATBRate * this.currentAction().item().meta.chargeRate;
}
// Sequential Cohesion
} // Game_Battler.prototype.setATBRates
While it's okay in many cases, it can still be somehow undesirable if the plugin also lets users set whether the charge rate will be based on the
Battler ATB Rate.
To solve this, this function will have to be broken down into 2 separate functions, with 1 implementing the
Battler ATB Rate and the other implementing the charge rate, meaning that it can no longer have sequential cohesion.
This type of cohesion is generally considered to be acceptable as it manifests a better cohesion than communicational cohesion and quite a good cohesion.
Functional Cohesion
Spoiler
From
Wikipedia:
- Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module (e.g.
Lexical analysis of an XML string).
For example, BattleManager.start_matb_battle exhibits functional cohesion(MATB v100a):
BattleManager.start_matb_battle = function() { // New
var start;
this._phase = 'turn';
start = this._preemptive ? "preempt" : this._surprise ? "surprise" : "norm";
$gameParty.battleMembers().forEach(function(mem) {
mem.set_start_matb_val(start);
});
$gameTroop.members().forEach(function(m) { m.set_start_matb_val(start); });
}; // BattleManager.start_matb_battle
It's because it just does a single well-defined task - Sets the
Starting ATB Value for all battlers upon battle start.
This type of cohesion is generally considered to be ideal as it manifests a better cohesion than sequential cohesion and the best cohesion.
I wanted to write the rest of
II. ATB System Code Qualities, but as it'd lead to this reply exceeding the 10000 word limit, and I've already spent 12 hours writing this in a single shot, I've to write the rest in an upcoming reply
🤣