├── .idea
├── .gitignore
├── js_design_principles.iml
├── modules.xml
└── vcs.xml
├── README.md
├── __tests__
├── dependency_inversion
│ ├── html_serializer.test.js
│ ├── response_writer.test.js
│ ├── string_serializer.test.js
│ └── xml_serializer.test.js
├── interface_segregation
│ ├── book.test.js
│ ├── book_stats.test.js
│ └── library.test.js
├── liskov_substitution
│ └── bank_account.test.js
├── open_closed
│ └── video_library.test.js
├── single_responsibility
│ └── bank_transfer.test.js
└── tell_dont_ask
│ └── carpet_quote.test.js
├── jest.config.js
├── package-lock.json
├── package.json
└── src
├── dependency_inversion
├── html_serializer.js
├── response_writer.js
├── string_serializer.js
└── xml_serializer.js
├── interface_segregation
├── book.js
├── book_stats.js
└── library.js
├── liskov_substitution
└── bank_account.js
├── open_closed
└── video_library.js
├── single_responsibility
├── bank_account.js
└── bank_transfer.js
└── tell_dont_ask
└── carpet_quote.js
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 |
--------------------------------------------------------------------------------
/.idea/js_design_principles.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # JS_design_principles
2 | First pass at porting SOLID examples to functional JavaScript (for Node.js) with Jest tests
3 |
4 | I've tried as much as possible to make the examples close to the Java and C# originals, though - since they're in a functional programming style, there are obvious differences.
5 |
6 | But the SOLID principles mostly apply, when you put somee thought into it. See how you get on with the exercises.
7 |
8 | # Single Responsibility
9 |
10 | Refactor the code so that each module only has one reason to change.
11 |
12 | # Open-Closed
13 |
14 | Extend the video library functions so that videos have a rating (18, 15, 12, U) and customers can't borrow videos they're not old enough to watch WITHOUT EDITING ANY EXISTING SOURCE FILES
15 |
16 | # Liskov Substitution
17 |
18 | Extend the bank account functions so that people can debit up to an agreed overdraft limit. Refactor the test code so that you can check the new functions pass the existing tests ("contract test")
19 |
20 | # Interface Segregation
21 |
22 | Argably, this doesn't apply directly to FP. In spirit, though, it does. Read the example code carefully. Refactor so that each module is only dependent on functions it's using.
23 |
24 | # Dependency Inversion
25 |
26 | Refactor the response_writer module so that it doesn't depend directly on the three different serialiser implementations.
27 |
28 |
29 | Assume in every exercise except for Open-Closed that you can refactor test code as well as src code if required. These are not APIs.
30 |
31 |
32 | If you'd like a Software Design Principles training workshop where you work, visit www.codemanship.com for details
33 |
--------------------------------------------------------------------------------
/__tests__/dependency_inversion/html_serializer.test.js:
--------------------------------------------------------------------------------
1 | const toHtml = require( "../../src/dependency_inversion/html_serializer");
2 |
3 | test('html serializer', () => {
4 | expect(toHtml({name: "xyz"})).toEqual(
5 | "
Customer Details" +
6 | ""
8 | );
9 | })
--------------------------------------------------------------------------------
/__tests__/dependency_inversion/response_writer.test.js:
--------------------------------------------------------------------------------
1 | const {ResponseKind, write} = require("../../src/dependency_inversion/response_writer");
2 |
3 | describe('response writer outputs', () => {
4 | it('should output XML when selected', () => {
5 | expect(write({name:""}, ResponseKind.XML)).toMatch("");
6 | })
7 |
8 | it('should output HTML when selected', () => {
9 | expect(write({name:""}, ResponseKind.HTML)).toMatch("");
10 | })
11 |
12 | it('should output as string when selected', () => {
13 | expect(write({name:""}, ResponseKind.STRING)).toMatch("Customer:");
14 | })
15 | })
--------------------------------------------------------------------------------
/__tests__/dependency_inversion/string_serializer.test.js:
--------------------------------------------------------------------------------
1 | const toString = require("../../src/dependency_inversion/string_serializer");
2 |
3 | test('string serializer', () => {
4 | expect(toString({name: "xyz"})).toEqual("Customer: xyz");
5 | })
--------------------------------------------------------------------------------
/__tests__/dependency_inversion/xml_serializer.test.js:
--------------------------------------------------------------------------------
1 | const toXml = require("../../src/dependency_inversion/xml_serializer");
2 |
3 | test('xml serializer', () => {
4 | expect(toXml({name: "xyz"})).toEqual(
5 | "xyz"
6 | );
7 | })
--------------------------------------------------------------------------------
/__tests__/interface_segregation/book.test.js:
--------------------------------------------------------------------------------
1 | const {rating, rate, summarize} = require("../../src/interface_segregation/book");
2 |
3 | test('rate a book', () => {
4 | const book = {title: "", author: "", published: 1990, totalRating: 0, ratingCount: 0};
5 | let rated = rate(4, rate(3, book));
6 | expect(rated.totalRating).toBe(7);
7 | expect(rated.ratingCount).toBe(2);
8 | })
9 |
10 | test('summarize book', () => {
11 | const book = {
12 | title: "Jaws",
13 | author: "Peter Benchley",
14 | published: 1974,
15 | totalRating: 0,
16 | ratingCount: 0
17 | };
18 |
19 | expect(summarize(book)).toEqual("Jaws by Peter Benchley, published 1974");
20 | })
--------------------------------------------------------------------------------
/__tests__/interface_segregation/book_stats.test.js:
--------------------------------------------------------------------------------
1 | const {rating, rate} = require("../../src/interface_segregation/book");
2 | const booksWithRating = require("../../src/interface_segregation/book_stats");
3 |
4 | test('get books with specific rating', () => {
5 |
6 | const ratedBook = rating => ({title: "", author: "", published: 1990, totalRating: rating, ratingCount: 1});
7 |
8 | const books= [
9 | ratedBook(5),
10 | ratedBook(5),
11 | ratedBook(1)
12 | ];
13 |
14 | expect(booksWithRating(5, books).length).toBe(2);
15 | })
--------------------------------------------------------------------------------
/__tests__/interface_segregation/library.test.js:
--------------------------------------------------------------------------------
1 | const {add, dump} = require("../../src/interface_segregation/library");
2 |
3 | describe('add books to library', () =>
4 | {
5 | let library = {books:[]};
6 |
7 | const jaws = {title: "Jaws", author: "Peter Benchley", published: 1974, totalRating: 0, ratingCount: 0};
8 | const foundation = {title: "Foundation", author: "Isaac Asimov", published: 1951, totalRating: 0, ratingCount: 0};
9 |
10 | library = add(library, jaws);
11 | library = add(library, foundation);
12 |
13 | it('should make added books available', () => {
14 | expect(library.books).toContain(jaws);
15 | expect(library.books).toContain(foundation);
16 | })
17 |
18 | it('should dump summaries of books in library', () => {
19 | expect(dump(library)).toEqual(
20 | "Jaws by Peter Benchley, published 1974/n" +
21 | "Foundation by Isaac Asimov, published 1951/n"
22 | );
23 | })
24 | })
--------------------------------------------------------------------------------
/__tests__/liskov_substitution/bank_account.test.js:
--------------------------------------------------------------------------------
1 | const {credit, debit} = require("../../src/liskov_substitution/bank_account");
2 |
3 | describe('bank account', () => {
4 |
5 | it('credit account', () => {
6 | const account = {id: 1, balance: 0};
7 | const credited = credit(account, 50);
8 | expect(credited.balance).toBe(50);
9 | })
10 |
11 | it('debit account with sufficient funds', () => {
12 | const account = {id: 1, balance: 50};
13 | const debited = debit(account, 50);
14 | expect(debited.balance).toBe(0);
15 | })
16 |
17 | it('debit account with insufficient funds', () => {
18 | const account = {id: 1, balance: 50};
19 | expect(() => debit(account, 51)).toThrow('Insufficient funds error');
20 | })
21 | })
--------------------------------------------------------------------------------
/__tests__/open_closed/video_library.test.js:
--------------------------------------------------------------------------------
1 | const borrow = require('../../src/open_closed/video_library.js')
2 |
3 | describe('borrow a video', () => {
4 |
5 | const customer = {
6 | id: 'jgorman',
7 | borrowedVideos: []
8 | }
9 | const video = {
10 | onLoan: false,
11 | borrower: undefined
12 | }
13 |
14 | const loan = borrow(customer, video);
15 |
16 | it('should add video to customer borrowed collection', () => {
17 | expect(loan.customer.borrowedVideos).toContainEqual(video);
18 | })
19 |
20 | it('should flag video as on loan', () => {
21 | expect(loan.video.onLoan).toBe(true);
22 | })
23 |
24 | it('should record who has borrowed the video', () => {
25 | expect(loan.video.borrower).toBe(customer.id);
26 | })
27 | })
--------------------------------------------------------------------------------
/__tests__/single_responsibility/bank_transfer.test.js:
--------------------------------------------------------------------------------
1 | const {transfer, toXml} = require("../../src/single_responsibility/bank_transfer");
2 |
3 | describe('bank transfer', () => {
4 | const payer = { id: 1, balance: 100.0 };
5 | const payee = { id: 2, balance: 0.0 };
6 |
7 | const transferRecord = transfer(payer, payee, 50.0);
8 |
9 | it('should debit amount from payer', () => {
10 | expect(transferRecord.payer.balance).toBe(50.0);
11 | })
12 |
13 | it('should credit amount to payee', () => {
14 | expect(transferRecord.payee.balance).toBe(50.0);
15 | })
16 |
17 | it('should serialize the transfer details to XML', () => {
18 | expect(toXml(transferRecord)).toEqual("" +
19 | "1" +
20 | "2" +
21 | "")
22 | })
23 | })
--------------------------------------------------------------------------------
/__tests__/tell_dont_ask/carpet_quote.test.js:
--------------------------------------------------------------------------------
1 | const quote = require("../../src/tell_dont_ask/carpet_quote");
2 |
3 |
4 | test("quote for carpet without rounding up", () => {
5 | const room = {length: 2.5, width: 2.5};
6 | const carpet = {pricePerSqrMetre: 10.0, roundUp: false};
7 | expect(quote(room, carpet)).toBe(62.5);
8 | })
9 |
10 | test("quote for carpet with rounding up", () => {
11 | const room = {length: 2.5, width: 2.5};
12 | const carpet = {pricePerSqrMetre: 10.0, roundUp: true};
13 | expect(quote(room, carpet)).toBe(70.0);
14 | })
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | // For a detailed explanation regarding each configuration property, visit:
2 | // https://jestjs.io/docs/en/configuration.html
3 |
4 | module.exports = {
5 | // All imported modules in your tests should be mocked automatically
6 | // automock: false,
7 |
8 | // Stop running tests after `n` failures
9 | // bail: 0,
10 |
11 | // Respect "browser" field in package.json when resolving modules
12 | // browser: false,
13 |
14 | // The directory where Jest should store its cached dependency information
15 | // cacheDirectory: "C:\\Users\\Jason\\AppData\\Local\\Temp\\jest",
16 |
17 | // Automatically clear mock calls and instances between every test
18 | clearMocks: true,
19 |
20 | // Indicates whether the coverage information should be collected while executing the test
21 | // collectCoverage: false,
22 |
23 | // An array of glob patterns indicating a set of files for which coverage information should be collected
24 | // collectCoverageFrom: null,
25 |
26 | // The directory where Jest should output its coverage files
27 | // coverageDirectory: null,
28 |
29 | // An array of regexp pattern strings used to skip coverage collection
30 | // coveragePathIgnorePatterns: [
31 | // "\\\\node_modules\\\\"
32 | // ],
33 |
34 | // A list of reporter names that Jest uses when writing coverage reports
35 | // coverageReporters: [
36 | // "json",
37 | // "text",
38 | // "lcov",
39 | // "clover"
40 | // ],
41 |
42 | // An object that configures minimum threshold enforcement for coverage results
43 | // coverageThreshold: null,
44 |
45 | // A path to a custom dependency extractor
46 | // dependencyExtractor: null,
47 |
48 | // Make calling deprecated APIs throw helpful error messages
49 | // errorOnDeprecated: false,
50 |
51 | // Force coverage collection from ignored files using an array of glob patterns
52 | // forceCoverageMatch: [],
53 |
54 | // A path to a module which exports an async function that is triggered once before all test suites
55 | // globalSetup: null,
56 |
57 | // A path to a module which exports an async function that is triggered once after all test suites
58 | // globalTeardown: null,
59 |
60 | // A set of global variables that need to be available in all test environments
61 | // globals: {},
62 |
63 | // An array of directory names to be searched recursively up from the requiring module's location
64 | // moduleDirectories: [
65 | // "node_modules"
66 | // ],
67 |
68 | // An array of file extensions your modules use
69 | // moduleFileExtensions: [
70 | // "js",
71 | // "json",
72 | // "jsx",
73 | // "ts",
74 | // "tsx",
75 | // "node"
76 | // ],
77 |
78 | // A map from regular expressions to module names that allow to stub out resources with a single module
79 | // moduleNameMapper: {},
80 |
81 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
82 | // modulePathIgnorePatterns: [],
83 |
84 | // Activates notifications for test results
85 | // notify: false,
86 |
87 | // An enum that specifies notification mode. Requires { notify: true }
88 | // notifyMode: "failure-change",
89 |
90 | // A preset that is used as a base for Jest's configuration
91 | // preset: null,
92 |
93 | // Run tests from one or more projects
94 | // projects: null,
95 |
96 | // Use this configuration option to add custom reporters to Jest
97 | // reporters: undefined,
98 |
99 | // Automatically reset mock state between every test
100 | // resetMocks: false,
101 |
102 | // Reset the module registry before running each individual test
103 | // resetModules: false,
104 |
105 | // A path to a custom resolver
106 | // resolver: null,
107 |
108 | // Automatically restore mock state between every test
109 | // restoreMocks: false,
110 |
111 | // The root directory that Jest should scan for tests and modules within
112 | // rootDir: null,
113 |
114 | // A list of paths to directories that Jest should use to search for files in
115 | // roots: [
116 | // ""
117 | // ],
118 |
119 | // Allows you to use a custom runner instead of Jest's default test runner
120 | // runner: "jest-runner",
121 |
122 | // The paths to modules that run some code to configure or set up the testing environment before each test
123 | // setupFiles: [],
124 |
125 | // A list of paths to modules that run some code to configure or set up the testing framework before each test
126 | // setupFilesAfterEnv: [],
127 |
128 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing
129 | // snapshotSerializers: [],
130 |
131 | // The test environment that will be used for testing
132 | testEnvironment: "node",
133 |
134 | // Options that will be passed to the testEnvironment
135 | // testEnvironmentOptions: {},
136 |
137 | // Adds a location field to test results
138 | // testLocationInResults: false,
139 |
140 | // The glob patterns Jest uses to detect test files
141 | // testMatch: [
142 | // "**/__tests__/**/*.[jt]s?(x)",
143 | // "**/?(*.)+(spec|test).[tj]s?(x)"
144 | // ],
145 |
146 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
147 | // testPathIgnorePatterns: [
148 | // "\\\\node_modules\\\\"
149 | // ],
150 |
151 | // The regexp pattern or array of patterns that Jest uses to detect test files
152 | // testRegex: [],
153 |
154 | // This option allows the use of a custom results processor
155 | // testResultsProcessor: null,
156 |
157 | // This option allows use of a custom test runner
158 | // testRunner: "jasmine2",
159 |
160 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
161 | // testURL: "http://localhost",
162 |
163 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
164 | // timers: "real",
165 |
166 | // A map from regular expressions to paths to transformers
167 | // transform: null,
168 |
169 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
170 | // transformIgnorePatterns: [
171 | // "\\\\node_modules\\\\"
172 | // ],
173 |
174 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
175 | // unmockedModulePathPatterns: undefined,
176 |
177 | // Indicates whether each individual test should be reported during the run
178 | // verbose: null,
179 |
180 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
181 | // watchPathIgnorePatterns: [],
182 |
183 | // Whether to use watchman for file crawling
184 | // watchman: true,
185 | };
186 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "function_design",
3 | "version": "1.0.0",
4 | "dependencies": {},
5 | "devDependencies": {
6 | "jest": "^24.4.0"
7 | },
8 | "scripts": {
9 | "test": "jest"
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/dependency_inversion/html_serializer.js:
--------------------------------------------------------------------------------
1 | const toHtml = (customer) => {
2 | return "Customer Details" +
3 | "Customer | " + customer.name +
4 | " |
";
5 | }
6 |
7 | module.exports = toHtml;
--------------------------------------------------------------------------------
/src/dependency_inversion/response_writer.js:
--------------------------------------------------------------------------------
1 | const toXml = require("./xml_serializer");
2 | const toHtml = require("./html_serializer");
3 | const toString = require("./string_serializer");
4 |
5 | const ResponseKind = {
6 | XML: 1,
7 | HTML: 2,
8 | STRING: 3
9 | }
10 |
11 | const write = (customer, responseKind) => {
12 | if(responseKind == ResponseKind.HTML) {
13 | return toHtml(customer);
14 | } else {
15 | if(responseKind == ResponseKind.XML){
16 | return toXml(customer);
17 | }
18 | }
19 | return toString(customer);
20 | }
21 |
22 | module.exports = {ResponseKind, write};
--------------------------------------------------------------------------------
/src/dependency_inversion/string_serializer.js:
--------------------------------------------------------------------------------
1 | const toString = (customer) => {
2 | return "Customer: " + customer.name;
3 | }
4 |
5 | module.exports = toString;
--------------------------------------------------------------------------------
/src/dependency_inversion/xml_serializer.js:
--------------------------------------------------------------------------------
1 | const toXml = (customer) => {
2 | return "" + customer.name + "";
3 | }
4 |
5 | module.exports = toXml;
--------------------------------------------------------------------------------
/src/interface_segregation/book.js:
--------------------------------------------------------------------------------
1 | const rating = (book) => {
2 | return Math.ceil(book.totalRating / book.ratingCount);
3 | }
4 |
5 | const rate = (score, book) => {
6 | return {...book,
7 | totalRating: book.totalRating + score,
8 | ratingCount: book.ratingCount + 1
9 | };
10 | }
11 |
12 | const summarize = (book) => {
13 | return book.title + " by " + book.author + ", published " + book.published;
14 | }
15 |
16 | module.exports = {rating, rate, summarize};
17 |
--------------------------------------------------------------------------------
/src/interface_segregation/book_stats.js:
--------------------------------------------------------------------------------
1 | const {rating, rate, summarize} = require("./book");
2 |
3 | const booksWithRating = (number, books) => {
4 | return books.filter((book) => rating(book) == number);
5 | }
6 |
7 | module.exports = booksWithRating;
--------------------------------------------------------------------------------
/src/interface_segregation/library.js:
--------------------------------------------------------------------------------
1 | const {rating, rate, summarize} = require("./book");
2 |
3 | const add = (library, book) => {
4 | return {...library, books: library.books.concat(book)};
5 | }
6 |
7 | const dump = (library) => {
8 | return library.books.reduce((contents, book) => contents + summarize(book) + "/n", "");
9 | }
10 |
11 | module.exports = {add, dump};
--------------------------------------------------------------------------------
/src/liskov_substitution/bank_account.js:
--------------------------------------------------------------------------------
1 | function credit(account, amount) {
2 | return {...account, balance: account.balance + amount};
3 | }
4 |
5 | function debit(account, amount) {
6 | if (amount > account.balance) {
7 | throw "Insufficient funds error"
8 | }
9 | return {...account, balance: account.balance - amount};
10 | }
11 |
12 | module.exports = {credit, debit};
--------------------------------------------------------------------------------
/src/open_closed/video_library.js:
--------------------------------------------------------------------------------
1 | const borrow = (customer, video) => {
2 | const borrowed = customer.borrowedVideos;
3 | return {
4 | customer: {...customer, borrowedVideos: borrowed.concat([video]) },
5 | video: {...video, onLoan: true, borrower: customer.id }
6 | }
7 | }
8 |
9 | module.exports = borrow;
--------------------------------------------------------------------------------
/src/single_responsibility/bank_account.js:
--------------------------------------------------------------------------------
1 | const debit = (payer, amount) => {
2 | return {...payer, balance: payer.balance - amount};
3 | }
4 |
5 | const credit = (payee, amount) => {
6 | return {...payee, balance: payee.balance + amount};
7 | }
8 |
9 | module.exports = {debit, credit};
--------------------------------------------------------------------------------
/src/single_responsibility/bank_transfer.js:
--------------------------------------------------------------------------------
1 | const {debit, credit} = require("./bank_account");
2 |
3 | const transfer = (payer, payee, amount) => {
4 | return {
5 | payer: debit(payer, amount),
6 | payee: credit(payee, amount),
7 | amount: amount
8 | };
9 | }
10 |
11 | const toXml = (transferRecord) => {
12 | return "" +
13 | "" + transferRecord.payer.id + "" +
14 | "" + transferRecord.payee.id + "" +
15 | "";
16 | }
17 |
18 | module.exports = {transfer, toXml};
--------------------------------------------------------------------------------
/src/tell_dont_ask/carpet_quote.js:
--------------------------------------------------------------------------------
1 | function area(room) {
2 | return room.length * room.width;
3 | }
4 |
5 | function priceForRoom(roomArea, carpet) {
6 | let sqrMetres = roomArea;
7 | if(carpet.roundUp){
8 | sqrMetres = Math.ceil(sqrMetres);
9 | }
10 | return sqrMetres * carpet.pricePerSqrMetre;
11 | }
12 |
13 | function quote(room, carpet) {
14 | return priceForRoom(area(room), carpet);
15 | }
16 |
17 | module.exports = quote;
--------------------------------------------------------------------------------