Factory pattern in Blockchain / Solidity - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using the factory pattern in blockchain code, it's important to know how the time needed to create objects grows as we create more of them.
We want to understand how the cost changes when making many objects through the factory.
Analyze the time complexity of the following code snippet.
contract TokenFactory {
Token[] public tokens;
function createToken(string memory name) public {
Token newToken = new Token(name);
tokens.push(newToken);
}
}
contract Token {
string public name;
constructor(string memory _name) {
name = _name;
}
}
This code creates new Token contracts using a factory contract and stores them in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new Token contract and adding it to the tokens array.
- How many times: Once per call to
createToken, repeated as many times as tokens are created.
Each time we create a token, the factory does a fixed amount of work: deploy one Token and add it to the array.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 token creations and 10 array insertions |
| 100 | 100 token creations and 100 array insertions |
| 1000 | 1000 token creations and 1000 array insertions |
Pattern observation: The work grows directly with the number of tokens created, increasing steadily.
Time Complexity: O(n)
This means the time to create tokens grows linearly with how many tokens you make.
[X] Wrong: "Creating many tokens at once is just as fast as creating one token."
[OK] Correct: Each token creation requires deploying a new contract and updating the array, so the total time adds up with each new token.
Understanding how factory patterns scale helps you explain how smart contract deployments affect blockchain performance and costs.
"What if the factory stored tokens in a mapping instead of an array? How would the time complexity change?"
Practice
What is the main purpose of the Factory pattern in blockchain development?
Solution
Step 1: Understand the Factory pattern role
The Factory pattern is used to create many similar contracts efficiently.Step 2: Identify its key feature
It also stores the addresses of these created contracts for easy access later.Final Answer:
To create multiple similar contracts easily and manage their addresses -> Option AQuick Check:
Factory pattern = create and manage contracts [OK]
- Confusing factory with encryption or mining
- Thinking factory validates transactions
- Assuming factory works off-chain
Which of the following is the correct Solidity syntax to deploy a new contract inside a factory contract?
function create() public returns (address) {
address newContract = new ?();
return newContract;
}Solution
Step 1: Recall Solidity contract creation syntax
To create a new contract instance, usenew ContractName().Step 2: Match syntax with code snippet
The placeholdernew ?()expects the contract name without 'new' repeated.Final Answer:
ContractName -> Option AQuick Check:
Use 'new ContractName()' but only 'ContractName' inside parentheses [OK]
- Writing 'new' twice
- Using lowercase contract names
- Omitting parentheses
Consider this Solidity factory contract snippet:
contract Simple {
uint public value;
constructor(uint _value) {
value = _value;
}
}
contract Factory {
Simple[] public simples;
function createSimple(uint _val) public {
Simple s = new Simple(_val);
simples.push(s);
}
function getValue(uint index) public view returns (uint) {
return simples[index].value();
}
}What will getValue(0) return after calling createSimple(42) once?
Solution
Step 1: Understand contract creation and storage
CallingcreateSimple(42)creates a newSimplecontract withvalue = 42and stores it insimplesarray.Step 2: Check what
It returns thegetValue(0)returnsvalueof the firstSimplecontract, which is 42.Final Answer:
42 -> Option CQuick Check:
Created contract value = 42 [OK]
- Confusing contract address with stored value
- Assuming default zero value
- Thinking it returns array length
Identify the error in this factory contract code snippet:
contract Product {
uint public id;
constructor(uint _id) {
id = _id;
}
}
contract ProductFactory {
Product[] public products;
function createProduct(uint _id) public {
Product p = Product(_id);
products.push(p);
}
}Solution
Step 1: Check contract instantiation syntax
In Solidity, to create a new contract instance, you must use thenewkeyword.Step 2: Identify the missing keyword
The lineProduct p = Product(_id);missesnew, it should beProduct p = new Product(_id);.Final Answer:
Missingnewkeyword when creatingProduct-> Option BQuick Check:
Contract creation requires 'new' keyword [OK]
- Forgetting 'new' keyword
- Changing array to mapping unnecessarily
- Marking create function as view incorrectly
You want to build a factory contract that creates multiple token contracts with different initial supplies and keeps track of them. Which approach best applies the factory pattern to save gas and organize your project?
Solution
Step 1: Understand factory pattern benefits
The factory pattern helps create many similar contracts and keeps track of them efficiently.Step 2: Evaluate options for managing multiple tokens
Creating each token contract inside the factory and storing their addresses allows easy management and gas savings.Step 3: Reject other options
Hardcoding addresses is inflexible, using one contract for all tokens breaks isolation, and not storing addresses loses track.Final Answer:
Create each token contract separately and store their addresses in an array inside the factory -> Option DQuick Check:
Factory creates and tracks contracts for organization [OK]
- Hardcoding addresses reduces flexibility
- Using one contract for all tokens causes conflicts
- Not storing addresses loses track of contracts
