Skip to content

Instantly share code, notes, and snippets.

@ahsan-ikram
Last active July 11, 2025 16:07
Show Gist options
  • Select an option

  • Save ahsan-ikram/91a1c1df1d95a6edc9f8ac746a575701 to your computer and use it in GitHub Desktop.

Select an option

Save ahsan-ikram/91a1c1df1d95a6edc9f8ac746a575701 to your computer and use it in GitHub Desktop.
The Clean Code Talks -- Unit Testing by Miško Hevery (Google Techtalks)
According to misko hevery
Work in the constructor such as: creating/initializing collaborators, communicating with other services,
and logic to set up its own state removes seams needed for testing, forcing subclasses/mocks to inherit
unwanted behavior. Too much work in the constructor prevents instantiation or altering collaborators in the test.
Warning Signs for class constructors:
> new keyword in a constructor or at field declaration
> Static method calls in a constructor or at field declaration
> Anything more than field assignment in constructors
> Object not fully initialized after the constructor finishes (watch out for initialize methods)
> Control flow (conditional or looping logic) in a constructor
> CL does complex object graph construction inside a constructor rather than using a factory or builder
> Adding or using an initialization block
WHY THIS IS A FLAW?
> It violates the Single Responsibility Principle
> Testing Directly is Difficult
> Subclassing and Overriding to Test is Still Flawed
> It Forces Collaborators on You
- Feature complete
- Squashing bugs
- Improving error messages
- Preliminary performance tests
- Developing migration guide
> How to write hard to test code?
>> Mixing new (object creation) with logic
>> Looking for things
>> Work in constructors
>> Global state (needs test to run in order)
>> Singletons
>> Static methods (similar to procedural code)
>> Deep inheritance (uneccessarily make you test classes up in the hierarchy)
>> Too many conditionals
>> Mixing service/value
>> Mixing concerns (contradicts testing one functionality at a time)
> How to write testable code?
>> Good OO
>> Dependency Injections
>> Test driven development
>> A whole lot about un-testable code
> What are different type of tests?
>> Scenario Tests
>>> Test whole system pretending to be a user
>> Functional Tests
>>> Test collection of classes as subsystem
>> Unit Tests
>>> Test individual classes and methods in isolation
> Areas of software construction
>> Object graph construction and lookup
>> Business logic
>>> Separate above two for better testing (use dependency injections)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment