# Refactoring two similar methods into a single Angular service

I am trying to create a service for two similar-but-still different methods:

Method one is this:

scope.computeStyle = (element, rowComponent) ->
elementHash = {}
if element.type == 'table'
elementHash.height = 600
if rowComponent?.height?
elementHash.height = rowComponent.height
else if element.type == 'single_value'
elementHash.height = 200
elementHash.width = 800
return elementHash


Method two is this:

scope.computeStyle = (component) ->
elementHash = {}
if component.element.type == 'table'
elementHash.height = 600
if component.height?
elementHash.height = component.height * 50
else if component.element.type == 'single_value'
elementHash.height = 200
elementHash.width = 800
return elementHash


What I am confused about is that method one has two inputs, while method one has one input.

There are also two idiosyncrasies in the two where we could compute a component.height * 50 for method two while method one, we can ignore that.

I tried something like the following -- to call computeStyle(element, rowComponent) when used in the controller for method one, and computeStyle(element, ""), and then check if the second input is an empty string. Then in the implementation, I would have method one be one code block, and method two be a second code block like:

scope.computeStyle = (myElement, rowComponent) ->
elementHash = {}
if rowComponent == ""
if myElement.element.type == 'table'
elementHash.height = 600
if myElement.height?
elementHash.height = myElement.height * 50
else if myElement.element.type == 'single_value'
elementHash.height = 200
elementHash.width = 800
return elementHash
else
if myElement.type == 'table'
elementHash.height = 600
if rowComponent?.height?
elementHash.height = rowComponent.height
else if myElement.type == 'single_value'
elementHash.height = 200
elementHash.width = 800
return elementHash


But that is even more unreasonable than having two separate methods in two different files.

• Please tell us what these code snippets do (ideally with usage examples) so that your intentions are clear and so that we don't have to reverse-engineer your code. Also reticle your question to state the purpose of the code rather than how you would like to see it transformed, as per the site guidelines. See How to Ask. – 200_success Jan 11 '17 at 3:51