Best practice for condensing code? [closed]

2019-08-28 23:31发布

问题:

If you have code (objective-c) within a method that you would like to condense to a single call (for brevity or readability) what is the preferred practice.

  1. don't do it, keep all related code in the method.
  2. Add a new method to the object in question i.e. - (NSString *)formatedTime;
  3. C-Style functions, defined outside the object in question.
  4. Other i.e. something I missed.

回答1:

My primary rule when rewriting code is always to ensure whatever I write is as readable as possible. With that in mind, then, I usually:

  1. Keep all the code in the method only if it's relatively short (fits in a screen or two) and is all logically related
  2. Add a new method if the name of the new method will make it more readable, reduce duplication of code, or make the flow make more sense to a reader
  3. Avoid C-style functions unless dealing with something very low-level, or in the context of other C-style functions; basically keep with the style of the code you're rewriting
  4. Above all else, try to ensure that the method once rewritten still makes sense, does what it's supposed to do (i.e. no bugs were introduced), and can be quickly read and understood by another developer


回答2:

The other thing that I'd say is that if you break out code into additional helper methods you should declare those methods in a class extension, rather than the main header for the class. Here's an example .m file:

@interface MyClass()
- (CGRect)makeRect;
- (NSString*)formatStringFromInput:(NSString*)input;
@end

@implementation MyClass

//Implementation here

@end


回答3:

This is similar to johnw188 hint, but goes a little bit further:

In a class extension you cannot only have private methods but private properties too.

@interface MyClass()
@property(retain) MyOtherClass *aNotherObject; //declared in .h. Should be @private
- (CGRect)makeRect;
- (NSString*)formatStringFromInput:(NSString*)input;
@end

@implementation MyClass
@synthesize aNotherObject;

//Implementation here

-(void)dealloc
{
    self.aNotherObject = nil;
    [super dealloc];
}

@end

The benefit is quite clear: You get the @property/@synthesize power, but only access it from with-in the class object. private properties are only accessible on self.