If all these 3 classes follow the SOLID concept

I want to ask you something else about this for the code below for SOLID. If all these 3 classes comply with the SOLID concept.

public interface A { public void calculate(String a); } public class B implements A { @Override public void calculate(String b) { System.out.println("value: " + b); } } public class C { private A a; public void show() { a = new B(); a.calculate("test"); } } 
+4
source share
2 answers

From the way I look at things

Class C splits

A single principle of responsibility, managing two responsibilities, namely: create instances of other objects (instance B) and show whatever it is. Creating an object must be handled by a separate class, and dependencies must be entered by users.

An open, closed principle, being closely related to B, while it could depend on the interface A, so it was open for extension using another implementation of A. See for more information. In other words, C had to use A, and the actual implementation was to be introduced in C.

Below you can write C for SOLID.

 class C { private A a; public C(A a) { super(); this.a = a; } public void show() { a.calculate("test"); } } class Creator { C createC() { A b = new B(); return new C(b); } } 

Creator can be replaced by a dependency injection framework, such as Spring.

+3
source

Hope the code snippet below is strictly SOLID compliant.

 public class Creator { public static A getA(){ A a = new B(); return a; } } public class C { private A a; public void show() { setB(); a.calculate("test"); } private void setB(){ a = Creator.getA(); } 

}

0
source

All Articles