Skip to content

Instantly share code, notes, and snippets.

@isaacssemugenyi
Created January 8, 2026 07:18
Show Gist options
  • Select an option

  • Save isaacssemugenyi/feef40bf5a53e1d9ed4b5ecc2f1b8553 to your computer and use it in GitHub Desktop.

Select an option

Save isaacssemugenyi/feef40bf5a53e1d9ed4b5ecc2f1b8553 to your computer and use it in GitHub Desktop.
"""
**************************************
ADDRESS BOOK (REFACTORED VERSION)
Behavior preserved, design improved
**************************************
"""
from datetime import datetime
class AddressBook:
def __init__(self, clock=None):
self.contacts = []
self.last_id = 0
self.clock = clock or (lambda: datetime.now().isoformat())
def add_contact(self, name, phone, email, address):
if not name or not phone:
return False
if any(c["phone"] == phone for c in self.contacts):
return False
self.last_id += 1
self.contacts.append({
"id": self.last_id,
"name": name,
"phone": phone,
"email": email or "",
"address": address or "",
"created_at": self.clock()
})
return True
def get_all_contacts(self):
return list(self.contacts)
def find_contact_by_phone(self, phone):
if not phone:
return None
return next((c for c in self.contacts if c["phone"] == phone), None)
def update_contact(self, phone, new_name, new_email, new_address):
contact = self.find_contact_by_phone(phone)
if not contact:
return False
if new_name:
contact["name"] = new_name
if new_email:
contact["email"] = new_email
if new_address:
contact["address"] = new_address
contact["updated_at"] = self.clock()
return True
def delete_contact(self, phone):
contact = self.find_contact_by_phone(phone)
if not contact:
return False
self.contacts.remove(contact)
return True
def search_contacts(self, keyword):
if not keyword:
return []
return [
c for c in self.contacts
if keyword in c["name"]
or keyword in c["phone"]
or keyword in c["email"]
]
# ---------- Backward-compatible API ----------
_book = AddressBook()
def add_contact(*args):
return _book.add_contact(*args)
def get_all_contacts():
return _book.get_all_contacts()
def find_contact_by_phone(phone):
return _book.find_contact_by_phone(phone)
def update_contact(*args):
return _book.update_contact(*args)
def delete_contact(phone):
return _book.delete_contact(phone)
def search_contacts(keyword):
return _book.search_contacts(keyword)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment