Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it generally bad practice to have many "initWith" parameters?

Say for instance I have an implementation of a UIView. The UIView contains a two labels, an image and a frame.

My "init" method ends up looking like:

- (id)initWithFrameAndLabelArrayAndImage:(CGRect)frame:(NSArray *)labelArray:(UIImage *)image;

Is that considered bad practice? Is it better to have a simple "initWithFrame" method and have the other label and picture as @properties?

like image 470
Vu Tran Avatar asked Dec 16 '11 01:12

Vu Tran


1 Answers

It's fine. Apple does it frequently. For example, look at NSString:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsstring_Class/Reference/NSString.html

– initWithBytes:length:encoding:
– initWithBytesNoCopy:length:encoding:freeWhenDone:
– initWithCharacters:length:
– initWithCharactersNoCopy:length:freeWhenDone:
– initWithString:
– initWithCString:encoding:
– initWithUTF8String:
– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:
– initWithData:encoding:

But, following those patterns, yours:

- (id)initWithFrameAndLabelArrayAndImage:(CGRect)frame:(NSArray *)labelArray:(UIImage*)image;

Should probably be:

- (id)initWithFrame:(CGRect)frame labels:(NSArray *)labelArray image:(UIImage *)image;

Now, having said that, I probably wouldn't pass an array of labels. I would pass the data and have the custom view take that data and create/layout the subviews. You're sort of exposing the internal views that compose your custom view in the public methods and you may want to change how you render and compose them in the future.

Another approach would be to use delegates to render the labels the labels would be rendered by calling the delegate for the data it needs - similar to a table view.

like image 62
bryanmac Avatar answered Oct 26 '22 06:10

bryanmac