问题
I have a method that performs an action and returns a value. For example from the input number it will update class's input history, then generate and return an input record. So how do I name this method?
I think even C has this problem, e.g. fopen function does open a file and return a handler. But with Objective C convention it seems difficult to name the method.
From apple document for cocoa name convention and also from this article cocoa with love They both said "If a method performs an action the first word should indicate that action" and "If a method returns a value the first word normally indicates what will be returned"
So if I name something like callRecordFromNumber:(NSString*) number
, it only indicates the returned value, not the action it performs. If I name something like updateCallRecordFromNumber:(NSString *) number
, it only indicate the action, not the returned value.
BTW, I do consider separate it into 2 methods, but the thing is the new record is generated alongside with the action is performed. The code like this: creating a new one if not exists, then update history record. And the actual code has several types of histories (say, missed call history, rejected call history, total history), and record is generated and updated for its own history. So separating it into 2 methods will introduce too many duplicated codes. Seems not a good option here.
Record *record = totalHistory[number];
if (record !=nil ) return record;
record = [[Record alloc] initWithNumber:number];
record.type = [self callType:number];
totalHistory[number] = record;
switch (record.type) {
case -1: /*missed call*/ {
missedHistory[number] = record;
break; }
case 0: /*normall call*/ {
acceptedHistory[number] = record;
break; }
case 1: /*rejected call*/ {
rejectedHistory[number] = record;
break; }
...
}
return record.
---- Update ----
Following 2 discussions are helpful too.
How to name a method that both performs a task and returns a boolean as a status?
Naming functions that retrieve a value
Now I am using the method name like this, valueByPerformed..., e.g. recordByUpdatedCallHistoryFrom:
Wordy :( I wish there was a better name!
---- update ----
swift 3.0 naming guideline, e.g. Verbs vs Nouns Naming Convention, like sort vs sorted gave me some new thought about this question. Now I do think valueByPerformed is probably a good name :D
回答1:
It sounds like you're letting the limitations of some other code prevent you from writing clean code. Don't let it. What exactly is stopping you from doing something like this...?
NSNumber *myID = @(123);
[self updateCallRecordWithID:myID];
Record *myRecord = [self callRecordWithID:myID];
- (void)updateCallRecordWithID:(NSNumber *)recordID {
history[number] = [[Record alloc] initWithNumber:recordID];
}
- (Record *)callRecordWithID:(NSNumber *)recordID {
return history[recordID];
}
来源:https://stackoverflow.com/questions/24154814/objective-c-naming-convention-for-method-performs-an-action-and-returns-a-value