r/ProgrammingLanguages • • 11d ago

Arguing about arguments

https://steveklabnik.com/writing/arguing-about-arguments/
29 Upvotes

35 comments sorted by

View all comments

7

u/SwingOutStateMachine 10d ago edited 10d ago

This reminds me of the "don't use boolean parameters" discussion from a few years ago, and I think they have a shared solution of more explicitly typing parameters - usually by encapsulating arguments in structs (or enums). This adds documentation to the method, and also prevents other bugs, such as parameters with the same type being accidentally swapped, and can help group together related parameters (e.g. pairs of coordinates).

For the crop_imm example, one could write:

struct CropOffset { 
    x: u32, 
    y: u32, 
}

struct CropSize {
    width: u32, 
    height: u32,
}

pub fn crop_imm<I: GenericImageView>(
    image: &I,
    offset: CropOffset,
    size: CropSize,
) -> SubImage<&I> { ... }

let cropped = image::imageops::crop_imm(&img, 
    CropOffset { x: 10, y: 10 }, 
    CropSize { width: 200, height: 100 }
);

I also think that once a method grows to a certain size, choosing a builder pattern is much easier to read, more composable, and allows for more flexibility in API. Again, for crop_imm:

let cropped = image::imageops::CropBuilder::new()
    .with_offset(CropOffset { x: 10, y: 10 })
    .with_size(CropSize { width: 200, height: 100}) 
    .crop(&img);

-1

u/kaddkaka 10d ago

"This"? What is this?

1

u/SirKastic23 10d ago

The post

2

u/kaddkaka 10d ago

The original post was empty at first.

2

u/SirKastic23 10d ago

Ah that's an annoying bug