Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface Segregation Principle and default methods in Java 8

As per the Interface Segregation Principle

clients should not be forced to implement the unwanted methods of an interface

...and so we should define interfaces to have logical separation.

But default methods introduced in Java 8 have provided the flexibility to implement methods in Java interfaces. It seems Java 8 has provided the feasibility to enhance an interface to have some methods not related to its core logic, but with some default or empty implementation.

Does it not violate the ISP?

like image 631
Harpreet Avatar asked Sep 23 '17 08:09

Harpreet


2 Answers

Good question. Definitely, it violates Interface Segregation Principle and I personally don't like the concept of default implementation because it spoils the beauty of interface design and a bit on exact polymorphism as well. If somebody is not aware of the concept of ISP then they will start design fat interfaces and will end up like everything packed in one interface. During code design, people will not think logically as well.

This will end up with code smells and I am sure those who don't know the concepts will start writing bad code. I believe default implementation is an unwanted feature as it will tend people to write smelly code.

like image 171
Vijayanath Viswanathan Avatar answered Sep 26 '22 08:09

Vijayanath Viswanathan


The ISP will be violated if you intend to do so. You can segregate the interfaces to fulfill only single responsibility. The group of methods for a particular responsibility most probably will follow 80-20 rule. You can provide the default implementations for 40-50% of the methods out of 80% part. This 40-50% part will be the one which will be rarely used and hence defaults are ok. If interface fulfills single responsibility, they will rarely be too big, and most often will be in ISP.

like image 41
Gaurav J. Avatar answered Sep 25 '22 08:09

Gaurav J.