Source Code
197 subscribers
30 photos
3 files
80 links
Download Telegram
9 важнейших принципов разработки программного обеспечения

1. Будь проще, Саймон (Keep It Simple Simon, KISS):
*Ваши методы должны быть небольшими, не превышающими 40-50 строк.
*Каждый метод должен решать только одну проблему.
*У вас в проекте много условий? Убедитесь, что вы разбили их на более мелкие блоки кода.

2. Вам это не понадобится (You Aren't Gonna Need It, YAGNI):
*Как развивающийся разработчик программного обеспечения, всегда начинайте с добавления всего нескольких методов в класс. Когда ваш проект начнет обретать форму и возникнут новые требования, вы можете добавить больше функций. Таким образом, вы будете придерживаться принципов бережливой разработки программного обеспечения.

3. Дважды отмерь и один раз отрежь (Measure Twice and Cut Once):
*Дважды проверьте все требования проекта, чтобы убедиться, что вы не ничего не упускаете и не добавляете лишнего в свой код. После этого сделайте наброски, которые будут направлять весь процесс для получения высококачественного кода. Всегда тестируйте свой проект с самых основ, чтобы убедиться, что все в порядке.

4. Не повторяйся (Don’t Repeat Yourself, DRY):
*При написании кода не повторяйтесь. То есть избегайте копирования кода в разные места. В противном случае дальнейшее обслуживание будет трудным. Причина в том, что вам придется изменять код в разных местах.

5. Бритва Оккама:
*Создатель этого принципа - Уильям Оккам, философ 14 века. Принцип гласит, что в группе гипотез всегда выбирайте ту, которая имеет наименьшее количество предположений. Следуя принципу бережливой разработки программного обеспечения, всегда начинайте с максимально простого кода. Затем осторожно увеличивайте сложность по мере необходимости.

6. Сначала большое проектирование (Big Design Up Front, BDUF):
*Этот принцип разработки программного обеспечения утверждает, что разработчик должен сначала завершить проектирование. После этого проект можно реализовать. Сторонники утверждают, что такой подход помогает обнаруживать проблемы на стадии требований и быстро их решать.

7. Избегайте преждевременной оптимизации:
*Дональд Кнут утверждал, что корень всего зла в программировании - преждевременная оптимизация. Мы все согласны с тем, что оптимизация ускоряет процесс разработки и снижает потребление ресурсов. Однако она приведёт к неприятным последствиям, если вы займётесь ей слишком рано.

8. Наименьшее удивление:
*Принцип наименьшего удивления гласит, что желательно разработать функцию, которая не имеет высокого коэффициента удивления. Компоненты системы должны вести себя так, как того ожидают конечные пользователи. Поэтому результаты вашего проекта будут прибыльными только в том случае, если они очевидны, предсказуемы и последовательны. В противном случае пользователи будут уклоняться от использования функций или структур, которые удивляют или сбивают их с толку.

9. Закон Деметры:
*Закон Деметры пытается разделить обязанности между классами и уменьшить связанность между ними.

Настоятельно рекомендуется:
*Обеспечить независимость программных объектов друг от друга.
*Уменьшить общение или связь между разными классами.
*Поместить связанные классы в один и тот же пакет, модуль или каталог для достижения согласованности.

P.S: О solid вы и так знаете)
#science #news

Скорость света ближе, чем казалось

Пионер варп-двигателя и бывший специалист НАСА по варп-двигателю доктор Гарольд Дж. «Сонни» Уайт сообщил об открытии настоящего, реального «варп-пузыря». И, по словам Уайта, этот первый в своем роде прорыв его команды, Института безграничного космического пространства (LSI), устанавливает новую отправную точку для тех, кто пытается создать полноразмерный космический корабль, способный к деформации.

https://thedebrief.org/darpa-funded-researchers-accidentally-create-the-worlds-first-warp-bubble/
Мы бы сделали какой-нибудь особый пост под новый год, но я уже достаточно выпил, чтобы лечь спать. Хорошего года, успешных проектов.
#java
Сохранение данных в постоянной памяти, используя Preferences.

Если вам нужно сохранять конфигурацию, информацию о пользователе, о программе на всех платформах одинаково и вы не хотите беспокоиться о разных путях, или писать отдельные методы для работы с файлами и переживать об их безопасности, то самый лучший и самый простой вариант это Preferences.

Если очень просто то это обычное API, позволяющее записывать значения по принципу ключ/значения. И основная особенность того, что на всех платформах оно будет адаптироваться. Фактическое хранение данных зависит от платформы.

Вот пример кода (Читайте комментарии):
import java.util.prefs.Preferences;

class PreferenceTest {
//Created node for storage
private final Preferences prefs = Preferences.userRoot().node(this.getClass().getName());

public void setPreference() {
//Keys
final String key1 = "key1";
final String key2 = "key2";
final String key3 = "key3";

//Here we define variables with default values
System.out.println(prefs.getBoolean(key1, true));
System.out.println(prefs.get(key2, "Hello World"));
System.out.println(prefs.getInt(key3, 50));

prefs.putBoolean(key1, false);
prefs.put(key2, "Bye bye");
prefs.putInt(key3, 0);

//You should write key and default value for getting present value
System.out.println(prefs.getInt(key3, 50));

prefs.remove(key1);
}

public static void main(String[] args) {
PreferenceTest test = new PreferenceTest();
test.setPreference();
}
}

Запустите программу дважды. Значение «key1» должно быть записано со значением по умолчанию (true) в командную строку, так как значение preference было удалено в конце метода. Значение «key2» и «key3» должно было измениться после первого вызова.

Useful link - https://spec-zone.ru/RU/Java/Docs/7/api/java/util/prefs/Preferences.html
#info
👋🏻 Мы решили делать посты на английском.

На это есть несколько причин:
1) количество охватываемой аудитории
2) хоть какая, но прокачка языка
3) легкость поиска контента

Всем тем, кто отпишется - спасибо что оставались с нами, несмотря на то, что мы часто забиваем на это дело ввиду работы и учебы в универе.

Если кому-то было интересно и/или полезно - не зря мы их писали 🐸
#java
Difference between Concurrency and Parallelism

Concurrency
:
By Concurrency, we mean executing multiple tasks on the same core. In simpler terms, it relates to processing more than one task at the same time. It is a state in which multiple tasks start, run, and complete in overlapping time periods. An application capable of executing multiple tasks virtually at the same time is called a Concurrent application.

In case the computer only has one CPU or one Core the application may not make progress on more than one task at the exact same time. Instead, divide the time and the Core/CPU among various tasks. Concurrency is useful in decreasing the response time of the system.

Parallelism:
Parallelism is the ability of an application to split up its processes or tasks into smaller subtasks that are processed simultaneously or in parallel. It is the mechanism in which multiple processes execute independently of each other where each process acquires a separate core. This utilizes all the cores of the CPU or
#java
Sealed Classes

Java 15 introduces Sealed Classes, a preview language feature, that allows classes/interfaces to restrict which other classes/interfaces may extend or implement them. Here is an example:

In the example above, Vehicle is a sealed class, which specifies three permitted subclasses; Car, Truck and Motorcycle.

Sealing serves two main purposes:

It restricts which classes or interfaces can be a subtype of a class or interface and thus preserves the integrity of your API.
It allows the compiler to list all the permitted subtypes of a sealed type (exhaustiveness analysis), which will (in a future Java release) enable switching over type patterns in a sealed type (and other features). For example, given the following switch statement, the compiler will detect that there is a case statement for every permitted subclass of Vehicle (so no default clause is needed) and it will also give an error if any of them are missing
#java
What is the structure of Java Heap?

The JVM has a heap of runtime data. Memory for all class instances and arrays is allocated to this heap, which is created at the JVM start-up. Heap memory for objects is reclaimed by the garbage collector, which is an automatic memory management system.

Both living objects, which are accessible by the application and won’t be part of garbage collection, and dead objects, which will never be accessible by the application but haven’t yet been collected by the garbage collector, make up the heap memory space until the dead objects eventually end up in the garbage collector.
You have an interface(Clickable) with the default click() method, and the class that implements it(Mouse). How to call the default interface method from the implemented click method?
Anonymous Quiz
22%
Clickable.super.click()
24%
Clickable.click()
37%
super.click()
17%
Mouse.super().click()
Result of the main method will be
Anonymous Poll
45%
false
24%
true
24%
compilation error
7%
runtime error
#java StreamAPI
We have a source - our collection. We don't copy all the elements at once, but stretch it, loading the elements in stages, doing some operations.

It's like a file stream, only instead of reading byte by byte, we get references to objects[1] (if we don't have a primitive stream - IntStream, etc.)

Therefore, when the stream is open (we are working with the address space of our data structure), we cannot change it.

[1]By the way, this is a stream of object references, not a stream of bytes. It means we can modify objects of the collection by reference(setters, getters, and so on).

That is, if we had a collection with objects of the Person type, we could do something like this:
personList.stream().forEach(x->x.setName("New name"));
Hi there. If there are any suggestions for improving the channel - write.

One of them, did you have a desire to improve the post, or even write your own?

If so, how do you like the idea of making a bot in which you can write your post, or some additions to one of the existing ones.
#jvm
Metaspace?

Metaspace is a special partition of memory in the Java virtual machine. It is located in the Runtime Data Area and is not part of the heap.

It is used to manage memory for metadata class.

Metadata of a class is a describtion of class fields, methods stored in a special object. Every class has own (meta) Class object.

Metadata class are allocated when classes are loaded. Their lifetime is usually scoped to that of the loading classloader - when a loader gets collected, all class metadata it accumulated are released in bulk. The memory manager does not need to track individual allocations for the purpose of freeing them.

Notes:
- Metaspace by default auto increases its size
- Max size can be set using XX: MetaspaceSize
- Comparatively effective Garbage collection. Deallocate class data concurrently and not during GC pause.
- In versions before Java 8 instead of Metaspace was PermGen Space
The best but not ideal map of JVM

Obviously not the prettiest blue line😁
#news #java

Oracle doesn't want Java EE any more

Oracle wants someone else to lead enterprise Java, though it says it will stay involved. Apache and Eclipse are likely candidates to take over Java EE.

Oracle wants to end its leadership in the development of enterprise Java and is looking for an open source foundation to take on the role.

The company said today that the upcoming Java EE (Enterprise Edition) 8 presents an opportunity to rethink how the platform is developed. Although development is done via open source with community participation, the current Oracle-led process is not seen agile, flexible, or open enough. ”We believe that moving Java EE technologies to an open source foundation may be the right next step, to adopt more agile processes, implement more flexible licensing and change the governance process,” Oracle said in a statement.
Why in functional programming languages recursion is faster compare to cycle?

Hi folks. I haven't written anything in a long time but now I have interesting topic to share.

You probably know that in Java recursion is much slower compare to loops. And It makes sense, because in recursion each time is created some stack frame. Each stack frame require some memory allocation and so on. So when we use recursion all time time during invocation your size of stack frames increasing. Same stuff in C++/C and in C#.

You can check it by writing Fibonacci numbers i.e.

But recently I figure out that in Haskell recursion works faster. And in mostly functional programming languages. Bot of course id depends on algorithm. The main reason is - Compiler is better in optimizing pure functions. He can make optimization more eagerly and aggressive.

"The key concept here is purity: a pure function is a function with no side effects and no state. Functional programming languages generally embrace purity for many reasons, such as reasoning about code and avoiding non-obvious dependencies. Some languages, most notably Haskell, even go so far as to allow only pure code; any side effects a program may have (such as performing I/O) are moved to a non-pure runtime, keeping the language itself pure."