Похожие чаты

Hi. I have a question regarding code organization. I

have an interface called Action with 2 implementing classes: Ticket and Email. I have a static method populate() in each class to populate details of the action in a static variable in the class.

I want to add this method to the Action interface, because I'm storing a list of implementation classes (ex. Ticket.class`) in an ArrayList of `Action`s. While iterating the list, I want to call `populate() on each class.

The problem is populate() can't be added in the interface as it is static and static methods need to be implemented in the interface itself, which I can't do as the method implementation varies for each class.

Is there an alternative to adding static method in the interface here?

1 ответов

22 просмотра

Wow, I missed this nice question! There are many mistakes in your design, which are very nice to do when you're learning. I mean, by doing them and trying to implement things, you will see it very clearly why it was not a good idea. 1. > I have a static method populate() in each class to populate details of the action in a static variable in the class. Using static here doesn't make sense because - if these "details of the action" are specific for this particular action among the millions other actions that have occurred already, or will occur in the future, then such data should not be static, it should live in the instance, as it's specific for the particular instance of action, and the lifespan of this data is the same as the lifespan of the Action instance - if this data is not instance specific, but generic for ALL the existing and future actions, then it doesn't make sense to create a separate "populate" method for it, just populate it in the static initializer block which gets called automatically when jvm first sees your class 2. > because I'm storing a list of implementation classes The whole idea of having interfaces is to dissect callers of the methods from implementation of the methods. So the callers should never know who implements those methods. Thus you should never store "list of known implementation classes" in 99.99% of cases. Why it's bad? Because this way the code becomes tightly coupled. Now every time some developer adds new implementation of "Action", he/she should not forget to add it to the list. Do you know "Collection" interface? Imagine that each time google or apache commons would want to add new collection implementation tuned for some specific use-case, they would need to ask jdk developers to add new "NewSuperDuperTunedCollectionImpl.class" to the "Collection" class. Terrible idea, right? 3. > The problem is populate() can't be added in the interface as it is static and static methods need to be implemented in the interface itself Exactly, this is by design. Interfaces are NOT for static methods. They are for defining ... (surprise) an interface of an object! For defining contract in other words, or list of required method signatures that the target object should have, so the caller can know that there are such methods in the target object. Static methods are for manipulating application global data. When you become more experienced, follow the rule of thumb - avoid using static by any means. Using static is good for constants only, in other cases static fields and methods will be more harmful than useful. You will feel static hell when you start writing tests for your code. But until then, play around with static fields and methods to understand what it is and how it works.

Похожие вопросы

Обсуждают сегодня

30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
Чёт не понял, я ж правильной функцией воспользовался чтобы вывести отладочную информацию? но что-то она не ловится
notme
18
Привет)) уже кажется эту тему перемусолили, но вот я так и не понял. Я сейчас сижу на 27дюймов 2к мониторе. На Актуальной макоси, если я куплю 27д 4к монитор: - будет ли изобр...
Vladislav Piskunov
16
Also, why can’t the community have a vote/ say when it comes to initiatives like buybacks. Isn’t the point of crypto decentralisation? Don’t we deserve input as long term supp...
👨🏽‍🦰
13
any reference of this implementation?
BitBuddha
29
Страшнейшая правда про списки ЦБ. С первых дней жизни P2P сферы, молодые человеки, начитавшись законодательной базы и "внутренних" документов, решили, что им противостоит сер...
Foxcool
3
У меня есть функция где происходит это: write_bit(buffer, 1); write_bit(buffer, 0); write_bit(buffer, 1); write_bit(buffer, 1); write_bit(buffer, 1); w...
~
14
Hi guys, any problem with Pulsebrige? Trying to transfer from wETH to ETH. First it tells me to connect my metamask "through mobile app" not desktop. Then I did and confirmed ...
Snowflakecrypto
13
Карта сайта