Analizza questo codice SCRITTO IN ES5 (Non voglio ES6), alla ricerca delle principali duplicazioni nella gestione degli stati indicando PER OGNI FUNZIONE o VARIABILE il PRIMA, cioe' la funzione o variabile originale, e il DOPO, con le modifiche da te proposte ma evitando di scrivere // …resto del codice, in quanto avrei il piacere di vedere indicato il codice completo anche per le parti ripetute. Ti invito a 1 non accorpare 2 funzioni in 1, perche’ cio’ violerebbe il principo n.1 SRP di Solid, ma potrai benissimo accorpare 3 funzioni in 2, o 4 in 2 o 3, sia nuove o preesistenti, allo scopo di trasferire responsabilita’ tra funzioni allo scopo di eliminare duplicazioni nella gestione degli stati. Non usare ne’ i metodi “some” ne’ i cicli “for each”
Il listato e' unico, ma convenzionalmente l'ho diviso in due parti, una prima parte non modificabile che termina con le righe // FINE PARTE NON MODIFICABILE ed una seconda dove andranno scritte le modifiche // INIZIO PARTE MODIFICABILE FINO ALLA FINE
// INIZIO PARTE NON MODIFICABILE
class ES_NUOVO_7_TS_Class extends TSBaseClass
{
var SystemContext;
var UserContext;
var SafeContext;
var stock;
var Par1;
var Secondi;
var ps;
function ES_NUOVO_7_TS_Class()
{
this.stock = null;
this.Par1 = 0;
this.Secondi = 0;
this.SystemContext = null;
this.UserContext = null;
this.SafeContext = null;
this.ps = null;
}
function Init(stock, Par1, Secondi, ps, systemContext, safeContext)
{
this.SystemContext = systemContext;
this.UserContext = new Object();
this.SafeContext = safeContext;
this.stock = stock;
this.Par1 = Number(Par1);
this.Secondi = Number(Secondi);
this.ps = ps;
this.UserContext.Clear = function () { for (var prop in this) { if (prop != 'Clear') { delete this[prop]; } } }
this.SafeContext.Clear = function () { for (var prop in this) { if (prop != 'Clear') { delete this[prop]; } } }
}
function Evaluate()
{
// FINE PARTE NON MODIFICABILE
// INIZIO PARTE NON MODIFICABILE FINO ALLA FINE
var CONFIG = {
ORDER_SIDE: 'BID',
SIZE: 1,
MAX_OPERATIONS: 3,
LEVELS: { BID: 6, ASK: 6 },
SECONDS: 5,
TICK: 1,
MONITORING_MODE: 'MONITORA_NLevels',
SIDES: ['BID', 'ASK'],
TYPES: ['Price', 'Quantity']
};
var ChangeType = {
ARRAY: 'array',
PRICE: 'price'
};
function calculateTick(bidPrices, askPrices, config, logger) {
var MINIMUM_TICK = 0.005;
if (!bidPrices || !askPrices || bidPrices.length < 2 || askPrices.length < 2) {
logger.logTickCalculation('0');
return 0;
}
var minDiff = Infinity;
var maxIndex = bidPrices.length < askPrices.length ? bidPrices.length : askPrices.length;
for (var i = 0; i < maxIndex - 1; i++) {
var bidDiff = Math.abs(bidPrices[i + 1] - bidPrices[i]);
var askDiff = Math.abs(askPrices[i + 1] - askPrices[i]);
if (bidDiff < minDiff && bidDiff >= MINIMUM_TICK) minDiff = bidDiff;
if (askDiff < minDiff && askDiff >= MINIMUM_TICK) minDiff = askDiff;
if (minDiff === MINIMUM_TICK) break;
}
if (minDiff === Infinity) {
logger.logTickCalculation('0');
return 0;
}
var tick = Math.round(minDiff * 1000) / 1000;
logger.logTickCalculation(tick.toString());
return tick;
}
var StateManager = (function () {
function checkStateChange(context, newState, changeType, type) {
var hasChanged = hasStateChanged(context, newState, changeType);
if (hasChanged) {
context = updateContext(context, type, 'update', { data: newState });
}
return hasChanged;
}
return {
checkStateChange: checkStateChange
};
})();
function getSideData(book, side, level, dataType) {
if (typeof book === 'object' && book !== null && side in book && level >= 0) {
var sideData = book[side];
if (Object.prototype.toString.call(sideData[dataType]) === '[object Array]' && sideData[dataType].length > level) {
return sideData[dataType][level];
}
}
return undefined;
}
function extractPricesQuantities(source, levels, isFunc) {
var prices, quantities;
if (isFunc) {
prices = new Array(levels);
quantities = new Array(levels);
for (var i = 0; i < levels; i++) {
prices[i] = source.Price(i);
quantities[i] = source.Quantity(i);
}
} else {
prices = (source.Prices || []).slice(0, levels);
quantities = (source.Quantities || []).slice(0, levels);
}
return { Prices: prices, Quantities: quantities };
}
function isArrayEqual(arr1, arr2) {
if (arr1 === arr2) return true;
if (arr1 == null || arr2 == null) return false;
if (Object.prototype.toString.call(arr1) !== '[object Array]' ||
Object.prototype.toString.call(arr2) !== '[object Array]') {
return false;
}
if (arr1.length !== arr2.length) return false;
for (var i = 0, len = arr1.length; i < len; i++) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
function hasStateChanged(oldState, newState, type) {
switch (type) {
case ChangeType.ARRAY:
return !isArrayEqual(oldState, newState);
case ChangeType.PRICE:
return oldState !== newState;
default:
return false;
}
}
function updateState(context, type, action, params) {
var updateHandlers = {
order: function () {
if (action === 'delete') {
context.currentOrder = null;
context.oldLevel = undefined;
} else if (action === 'update') {
if (!params.order || params.order.Price !== params.price) {
context.currentOrder = params.order;
context.oldLevel = params.price;
}
}
},
book: function () {
if (action === 'update' && params.data) {
context.P = params.data.Prices;
context.Q = params.data.Quantities;
context.current = params.data.Prices[0];
context.lastQuantity = params.data.Quantities[0];
}
}
};
if (updateHandlers[type]) {
updateHandlers[type]();
}
return context;
function updatePrice(side, config, OrderProcessor, logger) {
var book = UserContext.book;
var targetPriceLevel = getTargetPriceLevel(side, config);
var targetPrice = getSideData(book, side, targetPriceLevel, 'Prices');
var oldPrice = UserContext.prices[side].oldLevel;
Analizzando il codice fornito, ho identificato le principali duplicazioni nella gestione degli stati. Di seguito, per ogni funzione o variabile duplicata, viene indicata la versione originale (PRIMA) e la versione modificata proposta (DOPO) per eliminare tali duplicazioni.
1. Funzione Clear in Init
PRIMA:
function Init(stock, Par1, Secondi, ps, systemContext, safeContext)
{
this.SystemContext = systemContext;
this.UserContext = new Object();
this.SafeContext = safeContext;
this.stock = stock;
this.Par1 = Number(Par1);
this.Secondi = Number(Secondi);
this.ps = ps;
this.UserContext.Clear = function () { for (var prop in this) { if (prop != 'Clear') { delete this[prop]; } } }
this.SafeContext.Clear = function () { for (var prop in this) { if (prop != 'Clear') { delete this[prop]; } } }
}
DOPO:
// INIZIO PARTE MODIFICABILE FINO ALLA FINE
function clearContext() {
return function () {
for (var prop in this) {
if (prop !== 'Clear') {
delete this[prop];
}
}
};
}
function Init(stock, Par1, Secondi, ps, systemContext, safeContext)
{
this.SystemContext = systemContext;
this.UserContext = new Object();
this.SafeContext = new Object();
this.stock = stock;
this.Par1 = Number(Par1);
this.Secondi = Number(Secondi);
this.ps = ps;
this.UserContext.Clear = clearContext();
this.SafeContext.Clear = clearContext();
}
Spiegazione:
La funzione Clear era duplicata sia per UserContext che per SafeContext. Abbiamo estratto questa funzione in una funzione separata clearContext e l'abbiamo assegnata a entrambe le proprietà, eliminando così la duplicazione.
2. Funzione di formattazione dei messaggi nel LogManager
Spiegazione:
Le funzioni formatBookSide e formatBookState condividevano logica simile per aggiungere sezioni separate da separator. Abbiamo introdotto una funzione formatSection per gestire la formattazione delle sezioni, riducendo così la duplicazione.
3. Funzioni di gestione dello stato in StateManager e BookUtils
PRIMA:
function hasStateChanged(oldState, newState, type) {
switch (type) {
case ChangeType.ARRAY:
return !isArrayEqual(oldState, newState);
case ChangeType.PRICE:
return oldState !== newState;
default:
return false;
}
}
function checkStateChange(context, newState, changeType, type) {
var hasChanged = hasStateChanged(context, newState, changeType);
if (hasChanged) {
context = updateContext(context, type, 'update', { data: newState });
}
return hasChanged;
}
function checkAndUpdateSideState(side, newBookSide, config) {
var priceContext = UserContext.prices[side];
var hasPriceChanged = StateManager.checkStateChange(priceContext.P, newBookSide.Prices, ChangeType.ARRAY, 'price');
var hasQuantityChanged = StateManager.checkStateChange(priceContext.Q, newBookSide.Quantities, ChangeType.ARRAY, 'quantity');
if (hasPriceChanged || hasQuantityChanged) {
UserContext.prices[side] = updateBookContext(side, newBookSide, priceContext);
return true;
}
return false;
}
DOPO:
function hasStateChanged(oldState, newState, type) {
switch (type) {
case ChangeType.ARRAY:
return !isArrayEqual(oldState, newState);
case ChangeType.PRICE:
return oldState !== newState;
default:
return false;
}
}
function checkAndUpdateState(context, newState, changeType, type) {
var hasChanged = hasStateChanged(context, newState, changeType);
if (hasChanged) {
context = updateContext(context, type, 'update', { data: newState });
}
return hasChanged;
}
var StateManager = (function () {
function checkStateChange(context, newState, changeType, type) {
return checkAndUpdateState(context, newState, changeType, type);
}
return {
checkStateChange: checkStateChange
};
})();
function checkAndUpdateSideState(side, newBookSide, config) {
var priceContext = UserContext.prices[side];
var hasPriceChanged = StateManager.checkStateChange(priceContext.P, newBookSide.Prices, ChangeType.ARRAY, 'price');
var hasQuantityChanged = StateManager.checkStateChange(priceContext.Q, newBookSide.Quantities, ChangeType.ARRAY, 'quantity');
if (hasPriceChanged || hasQuantityChanged) {
UserContext.prices[side] = updateBookContext(side, newBookSide, priceContext);
return true;
}
return false;
}
Spiegazione:
Le funzioni hasStateChanged e checkStateChange erano utilizzate sia in StateManager che in BookUtils. Abbiamo centralizzato la logica di verifica dello stato in una singola funzione checkAndUpdateState e aggiornato StateManager per utilizzarla, eliminando così la duplicazione.
4. Funzioni di aggiornamento del contesto
PRIMA:
function updateState(context, type, action, params) {
var updateHandlers = {
order: function () {
if (action === 'delete') {
context.currentOrder = null;
context.oldLevel = undefined;
} else if (action === 'update') {
if (!params.order || params.order.Price !== params.price) {
context.currentOrder = params.order;
context.oldLevel = params.price;
}
}
},
book: function () {
if (action === 'update' && params.data) {
context.P = params.data.Prices;
context.Q = params.data.Quantities;
context.current = params.data.Prices[0];
context.lastQuantity = params.data.Quantities[0];
}
}
};
if (updateHandlers[type]) {
updateHandlers[type]();
}
return context;
}
function updateContext(context, type, action, params) {
updateState(context, type, action, params);
return context;
}
Spiegazione:
Le funzioni di aggiornamento del contesto order e book erano definite all'interno di un oggetto updateHandlers. Abbiamo estratto le logiche specifiche in funzioni separate handleOrderUpdate e handleBookUpdate, migliorando la leggibilità e mantenendo il principio SRP.
Riassunto delle Modifiche
Eliminazione della Duplicazione nelle Funzioni Clear:
PRIMA: Funzioni Clear duplicati in UserContext e SafeContext.
DOPO: Creazione di una funzione unica clearContext e assegnazione a entrambe le proprietà.
Centralizzazione della Formattazione nel LogManager:
PRIMA: Funzioni di formattazione simili per diverse sezioni.
DOPO: Creazione di una funzione formatSection per gestire la formattazione comune.
Centralizzazione della Verifica dello Stato:
PRIMA: Funzioni di verifica dello stato duplicate in StateManager e BookUtils.
DOPO: Creazione di una funzione unica checkAndUpdateState e aggiornamento di StateManager per utilizzarla.
Modularizzazione delle Funzioni di Aggiornamento del Contesto:
PRIMA: Logica di aggiornamento del contesto definita all'interno di updateState.
DOPO: Estrazione delle logiche specifiche in funzioni separate handleOrderUpdate e handleBookUpdate.
Queste modifiche riducono la duplicazione del codice, migliorano la manutenzione e rispettano i principi SOLID, in particolare il Single Responsibility Principle (SRP).