BOOKJAVA Telegram 3907
🧠Принципы SOLID

📌 S — Single Responsibility Principle (SRP)

Класс должен иметь только одну причину для изменения.


// Плохо: один класс делает и валидацию, и сохранение
class UserService {
void register(User user) {
if (user.email().isBlank()) throw new IllegalArgumentException();
userRepository.save(user);
}
}

// Хорошо: разбили ответственности
class UserValidator {
void validate(User user) { /*...*/ }
}
class UserService {
void register(User user) {
validator.validate(user);
userRepository.save(user);
}
}



📌 O — Open/Closed Principle (OCP)

Классы открыты для расширения, но закрыты для изменения.


// Используем Strategy вместо if-else
interface DiscountStrategy {
BigDecimal apply(BigDecimal price);
}
class BlackFridayDiscount implements DiscountStrategy {
public BigDecimal apply(BigDecimal price) { return price.multiply(new BigDecimal("0.8")); }
}
class CheckoutService {
BigDecimal checkout(BigDecimal price, DiscountStrategy strategy) {
return strategy.apply(price);
}
}



📌 L — Liskov Substitution Principle (LSP)

Объекты подклассов должны заменять объекты суперклассов без ошибок.

⚠️ Нарушение LSP вызывает баги, когда подкласс меняет поведение базового класса.


class Bird {
void fly() { /*...*/ }
}
class Ostrich extends Bird {
void fly() { throw new UnsupportedOperationException(); } // нарушает LSP
}


Решение — выносить общее поведение в интерфейсы по возможностям, а не по наследованию.


📌 I — Interface Segregation Principle (ISP)

Лучше несколько маленьких интерфейсов, чем один жирный.


// Плохо: интерфейс заставляет имплементировать ненужное
interface Machine {
void print(); void scan(); void fax();
}

// Хорошо: разделение по возможностям
interface Printer { void print(); }
interface Scanner { void scan(); }



📌 D — Dependency Inversion Principle (DIP)

Модули верхнего уровня не должны зависеть от низкоуровневых. Зависимость — от абстракций.


// Вместо прямой зависимости от класса — интерфейс
interface NotificationSender {
void send(String message);
}
class EmailSender implements NotificationSender { /*...*/ }
class UserNotifier {
private final NotificationSender sender;
public UserNotifier(NotificationSender sender) {
this.sender = sender;
}
}


💡 Spring идеально подходит для соблюдения DIP — внедрение зависимостей через @Autowired или @Bean.


Если вы соблюдаете SOLID — ваш код легче тестировать, расширять и поддерживать. Но без фанатизма: балансируйте с принципами KISS и YAGNI.

👉@BookJava
👍73



tgoop.com/BookJava/3907
Create:
Last Update:

🧠Принципы SOLID

📌 S — Single Responsibility Principle (SRP)

Класс должен иметь только одну причину для изменения.


// Плохо: один класс делает и валидацию, и сохранение
class UserService {
void register(User user) {
if (user.email().isBlank()) throw new IllegalArgumentException();
userRepository.save(user);
}
}

// Хорошо: разбили ответственности
class UserValidator {
void validate(User user) { /*...*/ }
}
class UserService {
void register(User user) {
validator.validate(user);
userRepository.save(user);
}
}



📌 O — Open/Closed Principle (OCP)

Классы открыты для расширения, но закрыты для изменения.


// Используем Strategy вместо if-else
interface DiscountStrategy {
BigDecimal apply(BigDecimal price);
}
class BlackFridayDiscount implements DiscountStrategy {
public BigDecimal apply(BigDecimal price) { return price.multiply(new BigDecimal("0.8")); }
}
class CheckoutService {
BigDecimal checkout(BigDecimal price, DiscountStrategy strategy) {
return strategy.apply(price);
}
}



📌 L — Liskov Substitution Principle (LSP)

Объекты подклассов должны заменять объекты суперклассов без ошибок.

⚠️ Нарушение LSP вызывает баги, когда подкласс меняет поведение базового класса.


class Bird {
void fly() { /*...*/ }
}
class Ostrich extends Bird {
void fly() { throw new UnsupportedOperationException(); } // нарушает LSP
}


Решение — выносить общее поведение в интерфейсы по возможностям, а не по наследованию.


📌 I — Interface Segregation Principle (ISP)

Лучше несколько маленьких интерфейсов, чем один жирный.


// Плохо: интерфейс заставляет имплементировать ненужное
interface Machine {
void print(); void scan(); void fax();
}

// Хорошо: разделение по возможностям
interface Printer { void print(); }
interface Scanner { void scan(); }



📌 D — Dependency Inversion Principle (DIP)

Модули верхнего уровня не должны зависеть от низкоуровневых. Зависимость — от абстракций.


// Вместо прямой зависимости от класса — интерфейс
interface NotificationSender {
void send(String message);
}
class EmailSender implements NotificationSender { /*...*/ }
class UserNotifier {
private final NotificationSender sender;
public UserNotifier(NotificationSender sender) {
this.sender = sender;
}
}


💡 Spring идеально подходит для соблюдения DIP — внедрение зависимостей через @Autowired или @Bean.


Если вы соблюдаете SOLID — ваш код легче тестировать, расширять и поддерживать. Но без фанатизма: балансируйте с принципами KISS и YAGNI.

👉@BookJava

BY Библиотека Java разработчика


Share with your friend now:
tgoop.com/BookJava/3907

View MORE
Open in Telegram


Telegram News

Date: |

Administrators Public channels are public to the internet, regardless of whether or not they are subscribed. A public channel is displayed in search results and has a short address (link). Don’t publish new content at nighttime. Since not all users disable notifications for the night, you risk inadvertently disturbing them. There have been several contributions to the group with members posting voice notes of screaming, yelling, groaning, and wailing in different rhythms and pitches. Calling out the “degenerate” community or the crypto obsessives that engage in high-risk trading, Co-founder of NFT renting protocol Rentable World emiliano.eth shared this group on his Twitter. He wrote: “hey degen, are you stressed? Just let it out all out. Voice only tg channel for screaming”. It’s yet another bloodbath on Satoshi Street. As of press time, Bitcoin (BTC) and the broader cryptocurrency market have corrected another 10 percent amid a massive sell-off. Ethereum (EHT) is down a staggering 15 percent moving close to $1,000, down more than 42 percent on the weekly chart.
from us


Telegram Библиотека Java разработчика
FROM American