DEV Community

loading...

Discussion on: Practical Advice to Good API Design

Collapse
blacklight profile image
Fabio Manganiello

"Long lists of identically typed parameters can be harmful and very error-prone" - I would argue that this can be a quite language-specific remark. Languages like Python or Perl make it easy to use keyword arguments to circumvent the curse of long function signatures:

def start_camera(device='/dev/video0',
                            resolution=(640,480),
                            color_mode='rgb24',
                            rotation=0,
                            scale=(1, 1), 
                            # ...
                           **kwargs):
    cam = Camera(device=device, ...)

# ...

# Pick only some of the parameters through named arguments
start_camera('/dev/video1', rotation=90)
Enter fullscreen mode Exit fullscreen mode

Although this can be achieved in languages like JavaScript with key-value objects:

const startCamera = (props) => {
    // ...
}

startCamera({
    device: '/dev/video1',
    rotation: 90,
})
Enter fullscreen mode Exit fullscreen mode

And in Java with, as you said, helper classes - and even though such a mechanism is also available in recent versions of Python (@dataclass) I still prefer the named arguments approach because it makes a method signature really self-explanatory.

Collapse
johannea profile image
Johanne Andersen Author

I completely agree with the named parameter approach, but I still think a long list of parameters, especially of the same type is still error-prone since you don't have to use the named parameters (I can only speak for Python and JavaScript).
Plus a long parameter list to begin with usually means bad design. But named arguments definitely make it less error-prone should you choose to go down that path.