Knowing how many ports are open in Java program

2

I have a program in Java to know how many ports are open but I'm not sure where to put the method to count the ports. Can I create a count method for open ports within the Porta class?

    package programa2;
    public class Programa2 {
    public static void main(String[] args) {
    Porta minhaPorta1;
    minhaPorta1 = new Porta();
    minhaPorta1.dimensaoX = 100;
    minhaPorta1.dimensaoY = 80;
    minhaPorta1.dimensaoZ = 30;
    minhaPorta1.cor = null;
    minhaPorta1.pinta("Verde");
    System.out.println("A porta é: " + minhaPorta1.cor + " e as dimensões são " + minhaPorta1.dimensaoX + ", " + minhaPorta1.dimensaoY + ", " + minhaPorta1.dimensaoZ + ".");
    minhaPorta1.abreFecha(1);

    Porta minhaPorta2;
    minhaPorta2 = new Porta();
    minhaPorta2.dimensaoX = 120;
    minhaPorta2.dimensaoY = 90;
    minhaPorta2.dimensaoZ = 40;
    minhaPorta2.cor = null;
    minhaPorta2.pinta("Azul");
    System.out.println("A porta é: " + minhaPorta2.cor + " e as dimensões são " + minhaPorta2.dimensaoX + ", " + minhaPorta2.dimensaoY + ", " + minhaPorta2.dimensaoZ + ".");
    minhaPorta2.abreFecha(2);

    Porta minhaPorta3;
    minhaPorta3 = new Porta();
    minhaPorta3.dimensaoX = 70;
    minhaPorta3.dimensaoY = 60;
    minhaPorta3.dimensaoZ = 10;
    minhaPorta3.cor = null;
    minhaPorta3.pinta("Amarela");
    System.out.println("A porta é: " + minhaPorta3.cor + " e as dimensões são " + minhaPorta3.dimensaoX + ", " + minhaPorta3.dimensaoY + ", " + minhaPorta3.dimensaoZ + ".");
    minhaPorta3.abreFecha(2);
}   
}

Port Class:

package programa2;
public class Porta {

boolean aberta;
String cor;
int dimensaoX, dimensaoY, dimensaoZ;

void abre() {
    this.aberta = true;
}

void fecha() {
    this.aberta = false;
}

void pinta(String novaCor) {
    this.cor = novaCor;
}

void abreFecha(int respUsuario) {
    switch (respUsuario) {
        case 1:
            abre();
            System.out.println("A porta está aberta.\n");
        break;
        case 2:
            fecha();
            System.out.println("A porta está fechada.\n");
        break;
    }
} 
}

int quantasPortasEstaoAbertas(){
    int cont = 0;
    if(this.minhaPorta1.abreFecha(1)){              
        cont = cont + 1;
    }
    if(this.minhaPorta2.abreFecha(1)){
        cont = cont + 1;
    }
    if(this.minhaPorta3.abreFecha(1)){
        cont= cont + 1;
    }           
    return cont; 
}
    
asked by anonymous 17.07.2016 / 21:44

2 answers

4

Introduction

You can always do whatever you want. Ideally, you should do the best for each situation. Who is learning still does not know what is best. But it is certainly advantageous to learn in steps. Start with the simple, and solve. It is no use learning all the possible concepts and applying a valid technique without even knowing if this technique is necessary or why you are using it. Worse, you can learn what is called "good practices", that is, someone tells you that right is such a thing and you go out repeating it without knowing why. And it's a lot that in the name of doing "good practice" you often opt for a more complex design than you actually need.

This is an exercise. The ideal is to learn all concepts correctly. But you do not need to learn concepts that are not absolutely necessary for this problem. You do not need to learn concepts that are not unanimous. So come on.

Count open ports

The Porta class should only handle a port. But nothing prevents it from controlling some general aspects of all existing ports. Again, if this is the error or not for the problem still does not know, and it is difficult to know since the problem is not real, it is just to train some aspects.

The easiest way to resolve is to have a class variable (as opposed to an instance variable that belongs to each object porta ), so there is only one data for every application. In this variable you control how many are open. Obviously you should add and subtract whenever you have the door open and close.

You can create a method to access this variable, as was done in the example. But as it will access a static (class) variable the method can be static as well.

Organizing the code

Taking advantage of this we will improve some things that already fit even in simple thing learning. Get used to organizing the code well. This is above the beginner average, but some things can be improved.

It is customary to say the visibility of all members even if it is not necessary. Say what is public and what is private, that documents better. Especially make the variable aberta private. The ideal (but it should not always be followed) is that all variables are private. This in particular does not have to be public since it is not publicly accessed.

Many people will say to create public access methods get and set for all variables and make them private. It depends, this can be good or not . Know that you can do this, but first understand why to do it before you start applying.

The dimensions of the door dimensions seem to be mandatory, right? That is, if they do not exist, the door does not exist. If so, consider build a builder to send this data and only then can the port be created.

Small problems

I removed the lines that put cor as null . Class creation already guarantees this, it's redundancy.

No switch called the abre() method in both situations, I think that was a lapse. I fixed it.

I have taken this since it is redundant.

I have my doubts if sending a number to an open method and choosing what to do is a good idea. It does not seem to be the responsibility of the Porta class to take care of this, this method does not seem to be suitable there, but for an initial exercise this is fine.

The day you feel you need a more robust solution, which will use competition, if you have determined that you need to know how many ports are open, whether other general port information is needed, whether they will be associated with something property, for example), that is, when you have a better defined problem, you can make a design more complex with other classes suitable for the problem. Without the proper definition of the requirements you will create frankestein solutions, this is to create addiction.

Conclusion

Obviously other improvements can be made, but I think it helps a lot.

In a real problem you will have to think about other things. This implementation is very naive.

But I would stay away from complex designs for now. Try to make the class alone work well. When you master it well, you can think of architecture. Ideally with real issues.

class Porta {
    private static int portasAbertas = 0;
    private boolean aberta;
    public String cor;
    public int dimensaoX, dimensaoY, dimensaoZ;

    public void abre() {
        if (!aberta) {
            portasAbertas++;
            aberta = true;
        }
    }

    public void fecha() {
       if (aberta) {
            portasAbertas--;
           aberta = false;
       }
    }

    public void pinta(String novaCor) {
        cor = novaCor;
    }

    public void abreFecha(int respUsuario) {
        switch (respUsuario) {
            case 1:
                abre();
                System.out.println("A porta está aberta.\n");
            break;
            case 2:
                fecha();
                System.out.println("A porta está fechada.\n");
            break;
        }
    } 

    public static int quantasPortasEstaoAbertas() {
        return portasAbertas; 
    }
}

class Programa2 {
    public static void main(String[] args) {
        Porta minhaPorta1;
        minhaPorta1 = new Porta();
        minhaPorta1.dimensaoX = 100;
        minhaPorta1.dimensaoY = 80;
        minhaPorta1.dimensaoZ = 30;
        minhaPorta1.pinta("Verde");
        System.out.println("A porta é: " + minhaPorta1.cor + " e as dimensões são " + minhaPorta1.dimensaoX + ", " + minhaPorta1.dimensaoY + ", " + minhaPorta1.dimensaoZ + ".");
        minhaPorta1.abreFecha(1);

        Porta minhaPorta2;
        minhaPorta2 = new Porta();
        minhaPorta2.dimensaoX = 120;
        minhaPorta2.dimensaoY = 90;
        minhaPorta2.dimensaoZ = 40;
        minhaPorta2.pinta("Azul");
        System.out.println("A porta é: " + minhaPorta2.cor + " e as dimensões são " + minhaPorta2.dimensaoX + ", " + minhaPorta2.dimensaoY + ", " + minhaPorta2.dimensaoZ + ".");
        minhaPorta2.abreFecha(2);

        Porta minhaPorta3;
        minhaPorta3 = new Porta();
        minhaPorta3.dimensaoX = 70;
        minhaPorta3.dimensaoY = 60;
        minhaPorta3.dimensaoZ = 10;
        minhaPorta3.pinta("Amarela");
        System.out.println("A porta é: " + minhaPorta3.cor + " e as dimensões são " + minhaPorta3.dimensaoX + ", " + minhaPorta3.dimensaoY + ", " + minhaPorta3.dimensaoZ + ".");
        minhaPorta3.abreFecha(2);

        System.out.println(Porta.quantasPortasEstaoAbertas());
    }
}

See running on ideone .

    
17.07.2016 / 23:44
2

The best place for this method is not within the Porta class, since you would need to pass a list of the instantiated ports for the count to be made. Note that, ideally, an instance of the port class should know only about it.

In this case, an alternative is to make this count in a class that is named PortaManager . This class would have the port list instantiated in your application. A method would loop through this list to return the number of ports that are open.

See the code below. The only change in the Main class is that the ports need to be added in the PortaManager.

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        PortaManager portaManager = new PortaManager();

        Porta minhaPorta1;
        minhaPorta1 = new Porta();
        minhaPorta1.dimensaoX = 100;
        minhaPorta1.dimensaoY = 80;
        minhaPorta1.dimensaoZ = 30;
        minhaPorta1.cor = null;
        minhaPorta1.pinta("Verde");
        System.out.println("A porta é: " + minhaPorta1.cor + " e as dimensões são " + minhaPorta1.dimensaoX + ", " + minhaPorta1.dimensaoY + ", " + minhaPorta1.dimensaoZ + ".");
        minhaPorta1.abreFecha(1);
        portaManager.adicionar(minhaPorta1);


        Porta minhaPorta2;
        minhaPorta2 = new Porta();
        minhaPorta2.dimensaoX = 120;
        minhaPorta2.dimensaoY = 90;
        minhaPorta2.dimensaoZ = 40;
        minhaPorta2.cor = null;
        minhaPorta2.pinta("Azul");
        System.out.println("A porta é: " + minhaPorta2.cor + " e as dimensões são " + minhaPorta2.dimensaoX + ", " + minhaPorta2.dimensaoY + ", " + minhaPorta2.dimensaoZ + ".");
        minhaPorta2.abreFecha(2);
        portaManager.adicionar(minhaPorta2);

        Porta minhaPorta3;
        minhaPorta3 = new Porta();
        minhaPorta3.dimensaoX = 70;
        minhaPorta3.dimensaoY = 60;
        minhaPorta3.dimensaoZ = 10;
        minhaPorta3.cor = null;
        minhaPorta3.pinta("Amarela");
        System.out.println("A porta é: " + minhaPorta3.cor + " e as dimensões são " + minhaPorta3.dimensaoX + ", " + minhaPorta3.dimensaoY + ", " + minhaPorta3.dimensaoZ + ".");
        minhaPorta3.abreFecha(2);
        portaManager.adicionar(minhaPorta3);

        System.out.println("A quantidade de portas abertas é: " + portaManager.quantasPortasEstaoAbertas());
    }
}

See the PortaManager class below. It can be improved, including methods to exclude ports, etc.

class PortaManager {
    private List<Porta> portas;

    PortaManager() {
        portas = new ArrayList<Porta>();
    }

    public int quantasPortasEstaoAbertas() {
        int resultado = 0;

        for (int i = 0; i < portas.size();i++) {
            if (portas.get(i).aberta)
                resultado++;
        }

        return resultado;
    }

    public void adicionar(Porta porta) {
        portas.add(porta);
    }
}
    
17.07.2016 / 22:34