### Setup for Reversal Adjustment Example (Java) Source: https://martinfowler.com/eaaDev/ReversalAdjustment.html Initializes customer data and processes usage events, including setting up for a subsequent adjustment. ```java public void setUp() { MfDate.setToday(2004,4,1); watson = new Customer("Dr Watson"); watson.setServiceAgreement(testAgreement()); usageEvent = new Usage(Unit.KWH.amount(50), new MfDate(2004, 3, 31), watson); eventList.add(usageEvent); eventList.process(); MfDate.setToday(2004,6,1); replacement = new Usage(Unit.KWH.amount(70), new MfDate(2004, 3, 31), watson, usageEvent); eventList.add(replacement); eventList.process(); } ``` -------------------------------- ### Simple Service Agreement Setup Source: https://martinfowler.com/eaaDev/AgreementDispatcher.html Creates a basic ServiceAgreement, sets a default rate, and adds the MultiplyByRatePR posting rule for USAGE events. This is used for testing or simple examples. ```java private ServiceAgreement simpleAgreement() { ServiceAgreement result = new ServiceAgreement(); result.setRate(10, MfDate.PAST); result.addPostingRule(EventType.USAGE, new MultiplyByRatePR(AccountType.BASE_USAGE, false), new MfDate(1999, 10, 1)); return result; } ``` -------------------------------- ### Setup and Teardown for Integration Tests Source: https://martinfowler.com/articles/dependency-composition.html This code block sets up the necessary database and server instances before each test and tears them down afterward. It populates the database with users, restaurants, and ratings, and starts the application server. This ensures a clean and consistent environment for integration tests. ```typescript describe("the restaurants endpoint", () => { let app: Server | undefined; let database: Database | undefined; const users = [ { id: "u1", name: "User1", trusted: true }, { id: "u2", name: "User2", trusted: false }, { id: "u3", name: "User3", trusted: false }, ]; const restaurants = [ { id: "cafegloucesterid", name: "Cafe Gloucester" }, { id: "burgerkingid", name: "Burger King" }, ]; const ratingsByUser = [ ["rating1", users[0], restaurants[0], "EXCELLENT"], ["rating2", users[1], restaurants[0], "TERRIBLE"], ["rating3", users[2], restaurants[0], "AVERAGE"], ["rating4", users[2], restaurants[1], "ABOVE_AVERAGE"], ]; beforeEach(async () => { database = await DB.start(); const client = database.getClient(); await client.connect(); try { // GIVEN // These functions don't exist yet, but I'll add them shortly for (const user of users) { await createUser(user, client); } for (const restaurant of restaurants) { await createRestaurant(restaurant, client); } for (const rating of ratingsByUser) { await createRatingByUserForRestaurant(rating, client); } } finally { await client.end(); } app = await server.start(() => Promise.resolve({ serverPort: 3000, ratingsDB: { ...DB.connectionConfiguration, port: database?.getPort(), }, }), ); }); afterEach(async () => { await server.stop(); await database?.stop(); }); it("ranks by the recommendation heuristic", async () => { // .. snip ``` -------------------------------- ### Solution: Overriding the Calling Method Source: https://martinfowler.com/bliki/CallSuper.html Demonstrates an alternative solution where the derived framework overrides the 'runBare' method to include its own setup logic before calling the original 'setUp'. This allows users to continue using the familiar 'setUp' method. ```java public class AlphaTestCase extends TestCase... public void runBare() throws Throwable { alphaProjectSetup(); setUp(); try { runTest(); } finally { tearDown(); } } protected void setUp() throws Exception { } ``` -------------------------------- ### Install Java Package and Configure Alternatives Source: https://martinfowler.com/bliki/DebianJava.html This sequence installs the `java-package` tool, builds a Debian package from the Sun JDK binary, installs the package, and configures the system's default Java version using `update-alternatives`. ```bash # apt-get install java-package download the sun jdk from java.sun.com # make-jpkg jdk-1_5_0-linux-i586.bin # dpkg -i sun-j2sdk1.5_1.5.0_i386.deb # apt-get install sun-j2sdk1.5debian # update-alternatives --config java ``` -------------------------------- ### Alternative Java Installation Procedure Source: https://martinfowler.com/bliki/DebianJava.html An alternative method for installing Java on Debian, involving downloading the binary JDK, installing `java-package`, creating the Debian package using `fakeroot`, installing the package, and verifying the version. ```bash //download bin jdk from Sun #apt-get install java-package //exit root and login with normal user: #fakeroot make-jpkg jdk-1_5_0_06-linux-i586.bin //su again: #dpkg -i sun-j2sdk1.5_1.5.0+update06_i386.deb #update-alternatives --config java # java -version //The latter just to check ``` -------------------------------- ### Install Node.js, npm, and Coffee-Script Source: https://martinfowler.com/articles/vagrant-chef-rbenv.html Installs Node.js and npm, then globally installs a specific version of coffee-script using npm. Includes a symbolic link for the 'node' command. ```ruby %w[nodejs npm].each {|p| package p} execute "node-packages" do command "npm install -g coffee-script@1.6.3" end # annoyingly mac and ubuntu use different commands for node link "/usr/bin/node" do to "/usr/bin/nodejs" end ``` -------------------------------- ### jQuery Getter and Setter Example Source: https://martinfowler.com/bliki/OverloadedGetterSetter.html Demonstrates how jQuery uses a single method for both getting and setting element properties. Use without arguments to get, with an argument to set. ```javascript $( "#banner" ).height() ``` ```javascript $( "#banner" ).height(100) ``` -------------------------------- ### Initialize Project and Add Dependencies Source: https://martinfowler.com/articles/build-own-coding-agent.html Use 'uv' to initialize a new project and add 'pydantic-ai' and 'boto3' as dependencies. ```bash uv init uv add pydantic_ai uv add boto3 ``` -------------------------------- ### Example JSON for Creative Matrix Generation Source: https://martinfowler.com/articles/building-boba.html Provide a detailed, few-shot example of the desired JSON output structure to guide the LLM. This is particularly effective for complex, multi-dimensional data like a creative matrix, ensuring context is maintained for each generated idea. ```json You will respond with a valid JSON array, by row by column by idea. For example: If Rows = "row 0, row 1" and Columns = "column 0, column 1" then you will respond with the following: [ {{ "row": "row 0", "columns": [ {{ "column": "column 0", "ideas": [ {{ "title": "Idea 0 title for prompt and row 0 and column 0", "description": "idea 0 for prompt and row 0 and column 0" }} ] }}, {{ "column": "column 1", "ideas": [ {{ "title": "Idea 0 title for prompt and row 0 and column 1", "description": "idea 0 for prompt and row 0 and column 1" }} ] }}, ] }}, {{ "row": "row 1", "columns": [ {{ "column": "column 0", "ideas": [ {{ "title": "Idea 0 title for prompt and row 1 and column 0", "description": "idea 0 for prompt and row 1 and column 0" }} ] }}, {{ "column": "column 1", "ideas": [ {{ "title": "Idea 0 title for prompt and row 1 and column 1", "description": "idea 0 for prompt and row 1 and column 1" }} ] }} ] }} ] ``` -------------------------------- ### Example Registration Calls (C#) Source: https://martinfowler.com/eaaDev/PresentationChooser.html Demonstrates how to register default and additional presenters using the DynamicPresentationChooser. This includes registering a specific conditional presenter for Mozart recordings. ```csharp presentationChooser.RegisterPresenter(typeof(ClassicalRecording), typeof(FrmClassicalRecording)); presentationChooser.RegisterPresenter(typeof(PopularRecording), typeof (FrmPopularRecording)); chooser.RegisterAdditionalPresenter( typeof(ClassicalRecording), typeof(FrmMozartRecording), new PresentationChoice.ConditionDelegate(MozartCondition)); ``` -------------------------------- ### HTTP Request with Access Token Source: https://martinfowler.com/articles/command-line-google.html This is an example of an HTTP GET request to a Google API endpoint, including the necessary Authorization header with an access token. ```http GET /plus/v1/people/me HTTP/1.1 Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg Host: googleapis.com ``` -------------------------------- ### Setup for Single Electricity Usage Adjustment (Java) Source: https://martinfowler.com/eaaDev/DifferenceAdjustment.html Initializes customer data, original usage event, and sets up the DifferenceAdjustment for a single event. Ensure MfDate is set correctly before processing. ```java public void setUp() { MfDate.setToday(2004, 4, 1); watson = sampleCustomer(); original = new Usage(Unit.KWH.amount(50), new MfDate(2004, 3, 31), watson); eventList.add(original); eventList.process(); MfDate.setToday(2004, 6, 1); replacement = new Usage(Unit.KWH.amount(70), new MfDate(2004, 3, 31), watson); adjustment = new DifferenceAdjustment(replacement, original); eventList.add(adjustment); eventList.process(); } ``` -------------------------------- ### JavaScript Getter/Setter Convention Example Source: https://martinfowler.com/tags/2011.html Illustrates the JavaScript convention of using the same function for getting and setting a property, similar to Smalltalk. This pattern is used in libraries like jQuery. ```javascript $("#banner").height() $("#banner").height(100) ``` -------------------------------- ### End-to-End Test with Spring Boot and Selenium Source: https://martinfowler.com/articles/practical-test-pyramid.html A Java example demonstrating an end-to-end test using Spring Boot, Selenium WebDriver, and ChromeDriver. Ensure Chrome is installed on the system where the test is run. ```java @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloE2ESeleniumTest { private WebDriver driver; @LocalServerPort private int port; @BeforeClass public static void setUpClass() throws Exception { ChromeDriverManager.getInstance().setup(); } @Before public void setUp() throws Exception { driver = new ChromeDriver(); } @After public void tearDown() { driver.close(); } @Test public void helloPageHasTextHelloWorld() { driver.get(String.format("http://127.0.0.1:%s/hello", port)); assertThat(driver.findElement(By.tagName("body")).getText(), containsString("Hello World!")); } } ``` -------------------------------- ### Install Apache and Link HTML Directory with Chef Source: https://martinfowler.com/articles/vagrant-chef-rbenv.html Installs the apache2 package and creates a symbolic link for the web root. Use the execute resource to overwrite existing directories. ```ruby package "apache2" execute "set-html_dir" do command "rm -r /var/www/html; ln -s #{helper.html} /var/www/html" end ``` -------------------------------- ### REST API Controller Example Source: https://martinfowler.com/articles/practical-test-pyramid.html A Spring Boot controller that handles GET requests to retrieve a person's greeting based on their last name. It demonstrates basic REST API functionality. ```java @RestController public class ExampleController { private final PersonRepository personRepository; // shortened for clarity @GetMapping("/hello/{lastName}") public String hello(@PathVariable final String lastName) { Optional foundPerson = personRepository.findByLastName(lastName); return foundPerson .map(person -> String.format("Hello %s %s!", person.getFirstName(), person.getLastName())) .orElse(String.format("Who is this '%s' you're talking about?", lastName)); } } ``` -------------------------------- ### Go: Render Initial HTML Model Source: https://martinfowler.com/articles/tdd-html-templates.html Initializes a todo list model with two items and renders it into an HTML template. ```go model := todo.NewList(). Add("One"). Add("Two") initialHtml := renderTemplate("index.tmpl", model, "/") ``` -------------------------------- ### Import Statement Data Creation in JavaScript Source: https://martinfowler.com/articles/refactoring-video-store-js This example demonstrates how to import the `createStatementData` function from a separate module. It shows the setup for using the refactored data creation logic within statement generation functions. ```javascript import createStatementData from './createStatementData.es6'; function htmlStatement(customer, movies) { … } function statement(customer, movies) { … } ``` -------------------------------- ### FrmAlbum Constructor and Event Wiring (C#) Source: https://martinfowler.com/eaaDev/MediatedSynchronization.html Initializes the FrmAlbum form, sets up the album reference, and wires up event listeners to observe changes in the album and its associated performers. ```csharp class FrmAlbum : Form { public FrmAlbum(Album album) { InitializeComponent(); this._album = album; observeDomain(); load(); } private Album _album; private void observeDomain() { _album.Changed += new DomainChangeHandler(Subject_Changed); foreach (Performer p in _album.Performers) p.Changed +=new DomainChangeHandler(Subject_Changed); } private void Subject_Changed(DomainObject source, EventArgs e) { load(); } } ``` -------------------------------- ### Implement Pact Provider Test for Spring Source: https://martinfowler.com/articles/practical-test-pyramid.html This example demonstrates a basic provider test setup using Pact for a Spring REST API. It configures the provider name, pact file location, and mocks dependencies. The `@State` annotation is used to define the expected state of the provider for a given test scenario. ```java @RunWith(RestPactRunner.class) @Provider("person_provider")// same as in the "provider_name" part in our pact file @PactFolder("target/pacts") // tells pact where to load the pact files from public class ExampleProviderTest { @Mock private PersonRepository personRepository; @Mock private WeatherClient weatherClient; private ExampleController exampleController; @TestTarget public final MockMvcTarget target = new MockMvcTarget(); @Before public void before() { initMocks(this); exampleController = new ExampleController(personRepository, weatherClient); target.setControllers(exampleController); } @State("person data") // same as the "given()" part in our consumer test public void personData() { Person peterPan = new Person("Peter", "Pan"); when(personRepository.findByLastName("Pan")).thenReturn(Optional.of (peterPan)); } } ``` -------------------------------- ### Bootstrap Script for Ruby and Bundler Installation Source: https://martinfowler.com/articles/vagrant-chef-rbenv.html A shell script to install a specific Ruby version using rbenv if not already present, install bundler, and then install project gems. ```shell read -r VERSION < mfcom/.ruby-version if [ -f .rbenv/versions/${VERSION}/bin/ruby ]; then echo "ruby ${VERSION} is already installed" else rbenv install $VERSION fi cd mfcom gem install bundler --no-rdoc --no-ri rbenv rehash bundle install --without=mac ``` -------------------------------- ### Initialize MCPServerStdio for AWS Labs Core Source: https://martinfowler.com/articles/build-own-coding-agent.html Sets up an MCPServerStdio instance for AWS Labs core functionalities using 'uvx' and specifying the 'awslabs.core-mcp-server@latest' package. Error logging is configured. ```python awslabs = MCPServerStdio( command="uvx", args=["awslabs.core-mcp-server@latest"], env={"FASTMCP_LOG_LEVEL": "ERROR"}, tool_prefix="awslabs", ) ``` -------------------------------- ### Initialize MCPServerStdio for Context7 Source: https://martinfowler.com/articles/build-own-coding-agent.html Sets up an MCPServerStdio instance for Context7 using npx to execute the '@upstash/context7-mcp' package. ```python context7 = MCPServerStdio(command="npx", args=["-y", "@upstash/context7-mcp"], tool_prefix="context") ``` -------------------------------- ### Install VMWare dependencies on Ubuntu Source: https://martinfowler.com/bliki/HotRod.html Installs necessary development tools like 'make' and 'gcc-3.4', and kernel headers required for VMWare installation on Ubuntu. ```bash sudo apt-get install make sudo apt-get install gcc-3.4 sudo apt-get install linux-headers-amd64-generic ``` -------------------------------- ### JUnit setUp Method for Reinitialization Source: https://martinfowler.com/bliki/JunitNewInstance.html Demonstrates the use of the `setUp` method in JUnit to reinitialize test state before each test method runs. This supports test isolation. ```java public void setUp() { list = new ArrayList(); } ``` -------------------------------- ### Configuring a Dynamic Service Locator Source: https://martinfowler.com/articles/injection.html Demonstrates how to configure the dynamic service locator by loading specific services with appropriate keys. Ensure the ServiceLocator class is loaded before use. ```java private void configure() { ServiceLocator locator = new ServiceLocator(); locator.loadService("MovieFinder", new ColonMovieFinder("movies1.txt")); ServiceLocator.load(locator); } ``` -------------------------------- ### Example JSON Order Document Source: https://martinfowler.com/bliki/EmbeddedDocument.html An example of a JSON document representing an order with items and deliveries. ```json { "id": 1234, "customer": "martin", "items": [ {"product": "talisker", "quantity": 500}, {"product": "macallan", "quantity": 800}, {"product": "ledaig", "quantity": 1100} ], "deliveries": [ { "id": 7722, "shipDate": "2013-04-19", "items": [ {"product": "talisker", "quantity": 300}, {"product": "ledaig", "quantity": 500} ] }, { "id": 6533, "shipDate": "2013-04-18", "items": [ {"product": "talisker", "quantity": 200}, {"product": "ledaig", "quantity": 300}, {"product": "macallan", "quantity": 300} ] } ] } ```