Reputation: 45
In OOP coding, there is a long-standing naming convention to name accessor/mutator methods get_something and set_something. These directly access or manipulate the properties.
However, if the type of something is like a dict
or list
in Python, what is a better choice to name the manipulating-function?
For example,
I have a list
named booklist
, which contains the name of books that I want to read. I want to name the function that appending a new book into the booklist
.
booklist = ["Clean Code", "Code Complete"]
def insert_book_into_booklist(new_book):
booklist.append(new_book)
Is there any better choice of insert_book_into_booklist
? Just like append_book_in_booklist
or set_booklist
?
I have a dict
named booklist
. The key is the name of books that I want to read and the value is the International Standard Book Number (ISBN). I want to name the function that inserts a new book into the booklist
.
booklist = {"Clean Code": "9789862017050", "Code Complete": "9789536185344"}
def insert_book_into_booklist(new_book, isbn):
if new_book not in booklist:
booklist[new_book] = isbn
Is there any better choice of insert_book_into_booklist
? Just like set_booklist
?
Thank you.
Upvotes: 1
Views: 3803
Reputation: 2072
As you've mentioned OOP, lets pretend, that your "booklist" is a member of a class:
class BookList(object):
def __init__(self):
self.booklist = []
So, if you want to add new book into your list, name your method as a verb, that doing what you need, for example "add_book". Also, you don't need to add "_into_booklist", bacause your class is a BookList itself and this is enough to understand where the book would be added:
class BookList(object):
def __init__(self):
self.booklist = []
def add_book(book):
self.booklist.append(book)
Also, you can make this method work with ISBN:
class BookList(object):
def __init__(self):
# creating dict, not list
self.booklist = {}
def add_book(book, isbn):
self.booklist[book] = isbn
Also, as Ev. Kounis said in comment, you can omit "_book" part of method, and leave just "add", but if your class would became more complex in future, this name could get ambiguos. For example, if you have "add_book" method, you can add "add_books" method later (for adding lots of books at a time), and the meaning of that names are easy to understand. But if you short it down, to "add", it'll be less clear, what does this method adds actually.
Upvotes: 3