Instruction file imported from diabolo-68/google-photos-backup (
.github/instructions/service-patterns.instructions.md). Copyright stays with the author.
Service Implementation Guidelines
Service Pattern
All services follow this lifecycle:
public class BackupService {
private final GooglePhotosApiService photosApi;
private final DatabaseService database;
private boolean initialized = false;
// Constructor injection
public BackupService(GooglePhotosApiService photosApi,
DatabaseService database) {
this.photosApi = Objects.requireNonNull(photosApi);
this.database = Objects.requireNonNull(database);
}
// Explicit initialization
public void initialize() {
if (initialized) {
throw new IllegalStateException("Already initialized");
}
// Setup code
initialized = true;
}
// Explicit shutdown
public void shutdown() {
if (!initialized) return;
// Cleanup code
initialized = false;
}
// Business methods
public Optional<BackupResult> backup(Path file) {
checkInitialized();
// Implementation
}
private void checkInitialized() {
if (!initialized) {
throw new IllegalStateException("Service not initialized");
}
}
}
Dependencies
- Inject via constructor, not field injection
- Use interfaces for testability
- Validate non-null in constructor
Threading
- Document thread safety guarantees
- Use appropriate synchronization
- Consider using
CompletableFuturefor async
Error Handling
- Don't swallow exceptions
- Log with context before rethrowing
- Use domain-specific exceptions