- This topic is empty.
-
AuthorPosts
-
January 7, 2026 at 12:49 am #5929
📌 Context (Code First)
Consider the following simplified phonebook application structure:
class PhoneBook: def __init__(self): self.__persons = {} # Return all entries (in dictionary format) def all_entries(self): return self.__personsclass PhoneBookApplication: # the rest of the user interface code # Method executed when the program exits def exit(self): self.__filehandler.save_file( self.__phonebook.all_entries() )A common beginner question is:
Why does
exit()passself.__phonebook.all_entries()instead of
self.__phonebook.all_entries().items()?
Q1. What does
all_entries()return?Answer:
all_entries()returns the entire phonebook data structure:{ "Alice": ["123", "456"], "Bob": ["999"] }This is a dictionary, which is the natural and complete representation of the phonebook’s data.
Q2. What does
.items()return then?Answer:
.items()does not return a dictionary.It returns a special dictionary view object:
dict_items([ ("Alice", ["123", "456"]), ("Bob", ["999"]) ])This object is mainly meant for looping, not for storing or transferring data.
Q3. Why shouldn’t
.items()be passed tosave_file()?Answer:
Because
save_file()is responsible for deciding how to write data to a file, not for receiving pre-processed loop data.Passing
.items():- Changes the data type
- Reduces flexibility
- Pushes storage logic into the UI layer
This breaks good program design.
Q4. Where should
.items()actually be used?Answer:
Inside the
FileHandler, where iteration is needed.Example:
def save_file(self, phonebook_dict): for name, numbers in phonebook_dict.items(): # write to fileHere,
.items()is used at the correct layer, where iteration logic belongs.
Q5. What design principle is being followed here?
Answer:
👉 Separation of Concerns
PhoneBook→ owns the dataFileHandler→ handles file storagePhoneBookApplication→ coordinates actions
Each class has one clear responsibility.
Q6. What would go wrong if we passed
.items()directly?Answer:
save_file()would be limited to one iteration style- Data could not be reused or modified easily
- The UI would start controlling storage behavior
In larger programs, this leads to tight coupling and fragile code.
Q7. What is the correct mental model to remember?
Answer:
- Use
all_entries()to transfer data - Use
.items()to loop over data - Never mix iteration helpers with data ownership
✅ Final Takeaway
Return full data structures from your classes.
Use.items()only at the point where looping is actually needed.This design makes your code cleaner, safer, and much easier to extend later — especially as your applications grow beyond simple scripts.
-
AuthorPosts
- You must be logged in to reply to this topic.
