search

Home  >  Q&A  >  body text

java - Is there any elegant way to handle calls from different sources differently for the same method?

When I was writing a control.
There is a class subViewPager that inherits ViewPager. I need to use the getCurrentItem() method of this ViewPager in another place. , which means to obtain a certain coordinate of this control.

But because my ViewPager is for special effects, the coordinates returned by its getCurrentItem() may exceed the length of my data collectionsize ,

For example, the length of my data collection is size = 1024
and getCurrentItem() returns 40280

So when I call him actively, I hope that he can return to me the result of coordinates %=size: 4028 24.

At the same time, his getCurrentItem() method should return a number like 40280 when called by the system.

My original approach was to write a special method to obtain the result after %=size. Force it when you need to get this parameter.

Later I changed a bit and used new Exception().getStackTrace(); to obtain the call stack information to determine whether the method was called by the specified class. This eliminates the need to force and write a subclass-specific method.

But this approach will generate a lot of garbage memory and frequently cause GC, so consider using the first method to deal with it.
But forced transfer is always a bit unpleasant, and it feels like there is no reusability. (Although it is because of the bad code... and the reusability of subViewPager is also reduced by doing this) So I want to ask if there is any way to make the same method be called in different classes. Can you perform different operations gracefully?

淡淡烟草味淡淡烟草味2690 days ago1236

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-07-03 11:44:06

    Isn’t it enough for subViewPager to override getCurrentItem()? .

    reply
    0
  • 欧阳克

    欧阳克2017-07-03 11:44:06

    I have seen implementation solutions of similar libraries. If the business logic returned by your internal and external calls of this method is not consistent, it is recommended to define an additional method...such as getCurrentRealItem()

    reply
    0
  • Cancelreply