-1

I am writing an implementation of a binary search tree and in doing this I need a method that splits an array in two.

I am unsure where it is appropriate to place this method. What I mean by "where to place" is if I am going to monkey patch the array class, create a class method belonging to Tree, create a global method or lastly do something else which I have not thought of.

Here is some code to further describe the alternatives I have thought of.

Alternative 1: Monkey patch

class Array
  def split
    each_slice(@size/2).to_a
  end
end

Alternative 2: Class method

class Tree
  def Tree.split(a)
    a.each_slice(a.size/2).to_a
  end
end

Alternative 3: Global method

def Tree.split(a)
  a.each_slice(a.size/2).to_a
end

Where is it appropriate to place this method?

As always thanks in advance for answering my question

Olav

2
  • What's the intended programming language?
    – Martin K
    Commented Jan 20, 2020 at 20:09
  • The intended language is Ruby
    – fossegrim
    Commented Jan 20, 2020 at 21:17

1 Answer 1

1

Unfortunately, there is no one size fits all answer.

Monkey patching is not generally a good idea as it places logic in places people don't think to look, especially new people who are looking at the API docs and trying to figure out where the split method is. However, there could be a very good reason to do it. For example if you think you're going to use Array.split nearly everywhere.

Instance v.s. class method is just the same old question. Does the logic need members of the instance? If yes then it's an instance method, if no, then it's a class method.

1
  • A refinement would make sense in this case. All the elegance of a monkey patched method (it looks like it was built in all along), without globally effecting the method tables in a way that might interfere with other monkey patches.
    – Alexander
    Commented Apr 17, 2021 at 21:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.