Похожие чаты

Hi. I have a design question: I have a class that

has a static variable x storing some details.
I have a method setX to update it (it has some db calls).
x is accessed to get details in different user requests from different classes.

But each time it's accessed, it has to be updated by calling setX, which increases db calls and therefore response time.

I can periodically call setX in a schedule and not call setX in each request, but that means the user doesn't always get the updated values.
Or I can call setX whenever the db gets updated, but another dev could forget to call setX when he updates the db and introduce bugs.

What's the right way to design this type of construct? I believe this is a common issue that has a standard solution?

4 ответов

10 просмотров

)))))) I've just answered your old question, which is related to static methods and fields too)))

Read my previous answer, it has some important notes about static data in general. Now this question. I clearly see here that you are using static when it's not needed here at all. The > x is accessed to get details in different user requests is a clear sign of that you should not make it static. Let each user create their own data, that is not shared (i.e. is in instance fields, not static), make new objects for each user. You're right, this is the common task. To understand the best practice design would be to consider several things that you didn't tought about yet: - when user receives response, does he see the *persistent* state? I.e. if the application will crash right away after user receives the response, after restart will the user see same state? This is crucial part here, as this is called "consistency", and the way how to implement things mostly depends on the consistency guarantees you want to provide. Strong consistencty is the preference, thus the most common design is to guarantee that the state is already persisted (saved to DB, file, whatever what survives app restart) when user receives response for his request. So the common flow is - receive request - fetch necessary data from DB (or from cache) - calculate stuff by your business logic - write results to DB - invalidate related cache entries - return response

Simple suggestion: get rid of static. Do not store anything "globally" or "info for all users in one single place". And everything will become much more simple after that.

(continuation) - next problem to think about - when your application won't be able to handle the load of incoming requests it would need to be scaled. How will it work when there will be 2 instances of your application running? 5 instances? 20 instances? What will happen when first request of the user will be served by instance N7 and it will crash after than, and next request from the same user will land to instance N11 ? Your approach with static methods and periodic sync calls will be a pain in the ... for this real life usecases.

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

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

А чем вам питонисты не угодили?😂
.
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
Карта сайта