John Baum
John Baum

Reputation: 3331

Refactoring methods that are very similar

I am trying to refactor two methods and am running into some issues. The methods are very similar and look like this:

- (void)methodOne:(NSString *)id idValue:(NSString *)idValue foo:(NSString *)bar parcel:(NSString)parcel anotherId:(NSString *) anotherIdValue:(NSString *)anotherIdValue{
  NSDictionary *params = @{id: idValue,
                           bar: parcel,
                           anotherId: anotherIdVaule};

  [self requestWithParams:params
                 method:POST];
}

- (void)methodTwo:(NSString *)id idValue:(NSString *)idValue foo:(NSString *)bar parcel:(NSString)parcel {
  NSDictionary *params = @{id: idValue,
                          bar: parcel};

  [self requestWithParams:params
                 method:POST];
}

How can I do this?

Upvotes: 2

Views: 34

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

One way would be to call the first method from the second method, in the same way that you call the designated initializer from other initializers:

- (void)methodOne:(NSString *)id idValue:(NSString *)idValue foo:(NSString *)bar parcel:(NSString)parcel anotherId:(NSString *) anotherIdValue:(NSString *)anotherIdValue{
  NSMutableDictionary *params = [@{id: idValue, bar: parcel} mutableCopy];
  if (anotherId != nil && anotherIdVaule != nil) {
      [params setObject:anotherIdVaule forKey:anotherId];
  }
  [self requestWithParams:params
                 method:POST];
}

- (void)methodTwo:(NSString *)id idValue:(NSString *)idValue foo:(NSString *)bar parcel:(NSString)parcel {
  [self methodOne:id idValue:idValue foo:bar parcel:parcel anotherId:nil anotherIdValue:nil];
}

Upvotes: 1

Related Questions