Testing Open-Close principle in Java - java

To demonstrate Open/Closed principle of SOLID principle, I implemented the following code.
Code:
interface IFaculty{
void admin();
}
class ITFac implements IFaculty{
#Override
public void admin() {
System.out.println("IT Fac Admin");
}
}
class MedFac implements IFaculty{
#Override
public void admin(){
System.out.println("Med Fac Admin");
}
}
class University{
public void adminFaculty(IFaculty iFaculty){
iFaculty.admin();
}
}
To test the above code, I tried to call the adminFaculty() method in the main method of main class as follows.
Code:
public class Main {
public static void main(String[] args) {
University u1 = new University();
u1.adminFaculty(); // cannot call this method without passing parameters
}
}
But I cannot call the method without passing the relevant parameter: an object of IFaculty. But I cannot do so. Does anybody knows how to call the adminFaculty(), from the main method? or any way to call the adminFaculty() and run the code to give relavent output.?
Thank you.

From your question I assume you want to be able to call adminFaculty() and always use the same faculty. For that, don't pass the faculty to the method but keep a reference in University. You can also add a default faculty.
class University {
private IFaculty faculty;
//default configuration of the university: it has a medical faculty
public University() {
this(new MedFac());
}
//allows to create a university with another faculty type
public University( IFaculty faculty) {
this.faculty = faculty;
}
public void adminFaculty(){
faculty.admin();
}
}
Now you can use it like this:
University medicalUni = new University();
medicalUni.adminFaculty();
University anotherMedicalUni = new University(new MedFac());
anotherMedicalUni.adminFaculty();
University itUni = new University(new ITFac());
itUni.adminFaculty();
Note that you always need an implementation of IFaculty like MedFac or ITFac. Of course I now could add a new faculty without having to change University:
class TechFac implements IFaculty{
#Override
public void admin() {
System.out.println("Tech Fac Admin");
}
}
University techUni = new University(new TechFac());

Related

When/Where to create a new object of my class that communicates with the Database

So I think I pretty much covered it in the Subject. But say I have a Class that communicates with the SQLite database. Methods like addInfo, fetchInfo and what have you, I am calling this class App.java (is this the right name for the Class that communicates with the DB?).
Pseudo-code for App.java:
public class App{
public void addInfo(String info){
INSERT INTO table VALUES(info)
}
public String fetchInfo(){
SELECT info FROM table
return stringWithInfo;
}
}
now, When I want to use the App.java in another class, should I create a new App object for each method that uses it?
public class AnotherClass{
public void methodOne(){
App a = new App();
String containingInfo = "Frogs quack";
a.addInfo(containingInfo);
}
public void methodTwo(){
App a = new App();
System.out.println(a.fetchInfo());
}
}
Or should I create a new class-wide object?
public class AnotherClass{
App a = new App();
public void methodOne(){
String containingInfo = "Frogs quack";
a.addInfo(containingInfo);
}
public void methodTwo(){
System.out.println(a.fetchInfo());
}
}
What is best practice? And why?

How to notify the obsever when list changes in Rxjava

I have class three classes. Pref, ClassA, and ClassB.
public class Pref{
public static ArrayList<Pref> prefList;
public static Observable<ArrayList<Pref>> observable;
public static void loadData(){
prefList = getFromDb();
observable = Observable.just(prefList);
}
}
Application runs the ClassA First.
public ClassA{
public ClassA(){
initObserver();
setObserver();
}
public void initObserver(){
Pref.loadData();
}
public void setObserver(){
Observer<ArrayList<Pref>> obs = new Observer() {
#Override
public void onSubscribe(Disposable dspsbl) {
System.out.println("Subscribed");
}
#Override
public void onNext(ArrayList<Pref>> t) {
System.out.println("Loading Preference.");
//Need to do some other works here.
}
#Override
public void onError(Throwable thrwbl) {
}
#Override
public void onComplete() {
}
};
Pref.observable.subscribe(obs);
}
}
Now I want to change the list from ClassB.
public class ClassB{
private void changeList(){
Pref.prefList = loadDataFromSomeSource();
}
}
When I run ClassA, the System.out works fine. But when I change the list from ClassB nothing happens. My question is, is the right way to work with Rxjava. Is it for Rxjava built? If I am wrong how can I achieve this functionality? How can I write several ClassA like classes so that When the ClassB::changeList() runs, I can listen it in ClassA?
By setting Pref.prefList = loadDataFromSomeSource();, you assign a new list instance to Pref.prefList. This will not update Pref.observable in any way, because this still refers to the old Pref.prefList instance.
I also think that you can not use an Observable to publish events through it. As far as I understand your situation, you need an ObservableSource (see http://reactivex.io/RxJava/javadoc/io/reactivex/ObservableSource.html). For example, it is implemented by PublishSubject. You could use it like this:
PublishSubject<String> source = PublishSubject.create();
source.subscribe(System.out::println);
source.onNext("test 1");
source.onNext("test 2");
source.onNext("test 3");
Or, in your case: in class Pref, you can use public static PublishSubject<ArrayList<Pref>> source = PublishSubject.create();. When loading the data, you can publish the new data using onNext, like this in ClassB: Pref.source.onNext(loadDataFromSomeSource())

Code implemented according statemachine pattern does not work

I am trying to solve statediagram exercise, but still have not understood why my code does not work.
I chave already cheked all possible code examles of code, but have not understood why mine version does not pass any tests.May be I chve some sort of small mistake which not easy to see. Below I provide my code, test semples and digramms I have.
https://drive.google.com/open?id=1SQAiwUBo1OwI-QKksxciDS7dEdKGS6dn [1]
https://drive.google.com/open?id=1JhdScK7t1XmNc3eLT7hSGpwyYDLWl46T [2]
public class GarageDoor {
private Motor motor;
private DoorState currentState;
public GarageDoor() {
this.setState(new Closed(this));
//currentState=new Closed(this);
}
public void openDoor(){
currentState.openDoor();
}
public void stopper(){
currentState.stopper();
}
public void closeDoor(){
currentState.closeDoor();
}
public Motor getMotor(){
return this.motor;
}
private void setState(DoorState ds){
this.currentState=ds;
}
public abstract class DoorState{
public abstract void openDoor();
public abstract void closeDoor();
public abstract void stopper();
}
public class Closed extends DoorState{
private GarageDoor garageDoor;
public Closed(GarageDoor garageDoor){
this.garageDoor=garageDoor;
}
#Override
public void openDoor() {
garageDoor.setState(new Opening(garageDoor));
garageDoor.getMotor().upwards();
}
#Override
public void closeDoor() {
throw new IllegalStateException();
}
#Override
public void stopper() {
throw new IllegalStateException();
}
}
}
Actually I cann not execute main()
public static void main(String[] args){
//Motor motor=new Motor();
GarageDoor gd=new GarageDoor();
gd.openDoor();
}
I don't see that you're setting motor anywhere, so in Closed.openDoor, when you call garageDoor.getMotor().upwards() you'll get a NullPointerException.
Also, I see that you're passing GarageDoor in to the Closed state and then calling garageDoor.setState. Consider just returning the next state from each DoorState method.
1) Try having GarageDoor extend DoorState, seems to override the same methods.
2) Nowhere in your code do you actually create the Motor in the GarageDoor class.
You need to initiate the Motor, e.g:
public GarageDoor() {
this.motor = new Motor();
}

Java - Method implementation dependent from parameter value

Consider a method
public void doSomething(String actionID){
switch (actionID){
case "dance":
System.out.print("I'm dancing");
break;
case "sleep":
System.out.print("I'm sleeping");
break;
default:
System.out.print("I've no idea what I'm doing");
}
The implementation of the method depends on the value of the parameter. Is there a more elegant way to do this, or a different design pattern to replicate the behaviour?
If the caller decides what logic is executed by passing different strings, then why not just have them call different methods:
public void doSomething(String actionID) {...}
...
doSomething("dance");
doSomething("sleep");
VS.:
public void dance() {...}
public void sleep() {...}
...
dance();
sleep();
It seems like you're unnecessarily funnelling all the calls into doSomething
But the strings might not always be literals. What if you're taking them from the console?
You could provide static mappings from the strings to the corresponding functions:
class MyClass {
private static final Map<String, Consumer<MyClass>> map = new HashMap<>();
static {
map.put("sleep", MyClass::sleep);
map.put("dance", MyClass::dance);
}
public void doSomething(String actionID) {
map.getOrDefault(actionID, MyClass::doNothing).accept(this);
}
public void dance() {
System.out.print("I'm dancing");
}
public void sleep() {
System.out.print("I'm sleeping");
}
private void doNothing() {
System.out.println("I've no idea what I'm doing");
}
}
This makes scenarios where you have a lot of switch cases a lot cleaner.
Introduce an interface, e.g.
public interface HumanState {
public void tellMeWhatYouAreDoing();
}
encapsulate the logic in different implementations
public class DancingState implements HumanState {
#Override
public void tellMeWhatYouAreDoing() {
System.out.println("I'm dancing");
}
}
public class SleepingState implements HumanState {
#Override
public void tellMeWhatYouAreDoing() {
System.out.println("I'm sleeping");
}
}
public class UnknownState implements HumanState {
#Override
public void tellMeWhatYouAreDoing() {
System.out.println("I've no idea what I'm doing");
}
}
and use a map. E.g.
public class HumanStateExample {
public static void main(String[] args) {
HumanStateExample humanStateExample = new HumanStateExample();
humanStateExample.doSomething("dance");
humanStateExample.doSomething("sleep");
humanStateExample.doSomething("unknown");
}
private final HashMap<String, HumanState> humanStateMap;
public HumanStateExample(){
humanStateMap = new HashMap<String, HumanState>();
humanStateMap.put("dance", new DancingState());
humanStateMap.put("sleep", new SleepingState());
}
public void doSomething(String action) {
HumanState humanState = humanStateMap.get(action);
if(humanState == null){
humanState = new UnknownState();
}
humanState.tellMeWhatYouAreDoing();
}
}
I'm not sure how the pattern is called, but it is very useful if you need to delegate the method call based on more than one parameter:
Create a lot of handlers where each one knows when it is responsible for handling a call. Then just loop through them and invoke the first one matching the parameter.
edit: I renamed the class from FancyParameterActionFactory to FancyParameterActionUtility: it is not a factory, the name was misleading
//Your method, but this time with a complex object, not with a simple string.
public void doSomething(FancyParameterObject fpo){
FancyParameterActionUtility.invokeOn(fpo);
}
//The utility which can handle the complex object and decides what to do.
public class FancyParameterActionUtility{
public Interface FPAHandler{
void invoke(FancyParameterObject fpo);
boolean handles(FancyParameterObject fpo);
}
//Omitted: Different implementations of FPAHandler
public static List<FPAHandler> handlers = new LinkedList<>();
static{
handlers.add(new DanceHandler());
handlers.add(new SleepHandler());
//Omitted: Different implementations of FPAHandler
}
public static void invokeOn(FancyParameterObject fpo){
for(FPAHandler handler:handlers){
if (handler.handles(fpo)){
handler.invoke(fpo);
return;
}
}
//Default-Behavior
}
}
Here is a simple implementation of the command pattern based your sample problem. I define a general AbstractCommand abstract class which contains two methods. The first method, createCommand(), instantiates a command class based on an input string name. This is how you can delegate your string input to create the right type of command. The second method is doAction(), and this is left undefined, to be implemented later on by specific concrete command classes.
public abstract class AbstractCommand {
public static AbstractCommand createCommand(String name) {
try {
String clsName = name + "Command";
Class<?> cls = Class.forName(clsName);
AbstractCommand command = (AbstractCommand) cls.newInstance();
return command;
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
}
public abstract void doAction();
}
public class DanceCommand extends AbstractCommand {
public void doAction() {
System.out.println("I'm dancing");
}
}
public class TestCommandPattern {
public void doSomething(String actionID) {
AbstractCommand cmd = AbstractCommand.createCommand(actionID);
cmd.doAction();
}
public static void main(String[] args) {
TestCommandPattern test = new TestCommandPattern();
test.doSomething("Dance"); // should print "I'm dancing"
}
}
Now that this framework has been setup, you could easily add other commands for the various types of actions in your original problem. For example, you could create a SleepCommand class which would output I'm sleeping, or do whatever action you wish.

Name for pattern that allows only certain classes to construct another class

I have to write a test for the login dialog that shows up on my website, but there are two, and only two access points for this login dialog. Ideally, my page objects should reflect the restricted access to this login dialog.
When you clickLogin on the Header, a LoginDialog pops up
When you postComment on an Article, and you aren't logged in (and we'll assume you aren't for simplicity), a LoginDialog pops up.
Here's what it looks like in code:
new LoginDialog().login(); // shouldn't be allowed
new Header().clickLogin().login(); // should be allowed
new Article().postComment().login() // should be allowed
I came up with a method for getting around this. LoginDialog only has two constructors, which both take in an object that can only be constructed in either Header or Article.
public class LoginDialogTest extends WebTest {
#Test
public void testLoginDialogFromHeader {
new HomePage().loadPage();
new Header().clickLogin().login();
verifyLoggedIn();
}
#Test
public void testLoginDialogFromArticleComment {
new ArticlePage(42).loadPage(); // Load an article with id=42
new Article().postComment().login();
verifyLoggedIn();
}
}
public class LoginDialog {
public LoginDialog(Article.CommentButton commentButton) {
}
public LoginDialog(Header.LoginButton loginButton) {
}
public void login() {
}
}
public class Article {
public class CommentButton {
private CommentButton() {
}
public LoginDialog click() {
return new LoginDialog(this);
}
}
public LoginDialog postComment() {
return new CommentButton().click();
}
}
public class Header {
public class LoginButton {
public LoginDialog click() {
return new LoginDialog(this);
}
}
public LoginDialog clickLogin() {
return new LoginButton().click();
}
}
My question is whether or not this is an existing pattern, and if it is, what is its name? If it isn't, what would be a good name for it?
I think this would be a foolproof way of making sure only Header or Article could create a LoginDialog:
public class LoginDialog {
private LoginDialog() {
... code to construct
}
public interface Constructor {
LoginDialog newLoginDialog();
}
private static class ConstructorImpl implements Constructor {
public LoginDialog newLoginDialog() {
return new LoginDialog();
}
}
private static ConstructorImpl constructor;
static {
constructor = new ConstructorImpl();
Header.provideLoginDialogConstructor(constructor);
Article.provideLoginDialogConstructor(constructor);
}
}
and in Header and Article, provide a public provideLoginDialogConstructor method:
private static LoginDialog.Constructor constructor;
public static void provideLoginDialogConstructor(LoginDialog.Constructor constructor) {
Header.constructor = constructor; // or Article.constructor
}
and when those classes need to construct a LoginDialog:
if (!loggedIn()) {
return constructor.newLoginDialog();
} else {
return null;
}
Since the LoginDialog class decides what classes get to have its private object to construct a LoginDialog, there should be no way for another class to obtain the ability to construct one using normal means [there might be tricky ways using reflection].
Note: I haven't tested this.

Categories