Похожие чаты

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 ответов

13 просмотров

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.

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

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

А чем вам питонисты не угодили?😂
.
79
or any website to buy prepaid card with xmr that's not trocador that's down?
Umbrella Party Partner
18
Всем привет, написал код ниже, но он выдает сегфолт, в чем причина? #include <stdio.h> #include <stdlib.h> #include <string.h> struct product { char *name; float price; };...
buzz базз
75
Hi, I can't understand promises in JavaScript and what we should use them for (maybe the teacher didn't teach well XD). Do you have a solution for this? And are promises used...
A
29
Ещё такой вопрос. Мне необходимо хранить пароль пользователя локально. Для этого планирую использовать ini файл. Это для автозаполнения полей логин и пароль при авторизации. Е...
Евгений
19
всем доброго времени суток! имею вопрос: как понять ТОЧНО, что на нексус производится атака или он перегружен? исходные данные: - Nexus OSS 3.67.1-01 на OrientDB - Total co...
Michael Kostelcev
3
Ты просто гитлеровскую эстетику плохо понимаешь. Он же всё под Цезаря делал. А это как бы запрещённый приём в политике. Пиджаки они зачем все носят? Чтобы показать что они тип...
Ivan Kropotkin
4
Xem delist ho rha hai agr naa bhechu toh kya hoga after 1 july?
ABHI
27
i need usdt exchanged to xmr without kyc any site there ?
Certained
12
Did you guys see the latest tweet from TonGifts? 🚀
Mike
44
Карта сайта