3º. 2º cuatrimestre. Itinerario de Computación. Grado en Ingeniería Informática. ULL
According to Martin Fowler, “a code smell is a surface indication that usually corresponds to a deeper problem in the system”.
Smells are certain structures in the code that indicate violation of fundamental design principles and negatively impact design quality.
Code smells are usually not bugs. They are not technically incorrect and do not currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.
switch
es a veces un punto débil: si introducimos nuevas casos deberemos modificar el código de la clase original en la que está el switch introduciendo un nuevo case
.Viola el principio Open/Closed.
El diseño inicial del lenguaje Egg viola el Principio Open/Close:
[~/.../PLgrado/eloquentjsegg(master)]$ sed -ne '/fun.*evaluate/,/^}/p' lib/eggvm.js
function evaluate(expr, env) {
switch(expr.type) {
case 'value': return expr.value;
case 'word':
if (expr.name in env) {
return env[expr.name];
} else {
throw new ReferenceError(`Undefined variable: ${expr.name}`);
}
case 'apply':
if (expr.operator.type == 'word' && expr.operator.name in specialForms) {
return specialForms[expr.operator.name](expr.args, env);
}
let op = evaluate(expr.operator, env);
if (typeof op != "function") {
throw new TypeError('Applying a non-function');
}
return op(...expr.args.map((arg) => evaluate(arg, env)));
}
}
A design pattern is a general, reusable solution to a commonly occurring problem.
It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.
Design patterns may be viewed as a structured approach to computer programming intermediate between the levels of
La solución para eliminar el Switch Smell es usar el strategy design pattern
.
The basic idea of the strategy design pattern
is to delegate tasks to encapsulated algorithms which are interchangable at runtime.
In the Strategy pattern we have an object (the context) that is trying to get something done. But to get that thing done, we need to supply the context with a second object, called the strategy, that helps to get the thing done.
Otro ejemplo, también de Elijah Manor se encuentra en el artículo Switching to the Strategy Pattern in JavaScript.
Vea el Vídeo de Elijah Manor.
Presta especial atención al code smell Switch Statement Smell desde el minuto 11:37 al 29:15.
Pueden encontrar las trasparencias de la presentación en http://elijahmanor.com/talks/js-smells/#/.
[~/.../chapter20-nodejs/juanIrache-20_3_public_space(master)]$ pwd -P
/Users/casiano/local/src/javascript/eloquent-javascript-3/juanIrache-solutions/20_3_public_space
const { createServer } = require('http');
const methods = Object.create(null);
createServer((request, response) => {
let handler = methods[request.method] || notAllowed;
console.log(`method= ${request.method} url=${request.url}`);
handler(request)
.catch(error => {
if (error.status != null) return error;
return { body: String(error), status: 500 };
})
.then(({ body, status = 200, type = 'text/plain' }) => {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'PUT, GET, OPTIONS, DELETE, MKCOL');
response.writeHead(status, { 'Content-Type': type });
if (body && body.pipe) body.pipe(response);
else response.end(body);
});
}).listen(8000);
async function notAllowed(request) {
return {
status: 405,
body: `Method ${request.method} not allowed.`
};
}
const { parse } = require('url');
const { resolve, sep } = require('path');
const baseDirectory = process.cwd();
function urlPath(url) {
let { pathname } = parse(url);
let path = resolve(decodeURIComponent(pathname).slice(1));
if (path != baseDirectory && !path.startsWith(baseDirectory + sep)) {
throw { status: 403, body: 'Forbidden' };
}
return path;
}
const { createReadStream } = require('fs');
const { stat, readdir, mkdir } = require('fs').promises;
const mime = require('mime');
methods.GET = async function(request) {
let path = urlPath(request.url);
let stats;
try {
stats = await stat(path);
} catch (error) {
if (error.code != 'ENOENT') throw error;
else return { status: 404, body: 'File not found' };
}
if (stats.isDirectory()) {
return { body: (await readdir(path)).join('\n') };
} else {
return { body: createReadStream(path), type: mime.getType(path) };
}
};
const { rmdir, unlink } = require('fs').promises;
methods.DELETE = async function(request) {
let path = urlPath(request.url);
let stats;
try {
stats = await stat(path);
} catch (error) {
if (error.code != 'ENOENT') throw error;
else return { status: 204 };
}
if (stats.isDirectory()) await rmdir(path);
else await unlink(path);
return { status: 204 };
};
const { createWriteStream } = require('fs');
function pipeStream(from, to) {
return new Promise((resolve, reject) => {
from.on('error', reject);
to.on('error', reject);
to.on('finish', resolve);
from.pipe(to);
});
}
methods.PUT = async function(request) {
let path = urlPath(request.url);
await pipeStream(request, createWriteStream(path));
return { status: 200, body: path };
};
methods.MKCOL = async function(request) {
let path = urlPath(request.url);
let stats;
try {
stats = await stat(path);
} catch (error) {
if (error.code != "ENOENT") throw error;
await mkdir(path);
return {status: 204};
}
if (stats.isDirectory()) return {status: 204};
else return {status: 400, body: "Not a directory"};
};
methods.OPTIONS = async function(request) {
return { status: 204 };
};
ULL-ESIT-GRADOII-DSI/temperature-oop-noswitch