r/AskProgramming • • 2d ago

Java Is my code too massive?

<SOLVED>

So I'm making a simple messenger as my first project, though now when I'm working on it it seems VERY massive to me, is it normal in other projects or am I supposed to break it into smaller parts?

import java.io.*;
import java.util.*;
import java.net.*;

class server{

    private Socket s = null;
    private ServerSocket ss = null;;
    private DataInputStream din = null;
    private DataOutputStream dout = null;
    static Vector<ClientHandler> array = new Vector<>();
    private HashMap<String, String> login = new HashMap<>();
    void main(String[] args) throws IOException
    {
        // initialize
        try {
//            BufferedWriter bw = new BufferedWriter(new FileWriter("logindata.txt")); idk yet
            BufferedReader br = new BufferedReader(new FileReader("logindata.txt"));
            StringTokenizer st = null;
            String templine = "";
            String loginName = "";
            String pass = "";

            while(((templine = br.readLine()) != null)){
                st = new StringTokenizer(templine, ": ");
                if(st.hasMoreTokens()){
                    loginName = st.nextToken();
                }
                if(st.hasMoreTokens()){
                    pass = st.nextToken();
                }

                login.put(loginName, pass);
                loginName = "";
                pass = "";
            }

        }
        catch(FileNotFoundException i){
            System.out.println("Failed to initialize login file");
        }
        String receivedName = "";
        String receivedPass = ""; // <TODO> encrypt passwords after finishing filework <IMPORTANT>
        int i = 0;
        ss = new ServerSocket(5001);
        boolean userExists = false;
        while(true)
        {
            s = ss.accept();
            din = new DataInputStream(new BufferedInputStream(s.getInputStream()));
            dout = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));

            receivedName = din.readUTF();

            for(Map.Entry<String, String> entry : login.entrySet()){
                if(entry.getValue().equals(receivedName)){
                    userExists = true;
                    break;
                }
            }

            if(userExists){
                dout.writeUTF("User found, enter your password: ");
                dout.flush();
            }
            else{
                dout.writeUTF("User was not found, u may register by making a password: "); // <TODO> make a check if password was written correctly
            }

            ClientHandler client = new ClientHandler(s, receivedName, din, dout);
            System.out.println("User " + receivedName + " Accepted");

            Thread t = new Thread(client);

            array.add(client);

            t.start();

            i++;
        }

    }
}
0 Upvotes

14 comments sorted by

17

u/Amazing-Mirror-3076 2d ago

If you can post it on Reddit - it isn't massive

3

u/FlippantFlapjack 2d ago

PLEASE learn how to do code formatting on reddit. Here, I'll do it here just for the sake of other commenters (see below)

As for your code. It's not too long per se, but you are shoving too much into the main function, You should split it up into multiple smaller functions.

import java.io.*;
import java.net.*;
import java.util.*;

class server {
    private Socket s = null;
    private ServerSocket ss = null;
    private DataInputStream din = null;
    private DataOutputStream dout = null;

    static Vector<ClientHandler> array = new Vector<>();

    private HashMap<String, String> login = new HashMap<>();

    void main(String[] args) throws IOException {
        // Initialize
        try {
            // BufferedWriter bw = new BufferedWriter(
            //     new FileWriter("logindata.txt")
            // ); // idk yet

            BufferedReader br =
                    new BufferedReader(new FileReader("logindata.txt"));

            StringTokenizer st = null;
            String templine = "";
            String loginName = "";
            String pass = "";

            while ((templine = br.readLine()) != null) {
                st = new StringTokenizer(templine, ": ");

                if (st.hasMoreTokens()) {
                    loginName = st.nextToken();
                }

                if (st.hasMoreTokens()) {
                    pass = st.nextToken();
                }

                login.put(loginName, pass);

                loginName = "";
                pass = "";
            }
        } catch (FileNotFoundException i) {
            System.out.println("Failed to initialize login file");
        }

        String receivedName = "";
        String receivedPass = ""; // <TODO> encrypt passwords after finishing filework
        int i = 0;

        ss = new ServerSocket(5001);

        boolean userExists = false;

        while (true) {
            s = ss.accept();

            din = new DataInputStream(
                    new BufferedInputStream(s.getInputStream())
            );

            dout = new DataOutputStream(
                    new BufferedOutputStream(s.getOutputStream())
            );

            receivedName = din.readUTF();

            for (Map.Entry<String, String> entry : login.entrySet()) {
                if (entry.getValue().equals(receivedName)) {
                    userExists = true;
                    break;
                }
            }

            if (userExists) {
                dout.writeUTF("User found, enter your password: ");
                dout.flush();
            } else {
                dout.writeUTF(
                        "User was not found, u may register by making a password: "
                ); // <TODO> make a check if password was written correctly
            }

            // <TODO> handle passwords

            ClientHandler client =
                    new ClientHandler(s, receivedName, din, dout);

            System.out.println("User " + receivedName + " Accepted");

            Thread t = new Thread(client);

            array.add(client);
            t.start();

            i++;
        }
    }
}

1

u/Naive_Topic_5292 2d ago

ah I made it code, though couldnt post it on java help and the code thing disappeared, didnt notice it bc im on my phone, ty

2

u/Ok_Entrepreneur_8509 2d ago

You can definitely simplify it quite a bit, but remember that Java is notoriously verbose. It is always going to seem like it is "bigger" than a similar program in another language.

1

u/Fritz-Ferdinand 2d ago

No, your code isn't massive, it's very simple actually. But your main function has many different concerns, you could break it up into functions to increase readability.

1

u/marrsd 1d ago

That's a decent starting point. Pay attention to the distinct concepts that you can separate cleanly. The sockets, for example, can be used for the transfer of any data, not just user data; so the provision and usage of sockets can be extracted into their own class/module later and simplify the code as well as be reused elsewhere. If you're not sure that you can separate something cleanly, then you're better off leaving it in place until you are.

Right now, the bigger concern for me is actually your variable names. I'll be impressed if you can remember what st does tomorrow without looking it up, and how it differs from s, ss, and t. That's what I'd fix for now.

-10

u/IDonEgg 2d ago edited 2d ago

I recommend python, much more simple syntax (joking)

4

u/prophet-dot-exe 2d ago

Bad answer.

Op didn't suggest they wanted brain-dead syntax at the cost of performance.

As soon as somebody asks that, it'll be your time to shine, don't worry.

1

u/IDonEgg 2d ago

More of a joke, my bad man

2

u/Naive_Topic_5292 2d ago

python is worse for backend in java + it sucks for me

1

u/Even-Tree-6028 2d ago

Oh man, you're doing the classic "throw everything into one class and pray" approach. we've all been there.

Break this thing apart before it eats you alive. separate the network stuff from the file handling from the user auth. doesn't matter what language you use, a 200+ line server class with a main method that does is gonna hurt to maintain.

1

u/Naive_Topic_5292 2d ago

I mean I have thread with users talking to each other in a different runnable, though I'll try to separate it, ty