# teaching machines

## Refactor

May 12, 2021 by . Filed under public, slai-2021.

This post is part of a course on geometric modeling at the Summer Liberal Arts Institute for Computer Science held at Carleton College in 2021.

Reorganizing your code to make it easier to understand and easier to update is called refactoring. Let’s refactor your code by organizing it into two separate files: one to hold your rendering code and one to hold your shape drawing code. By the end of the course, we’re going to have a lot of code for writing shapes. Our renderer won’t change nearly so much. You’ll save yourself some headache by separating them.

• Create a new file named shapes.js.
• Import your shapes.js script so that it loads before render.js by adding a new script tag in index.html.
• Inside shapes.js create a new function that looks like this:
function generateSquareDonut() {
const positions = [ /* ... */ ];
const triangles = [ /* ... */ ];
return {positions, triangles};
}

Use your actual definitions for positions and triangles that are in render.js.
• Replace the positions and triangles definitions in render.js with a call to your shape generator function:
const shape = generateSquareDonut();

• Update your geometry configuration to use the shape object instead of the two stray arrays:
let geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(shape.positions), 3));
geometry.setIndex(shape.triangles);


When you reload the page, everything should still work. When you add new shapes from here on out, start by adding to shapes.js a new function that is self-contained and named meaningfully, like this:

function generateLincolnSilhouette() {
const positions = [ /* ... */ ];
const triangles = [ /* ... */ ];
return {positions, triangles};
}


Then in render.js, change only the shape generator that you call. The rest of the rendering code stays the same.