Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO Design Pattern for object initiation in an API

Tags:

python

oop

api

When creating an API in python, I'm not sure what approach to take in creating an instance of a basic object with init.

When creating an instance of the object in the API, the user will most likely want the object to be one of two things:

  1. An instance of an object that already exists in what the API is being called against
  2. Create a new object in what the API is being called against

Is there an accepted design pattern for this? Should init just create an empty object, and then the consumer must call a get or set method? Or maybe init should take an argument as to if this is a get or set? Or lastly, should get or set be inferred from the arguments to init?

like image 231
Kyle Brandt Avatar asked Nov 04 '22 08:11

Kyle Brandt


1 Answers

I can't think of a design pattern to match exactly what you are describing, since:

  • Factory pattern usually deals with a family (hierarchy) of classes.
  • Builder pattern usually deals with complex objects composed of many classes.

How about overloading the API to the following?

When invoked with no arguments:

custom_API()

then just create a new basic object with some reasonable default values and let the consumer use get / set to configure it.

When invoked with a lookup key of some sort:

custom_API("abc")

then return the corresponding object, or a list of objects of the lookup key is vague, or None if no matching object can be found.

like image 129
sampson-chen Avatar answered Nov 12 '22 16:11

sampson-chen