Onboarding

Guide and best practices for Blueprint Developers on both Project Teams and Tech Team. We recommend reading this if you are new to any Blueprint role: E-Board Member, Technical Lead, Product Manager, Designer, and Developers!

Onboarding for Tech Team

Onboarding

Quick Links:

How does the Tech Team work?


Git/Github

Making Your First Contribution!

This will be instructions on how to make your first contribution, with the example of adding John Doe to the list of contributors.

  1. Cloning the repository.
    • Open a new terminal and type the git clone command followed by the GitHub repository you want to clone. In this case, it would be git clone https://github.com/stevensblueprint/blueprint_website.git. This should create a new folder on your computer with the name of the repository.
    • Cloning the repository creates a local copy of all the code that you can edit on your computer. This only needs to be run once and from here, you can keep editing this local copy and updating it from the GitHub repository when needed.git_clone_command.png
  2. Creating a new branch.
    •  Open the folder of the local repository and run the git checkout command followed by the name of the branch. When naming a branch, it's good to pick a short, descriptive name. In our case, we are adding a contributor, so we'll type git checkout -b contributors/johnDoe.
    • Notice the -b? That's used to create a new branch as opposed to checking out a branch that already exists.
    • Creating a new branch makes a new version of the code that is isolated from the main code. This means changes can be made without affecting the main code (in case something goes terribly, disastrously wrong).creating_new_branch1.png
  3. Making the change!
    • Open the file you want to edit and make the necessary changes. In this case, we will be adding John Doe to the list of contributors.making_first_change.png
    • Make sure to save the file!

  4. Adding a file to a commit.
    • Once the change is made, use the git add command followed by the local file path to the changed file, in order to include or 'stage' the change them for the next commit. Commits can be thought of as checkpoints; more on that later.
    • In this case, we made changes to the CONTRIBUTORS.MD file in the .github folder, so our file path is .github/CONTRIBUTORS.MD and we type in git add .github/CONTRIBUTORS.MD.
    • You can use git add multiple times to add as many files as you need.
    • Another option is to use git add . to add all files with changes.adding_changes_to_commit1.png
    • Note that the file path is case sensitive.

  5. Checking changes to be committed.
    • You can use the git status command to check what files have been added or "staged" for a commit. In this case, it's only the one contributors file that we added.git_status_command.png
    • You can see here that our file is under changes to be committed and is in green text. Changes not staged for commit will be in red.

  6. Committing changes.
    • With our changes made and staged, we can create a commit which is basically a checkpoint for our code. We can revert to this point if we make mistakes or need to look at the version of the code at this point in time.
    • It is also good practice to include a commit message by using the -m flag to describe what changes were made. For us, we will just say that we are adding a new contributor, like so: git commit -m "Added a new contributor!".
      • Commit Messages: When writing a commit, it is usually good practice to follow a convention. At Blueprint, we use the Conventional Commits specification: www.conventionalcommits.org
        • Most basic form: <type>: <decscription>, two common types are feat (feature) or fix (bug-fix)
    • We can commit as often as we want, or when we feel it is necessary before making big changes.git_commit_command.png
  7. Pushing the commit.
    • In order for our changes to appear on the remote repository (the one on Github), we need to push our changes using the git push command. If we run it as is, however, we will encounter an error:git_push_command_1.png
    • This is because when we create the branch contributors/johnDoe, we only created it locally and it does not exist on the Github repository. Therefore, we must run the command shown: git push --set-upstream origin contributors/johnDoe.git_push_command_2.png
    • Once the branch is set up remotely, or if the branch already existed remotely and was not created locally, we can simply use git push.
  8. Creating a pull request.
    • Once we have completed our task and pushed the changes, we can work on merging the changes back into the main code. To do this, we can create something called a pull request (PR for short) where we essentially propose the changes we made.
    • Going onto Github, you will likely see a pop-up asking if you want to create a pull request for your branch. If so, press "Compare & pull request".making_pull_request.png
    • If you don't see it, you can also create a new pull request by navigating to the "Pull requests" tab and selecting "New pull request".navigate_to_new_pr.png
  9. Approvals and Merging.
    • Next, you can put in details for your pull request such as a title and detailing what changes were made on your branch.new_pull_request.png
    • You will also see a list of approvals, some of which are run automatically. It is also necessary for at least one person to review your pull request before you can merge it with the main branch. Once your pull request is approved, hit "Squash and merge". You're done!merging_request.png
  10. What Now?
    • In order to keep your local copy updated with the remote repository (on GitHub), you can run the git pull command. This pulls all the changes made by other people.
      • Pulling changes can sometimes result in merge conflicts which is when the changes on the remote repository don't work well with your local version. See the Merge Conflict section below for more details.

         
    • For each task, your process should be something like this:
        • Step 2, create a new branch
        • Repeat Steps 3-7 as you work on your task and make changes
        • Steps 8-9 when you complete your task
          • Make revisions as needed.
  11. Merge Conflicts
    • What is a merge conflict?
      • When different versions of the code are combined, the changes don't always align well. For example, if you have a version where you changed a line of code, but the same line of code was removed in a different version, this could create a conflict.
    • How to fix?

Project Board and Tasks

Now that you know how to make changes, there's the questions of what to change.

Tasks
Project Board

If you're ever unsure of which task to pick up or having difficulty completing a task, drop by a Tech Team meeting and ask!

Git/Github Quick Reference

New to Git and Github? Checkout these resources:

Overview of Git and Github: https://wiki.sitblueprint.com/books/onboarding/page/contributing-to-blueprint-gitgithub

Full comprehensive guide/walkthrough of Git and Github: GitHub Foundations - Training | Microsoft Learn

If you prefer a comprehensive book: https://git-scm.com/book/en/v2

Or comprehensive video: Git Tutorial for Beginners: Learn Git in 1 Hour

Git Clone

git clone [<repository>]

Git Pull

git pull

Git Checkout

git checkout [-b <branch>]

Git Add

git add [<path>]

Git Commit

git commit [-m <message>]

git push

git merge [<branch-name>]

Contributing to Blueprint - git/GitHub

How to contribute?

All of our projects are hosted on GitHub. Being able to contribute to any GitHub is an essential skill for any developer; let's learn how to do it. If you would like a more in depth guide on contributing in GitHub, refer to the Tech Team Onboarding Guide

Click here to view the Stevens Blueprint GitHub.

What are git and GitHub? What are their differences?

Check out these resources for more detail on how to use the technologies:

Git and GitHub are essential tools in the world of software development, used for version control and collaboration. They serve related but distinct purposes, and understanding their main features and differences is key to utilizing them effectively.

Git

Git is a free, open-source version control system designed to handle everything from small to very large projects with speed and efficiency. It was created by Linus Torvalds in 2005 to support the development of the Linux kernel. Git operates on your local computer and allows you to keep track of changes to your files and code. Its main features include:

GitHub

GitHub is a web-based hosting service for version control using Git. It provides a cloud-based platform for developers to store, manage, and track changes to their code projects. GitHub was launched in 2008 and has become one of the most popular platforms for code hosting and collaboration. Its main features include:

Main Differences

Joining Blueprint's GitHub Organization

In order to join the Stevens Blueprint GitHub organization you must do the following:

  1. Install Git
  2. Create a GitHub Account (Instructions here)
  3. Send your GitHub username or email associated with your GitHub account to a member of the Stevens Executive Board. Once they said the invite it will appear in your email inbox and you must accept the invitation. 

Once you are part of the GitHub organization you can begin working on your respective project!

Product Management & Agile at Blueprint

This article explores how effective communication and streamlined meetings, leveraging platforms like Discord and GitHub (focusing on Issues and Project Boards) within Agile Project Methodology, can significantly enhance software development collaboration. Our goal is to provide strategies to optimize these tools, improving team efficiency and project outcomes.

Teamwork makes the dream work

Using Agile/Scrum in Blueprint Teams

Agile

Agile Methodology is a project management approach used primarily in software development. It focuses on delivering value through flexible, iterative progress rather than following a fixed plan. Agile emphasizes collaboration, customer feedback, and small, rapid releases of software.

Key Concepts:

Scrum

Scrum is a framework that implements Agile principles. It provides a structured, yet flexible way to manage projects.

Key Concepts:

This is a VERY brief and general introduction to Agile and Scrum. Please refer to the additional resources for more information.

How Blueprint Developers can Follow These Principles and Frameworks (Scrumprint)


Given the unique structure of Blueprint, adhering strictly to a traditional Scrum framework is not feasible for us. Our commitment to academic and extracurricular activities, alongside the absence of a standard 9-5 work schedule, necessitates a more flexible, hybrid approach to project management. Consequently, we are tasked with tailoring industry-standard methodologies to accommodate the diverse schedules of our student team members. Recognizing the dynamic nature of this adaptation, we remain open to continuous feedback and anticipate that our approach will evolve over time. The following outlines an adapted framework we encourage teams to implement

Roles

Events

Goals and Additions:

The next sections will show how tools like GitHub and Discord can be used to encourage this framework.

Joining & Interacting in Discord

Discord is our primary mode of communication used for project teams, tech teams, and general blueprint announcements. You can join Discord using this link: Blueprint Discord Link. Upon joining the server, you will be prompted to change your username to [FIRSTNAME] [LASTNAME] ['YEAR]. For example: "Atilla Duck '25". There are a lot of users on the Discord, so please do this as soon as possible. 

If you are on a Project Team or a Tech Team project we kindly ask that you leave the notifications on for your respective channel.

Make Use of Discord Features

There are several features that you can make use of in Discord to help organize channels.

Pinning Messages: Use this to save the most important messages in your channel for quick access. This can include Project Proposal Documents, Links to specific resources, or important channel guidelines that you want to save in the channel. 

Threads: Use threads to manage conversations on a specific topic. Perhaps their is a bug that someone needs help with or the Project Leader would like to collect team members opinions on a new feature. Using threads leaves the main channel less cluttered. Threads can be used for the Async Stand up events from the Scrumprint framework.

@People: Use the @ feature in your messages to get the attention of specific users or roles. Do not be afraid to make use of this feature if you need help with something or if someone has been unresponsive. "@here" is a good way to get the attention of everyone in a respective channel.

Reactions: It's respectful to acknowledge your teammates messages! Thankfully discord makes this easy so you can throw a quick thumbs up without having to type anything.

Webhooks

Webhooks make it easy way to get automated messages and data updates sent to a text channel in your server. Each project team and tech team project channel will be accompanied by another "-hooks" channel. This channel connects to the team's repository on GitHub. Whenever someone makes a contribution (commits code, opens a Pull Request (PR), comments on an issue, etc.) the "-hooks" channel will be notified. Currently, the Webhooks are configured to output the results of certain tests whenever you commit code. This makes it easy for you to see the activity going on in your project!

GitHub Project Boards & Issues

GitHub offers more than just hosting our repositories. There are two features that we can make use of to help organize tasks and adhere to the Scrumprint framework. 

Project Boards

Project Boards on GitHub offer a dynamic and intuitive interface for managing the various stages of our tasks. By creating Kanban boards, we can streamline our workflow into three fundamental columns, which simplifies the process of tracking progress throughout the development cycle. This method not only aids in maintaining organization but also ensures that our team remains aligned with the goals of each sprint. Here's how Project Boards can be utilized effectively:

image.png

Follow this guide to create a project.

Issues

GitHub Issues are a powerful tool within GitHub's ecosystem, designed to facilitate collaboration and communication on projects hosted on the platform. They serve as a primary method for tracking various tasks related to software development, including bug reports, feature requests, enhancements, and general questions or discussions. Here's a closer look at how GitHub Issues can be utilized:

image.png

Issues should be descriptive and it should be clear what the requirements and scope of the task are.

Additional Resources

Introduction to UI/UX Design

See the attached PDF for slides: GBM #2_ UI_UX Design Workshop.pdf

The UI/UX Design Workshop emphasized the importance of the design process in building user-friendly digital products. Here are some of the essential points covered, along with additional insights for aspiring UI/UX designers:

Understanding Your Role in a Design Project

As a UI/UX designer, your primary responsibility is to create intuitive, engaging designs while collaborating with tech leads, project managers, and developers. It’s essential to:

Identifying Bad UI/UX

We explored several examples of bad UI/UX and identified key issues, such as poor navigation, confusing layouts, and non-responsive designs. The main takeaway is that even small design missteps can significantly affect user experience. Therefore, always be mindful of:

Inspiration from Award-Winning Designs

We reviewed examples of award-winning websites like Spotify’s Culture Next and Edcamp Ukraine, highlighting the importance of thoughtful color use, space management, clear branding, and language. As a designer, always draw inspiration from industry leaders to:

Tools and Process

We also highlighted the importance of tools and processes such as:

Practical Tips for Aspiring Designers

To thrive in UI/UX design, consider these tips:

In conclusion, UI/UX design is not just about making things look good; it’s about crafting intuitive, accessible, and functional user experiences. The tools, tips, and insights shared in this workshop provide a strong foundation for your journey as a UI/UX designer.

Resources LInked in Slides


Introduction to Docker

Click here for the Docker workshop slides: GBM #4_ Docker Workshop - Ezri Slides.pdf

What is Docker

Docker is a platform and tool for developing, shipping, and running applications by using containerization technology. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package. This ensures that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code. 

This provides consistency when working on a team where people run different operating systems.

In Blueprint we use Docker containers in several of our applications to manage different services and projects. 

Additional Resources

Introduction to Node.js

What is Node.js?

Node.js is an open-source, cross-platform, JavaScript runtime environment that allows developers to run JavaScript on the server side. It is built on Chrome's V8 JavaScript engine, and it enables the execution of JavaScript code outside a web browser. This capability makes it possible to use JavaScript for server-side scripting and building fast and scalable network applications. Node.js comes with a rich library of various JavaScript modules, which simplifies the development of web applications.

What is npm?

npm stands for Node Package Manager. It is the default package manager for Node.js and is used for managing and sharing JavaScript packages. It comes bundled with Node.js, which means when you install Node.js, you automatically get npm installed on your system. npm makes it easy for JavaScript developers to share and reuse code, and it's a vital tool for managing project dependencies.

How to Install Node.js and NVM

You can install specific versions of node individually, however we recommend making use of a tool called Node Version Manager (NVM). NVM allows you to change and install new versions of Node on your device easily. When working with multiple node projects that may rely on features from certain versions, NVM is extremely helpful.

For Mac:

If you have brew installed, you run

brew update
brew install nvm
mkdir ~/.nvm

# Using zsh
echo "export NVM_DIR=~/.nvm\nsource \$(brew --prefix nvm)/nvm.sh" >> .zshrc
source ~/.zshrc

For Windows

Credit: https://www.freecodecamp.org/news/node-version-manager-nvm-install-guide/ 

  1. Click on Download now
    In the nvm-windows repository Readme, click on "Download Now!":

    image-338

    This will open a page showing different NVM releases.

  2. Install the .exe file of the latest release

    In the latest release you'll find different assets. Click on the nvm-setup.exe asset which is the installation file for the tool

  3. Follow the Installation Wizard

Installing node and npm with nvm:

Verify your installation with nvm -v in the terminal. Once nvm is installed, you can install specific versions of node:

nvm install 20.0.0 # Installs a specific version
nvm install --lts # Installs the latest Long Term Support Version

nvm ls # Shows all the version of node installed

# Switch to a specific node version
nvm use <VERSION_NUMBER> 
nvm use 20.11.1

# Sets devices default node version to the specific version
nvm alias default <VERSION_NUMBER> 
nvm alias default 20.11.1

To verify your installation type node -v and npm -v in the terminal. 

If the instructions above don't work, check out these resources:

Software Development Crash Course

This workshop covers some tools and best practices that will help you develop software more efficiently, both independently, but especially as a TEAM. We attached the following resources for anyone who missed the workshop or would like a refresher:

Backend Wiki

Controller-Service-Repository Pattern

The controller-service-repository (CSR) pattern is a pattern used to build software applications.

It divides the software into three distinct sections, here's a quick summary, see further below for more:

Controller: Processes incoming requests and returns a response (like a front desk job). This communication most likely uses HTTP.

Service: Processes data from controller, then, based on controller data, communicates with repository. For example, if the data from the controller is requesting specific information, the service layer can get information from the repository, process the retrieved information, and then return it to the controller.

Communication between the controller and service layer uses DTO (Data Transfer Objects) which is essentially nicely packaged data. The controller may receive an HTTP request in a JSON format, then convert it to a DTO which is sent to the service layer.

Repository: The service talks to the repository/data layer for persistence (making sure the data is maintained even after the program is run). It handles all the details of accessing and storing data.

Controller:

What does the Controller layer do?

The controller handles incoming requests and returns appropriate responses (usually using HTTP (Hypertext Transfer Protocol) and TCP (Transmission Control Protocol)).

REST, API, and HTTP

An API establishes an interface for two processes to communicate. This could be a way for an app on your phone to communicate with your phone’s operating system, it could also be a web API for communicating over the internet. Whenever you use the “Login with Google” feature, the website you are trying to log in to (using your Google account) will send an API request to Google’s API, which will send a response confirming your identity.

REST (Representational State Transfer) is a software architecture that has rules for how APIs should communicate. If an API follows the principles of REST, then it is a "RESTful API" (a.k.a. REST API).

In order to communicate between them, HTTP (Hypertext Transfer Protocol) methods (such as GET, POST, DELETE) are used.

Service:

What does the Service layer do?

The service layer receives data from the Controller layer and performs "business logic" by communicating with the Repository layer to fetch or store data.

Business Logic

It's a very broad term, but it generally means the logic that relates the software to the real-world--as opposed to the lower-level logic such as displaying something to your screen.

For example, this may include data validation, or making sure that the data entered is the correct type. Let's say a user was making changes to a database and wanted to enter a string where the cost of a cookie should be. We, as humans, understand that the cost of a cookie should be a dollar amount, not some blurb of text; business logic is our way of telling a program this so it will not allow the change to happen.

As another example, let's say the controller is asking for the number of cookies left in a jar. The service layer would communicate with the repository layer to get the number of cookies originally in the jar and the number of cookies taken out of the jar. Then, it would subtract to two for the number of remaining cookies and return it.

Repository:

What does the Repository layer do?

The repository layer is focused on handling data and modifying and retrieving data from the database.

SQL and PostgreSQL

Structured Querying Language (SQL) is a language used by Relational Database Management System (RDBMS) such as PostgreSQL in order to manage databases.

The repository will communicate with the PostgreSQL database to get or change information.

Java Persistence API (JPA)

Bridges the gap between object-oriented programming and relational databases. Basically, it maps Java objects to database tables.

"The Java Persistence API (JPA) is the Java API specification that bridges the gap between relational databases and object-oriented programming by handling the mapping of the Java objects to the database tables and vice-versa. This process is known as the Object Relational Mapping (ORM). JPA can define the way Java classes (entities) are mapped to the database tables and how they can interact with the database through the EntityManager, the Persistence context, and transactions."

JPA - Introduction - GeeksforGeeks

Relational Database

What is a Relational Database?

A relational database is--as the name suggests--a type of database. Data is stored in multiple tables, all with some relation to each other.

For any given table, each row has a unique ID called a "key".

Users:

id first_name last_name account_balance
1 Jane Doe $2203
2 John Doe $1039
3 Ada Lovelace $5000

Orders:

order_num customer payment_amount
1 2 $50
2 3 $200
3 1 $80
4 2 $70


As shown in the example above, every row in both tables has a "key" (id and order_num). Additionally, they are related because every order has a customer id number associated with it (ie., the "customer" column in the Orders table contains the "id" in the Users table).

For example, for order 1, the row has 2 listed as the customer, which relates back to the id of John Doe in the Users table.

Resources

SQL

What is SQL?

SQL stands for Structured Query Language.

It is used by a Relational Database Management System (RDBMS) such as PostgreSQL, MySQL, etc., as a "language" to manipulate a Relational Database.

SQL vs NoSQL Database

A NoSQL database is a non-relational database meaning that the structure is different from that of an SQL database. Instead of tables, NoSQL databases typically store information as JSON objects. Overall, it is a much more dynamic system since there does not need to be a predefined schema that each item needs to conform to. In the end, NoSQL databases are better suited if you have unstructured data.

One prominent example of a NoSQL database is MongoDB. It uses JSON-like documents to store data, and it organizes these documents into collections to be queried. This collection method of organizing data can make data retrieval faster in some use cases, particularly when dealing with large amounts of data.

Resources

Videos

HTTP

What is HTTP

HTTP or Hypertext Transfer Protocol is a protocol (as the name suggests) that is used to communicate between client and server on the world wide web.

This is probably used in your everyday life! Whenever you search a URL for example, an HTTP request is sent to a server which sends back an appropriate response; most of the time, it's the webpage you were looking for.



GET, POST, DELETE

GET

A GET request is used to retrieve information from a server. For example, if we want to access a webpage, we can use a GET request to get information from the webserver.

POST

A POST request is used for creating new data. If you were to make a new account, a POST request would be used to create the account on the server

DELETE

This is used to delete data from a server such as removing a user profile.

What Does HTTP Look Like?

HTTP is based on a number of methods, however the most basic ones are GET and POST .

Sample Request:
The snippet below asks for a resource at example.com/contact:

GET / HTTP/1.1
Host: example.com
User-Agent: curl/8.6.0
Accept: */*
GET - HTTP | MDN

In this case, we are doing GET / indicating that we are getting the root of example.com. User-Agent and Accept are examples of headers which specify additional arguments to include in the request. User-Agent specifies information such as browser information (or in this case the version of the curl command). Accept indicates the type of response that the request will accept (which is all in this case).

You can try this request yourself in the terminal (use Command Prompt, not PowerShell for this if you are on windows). The -i flag simply signals to include response headers.

Without headers:

curl -i -X GET example.com

With headers:

curl -i -X GET http://example.com -H "User-Agent: curl/8.6.0" -H "Accept: */*"

In this scenario, -X GET is redundant since it is the default method.

Sample Response
In our case, we sent a request to the webpage, so we will get the HTML for that webpage back. However, we will also receive the response headers. It will look something like this:

HTTP/1.1 200 OK
Content-Type: text/html
ETag: "84238dfc8092e5d9c0dac8ef93371a07:1736799080.121134"
Last-Modified: Mon, 13 Jan 2025 20:11:20 GMT
Cache-Control: max-age=1405
Date: Thu, 16 Jan 2025 17:46:37 GMT
Content-Length: 1256
Connection: keep-alive

The first line includes our status code, in this case 200, which means OK. Others include 404 (Not Found), 403 (Access Denied), 503 (Service Unavailable) among others.

Resources

REST API

What is REST?

REST stands for Representational State Transfer. It is a software architecture that has rules for how APIs should communicate. If an API follows the principles of REST, then it is a "RESTful API" (a.k.a. REST API).

What are the guidelines for REST?

 What is REST?: REST API Tutorial

For our specific context, we will look at how HTTP (a method of communication for APIs) can be RESTful

  1. Uniform Interface
    HTTP uses standard methods such as GET, POST, and DELETE.
  2. Client-Server
    The UI is handled by the frontend while the business logic and data storage is handled by the backend.
  3. Stateless
    HTTP requests are self-contained, so they don't need information from previous requests.
  4. Cacheable
    HTTP responses can be "cached" meaning that they can be stored for later use. For example, webpages can be cached so they can be loaded faster.
  5. Layered System
    Gateways and proxies are layers between the client and server. A proxy might redirect requests to different servers to prevent overloading one particular server.
  6. Code on Demand
    When a server sends code to run client-side (locally) on your computer such as JavaScript. This is not too common due to security concerns; it's also why you'll sometimes get a popup saying, "Allow website to run JavaScript."

Dependency Injection

What is Dependency-Injection?

Dependency-Injection (DI) is a design pattern used in Object-Oriented languages, such as Java, as a way to decouple classes from dependencies, or make the classes more separated from their dependencies. This is done in order to make testing and maintaining the code easier.

What Does it Look Like?

Example from: Dependency Injection Made Simple with Java Examples | Clean Code and Best Practices | Geekific: https://youtu.be/GATSXm7WAxU

Before DI:

In order to better understand what DI is and the problem it is supposed to solve, let's see some code without DI.

public interface Food {}

public class Burger implements Food {}

public class Chef
{
	private Food burger;

    public Chef ()
    {
    	burger = new Burger();
    }
    
    public void prepareFood()
    {
    	//do something with burger
    }
}

Notice how the Chef class instantiates a Burger object (in the line burger = new Burger()). In this case, the Burger class is a dependency of the Chef class. The Chef class needs the Burger class in order to run.

This is okay if we only prepare burgers, but if we want other foods then it may look something like this. Let's say we introduce a Pizza class:

public class Pizza implements Food {}

Then our Chef will look something like this:

public class Chef
{
    private Food burger;
    private Food pizza;

    public Chef ()
    {
    	burger = new Burger();
    	pizza = new Pizza();
    }

    public void prepareBurger()
    {
        //do something with burger
    }

    public void preparePizza()
    {
        //do something with pizza
    }
}

There are other ways as well, such as having multiple instances of the Chef class. Either way, this makes things very interdependent; every time we change menus, we will need to update the Chef class as well.

After DI

Let's keep with the same example as before:

public interface Food {}

public class Burger implements Food {}

public class Pizza implements Food {}

However this time with the Chef class:

public class Chef
{
	private Food food;
  
    public Chef (Food someFood)
    {
    	this.food = someFood;
    }

    public void prepareFood()
    {
    	//do something with burger
    }
}

Notice the changes to the constructor. When initializing the Food class, we will pass the dependency as a parameter, or "inject" the dependency.

We can then instantiate the Chef object as such:

Chef burgerChef = new Chef(new Burger());

Chef pizzaChef = new Chef(new Pizza());

Now, it doesn't matter what food is being added or removed, it (as the dependency) will simply be "injected" in.

Types of Dependency Injection

The example shown above is constructor injection, since the dependency is injected in the constructor.

There is also setter injection where a setter method takes a dependency as input and assigns it to an object variable.

Finally, there is field injection where the dependency is set outside of the class it is being injected into.

Generally, constructor injection is favored because the dependency is apparent in the constructor signature, which is not true for the other two methods.

Resources