r/learnjava • • Apr 23 '21

Please roast my first attempt at Java!

Coming from C and C++ and just got my first Java program to compile. Generics are actually not like templates! ;) How bad is it in the eyes of a Java programmer? What are the key mistakes I should avoid to eventually find the Java way. Generics used correctly? Anti patterns?

Program is just a graph data structure and a breadth first searcher.

import java.io.*;
import java.util.Vector;
import java.util.LinkedList;
import java.util.Queue;
import java.util.HashMap;
import java.util.Collection;

enum Color { white, grey, red, black }
enum Control { accept, discard }

interface Vertex {}
interface Edge {}

abstract class Visitor
{
    public void start(Vertex root) {}
    public void finish() {}
    
    public Control vertex(Vertex v) { return Control.accept; }
    public Control edge(Edge e, Color col) { return Control.accept; }
}

interface Graph<GraphProperty, VertexProperty, EdgeProperty>
{
    GraphProperty property();
    void property(GraphProperty x);
    VertexProperty property(Vertex v);
    void property(Vertex e, VertexProperty prop);
    EdgeProperty property(Edge e);
    void property(Edge v, EdgeProperty prop);
    Vertex addVertex(VertexProperty x);
    void removeVertex(Vertex x);
    Edge addEdge(
        Vertex from,
        Vertex to,
        EdgeProperty prop);
    void removeEdge(Edge x);
    void clear();
    boolean isEmpty();
    int vertexCount();
    int edgeCount();
    Collection<Vertex> vertices();
    Collection<Edge> edges();
    Collection<Edge> inEdges(Vertex v);
    Collection<Edge> outEdges(Vertex v);
    int index(Vertex v);
    int index(Edge e);
    int inDegree(Vertex v);
    int outDegree(Vertex v);
    int Degree(Vertex v);
    Vertex source(Edge e);
    Vertex target(Edge e);
    void bfs(Vertex root, Visitor vis);
}

abstract class AbstractGraph<GraphProperty, VertexProperty, EdgeProperty>
    implements Graph<GraphProperty, VertexProperty, EdgeProperty>
{
    public abstract class AbstractVertex implements Vertex
    {
        private VertexProperty property_;
        
        protected int index_;
        
        public AbstractVertex(VertexProperty prop, int index__)
        {
            property_ = prop;
            index_ = index__;
        }
    }
    
    public abstract class AbstractEdge implements Edge
    {
        private EdgeProperty property_;
        
        protected Vertex src_, trg_;
        protected int index_;
        
        public AbstractEdge(EdgeProperty prop, Vertex from, Vertex to, int index__)
        {
            property_ = prop;
            src_ = from;
            trg_ = to;
            index_ = index__;
        }
    }
    
    private GraphProperty property_;
    
    protected AbstractGraph(GraphProperty prop)
    {
        property_ = prop;
    }
    
    public GraphProperty property() { return property_; }
    public void property(GraphProperty x) { property_ = x; }
    public VertexProperty property(Vertex v) { return ((AbstractVertex)v).property_; }
    public void property(Vertex v, VertexProperty p) { ((AbstractVertex)v).property_ = p; }
    public EdgeProperty property(Edge e) { return ((AbstractEdge)e).property_; }
    public void property(Edge e, EdgeProperty p) { ((AbstractEdge)e).property_ = p; }
    
    public int index(Vertex v) { return ((AbstractVertex)v).index_; }
    public int index(Edge e) { return ((AbstractEdge)e).index_; }
    public int Degree(Vertex v) { return inDegree(v) + outDegree(v); }
    public Vertex source(Edge e) { return ((AbstractEdge)e).src_; }
    public Vertex target(Edge e) { return ((AbstractEdge)e).trg_; }
    
    public void bfs(Vertex root, Visitor vis)
    {
        var q = new LinkedList<Vertex>();
        var col = new HashMap<Vertex, Color>();
        
        vis.start(root);
        
        q.add(root);
        col.put(root, Color.grey);
        
        while(!q.isEmpty())
        {
            Vertex v = q.poll();
            
            switch(vis.vertex(v))
            {
            case accept:
                for(Edge e : outEdges(v))
                {
                    Color c = col.get(target(e));
                    
                    if(null == c) c = Color.white;
                    
                    Control res = vis.edge(e, c);
                    
                    if(Control.discard == res)
                    {
                        col.put(target(e), Color.black);
                        c = Color.black;
                    }
                    else if(Color.white == c)
                    {
                        col.put(target(e), Color.grey);
                        q.add(target(e));
                    }
                }
                break;
            case discard: break;
            }
            
            col.put(v, Color.black);
        }
        
        vis.finish();
    }
}

class ConcreteGraph<GraphProperty, VertexProperty, EdgeProperty>
    extends AbstractGraph<GraphProperty, VertexProperty, EdgeProperty>
{
    public class MyVertex extends AbstractVertex
    {
        private Vector<Edge> in_;
        private Vector<Edge> out_;
        
        public MyVertex(VertexProperty prop, int index__)
        {
            super(prop, index__);
            in_ = new Vector<Edge>();
            out_ = new Vector<Edge>();
        }
    }
    
    public class MyEdge extends AbstractEdge
    {
        public MyEdge(
            EdgeProperty prop,
            Vertex from,
            Vertex to,
            int index__)
        {
            super(prop, from, to, index__);
        }
    }
    
    public GraphProperty property;
    
    private Vector<Vertex> vertices_;
    private Vector<Edge> edges_;
    
    public ConcreteGraph(GraphProperty prop)
    {
        super(prop);
        vertices_ = new Vector<Vertex>();
        edges_ = new Vector<Edge>();
    }
    
    public Vertex addVertex(VertexProperty prop)
    {
        var V = new MyVertex(prop, vertices_.size());
        vertices_.add(V);
        return V;
    }
    
    public void removeVertex(Vertex v__)
    {
        var v = (MyVertex)v__;
        
        while(!v.out_.isEmpty())
        {
            var e = (MyEdge)v.out_.lastElement();
            
            edges_.remove(e.index_);
            
            for(var ee : edges_.subList(e.index_, edges_.size()))
            {
                ((MyEdge)ee).index_--;
            }
            
            ((MyVertex)e.trg_).in_.remove(e);
            
            v.out_.remove(v.out_.size()-1);
        }
        while(!v.in_.isEmpty())
        {
            var e = (MyEdge)v.in_.lastElement();
            
            edges_.remove(e.index_);
            
            for(var ee : edges_.subList(e.index_, edges_.size()))
            {
                ((MyEdge)ee).index_--;
            }
            
            ((MyVertex)e.src_).out_.remove(e);
            
            v.in_.remove(v.out_.size()-1);
        }
        
        vertices_.remove(v.index_);
        
        for(var vv : vertices_.subList(v.index_, vertices_.size()))
        {
            ((MyVertex)vv).index_--;
        }
    }
    
    public Edge addEdge(
        Vertex from__,
        Vertex to__,
        EdgeProperty prop)
    {
        var from = (MyVertex)from__;
        var to = (MyVertex)to__;
        
        var E = new MyEdge(prop, from__, to__, edges_.size());
        from.out_.add(E);
        
        try
        {
            to.in_.add(E);
        }
        catch(Throwable x)
        {
            from.out_.remove(from.out_.size()-1);
            throw x;
        }
        
        try
        {
            edges_.add(E);
        }
        catch(Throwable x)
        {
            from.out_.remove(from.out_.size()-1);
            to.in_.remove(from.in_.size()-1);
            throw x;
        }
        
        return E;
    }
    
    public void removeEdge(Edge e__)
    {
        MyEdge e = (MyEdge)e__;
        
        edges_.remove(index(e));
        
        for(var ee : edges_.subList(e.index_, edges_.size()))
        {
            ((MyEdge)ee).index_--;
        }
        
        ((MyVertex)e.src_).out_.remove(e);
        ((MyVertex)e.trg_).in_.remove(e);
    }
    
    public void clear()
    {
        vertices_.clear();
        edges_.clear();
    }
    public boolean isEmpty() { return vertices_.isEmpty(); }
    
    public int vertexCount() { return vertices_.size(); }
    public int edgeCount() { return edges_.size(); }
    
    public Collection<Vertex> vertices()
    {
        return java.util.Collections.unmodifiableCollection(vertices_);
    }
    public Collection<Edge> edges()
    {
        return java.util.Collections.unmodifiableCollection(edges_);
    }
    public Collection<Edge> inEdges(Vertex v)
    {
        return java.util.Collections.unmodifiableCollection(((MyVertex)v).in_);
    }
    public Collection<Edge> outEdges(Vertex v)
    {
        return java.util.Collections.unmodifiableCollection(((MyVertex)v).out_);
    }
    
    public int inDegree(Vertex v) { return ((MyVertex)v).in_.size(); }
    public int outDegree(Vertex v) { return ((MyVertex)v).out_.size(); }
}

class myvis extends Visitor
{
    Graph g;
    myvis(Graph gg) { g=gg; }
    
    public void start(Vertex root)
    {
        System.out.println("start");
    }
    public void finish()
    {
        System.out.println("finish");
    }
    
    public Control vertex(Vertex v)
    {
        System.out.println(g.index(v));
        return Control.accept;
    }
    public Control edge(Edge e, Color col)
    {
        System.out.println("" + g.index(e) + ": " + g.index(g.source(e)) + " -> " + g.index(g.target(e)) + " " + col);
        return Control.accept;
    }
}

class Test
{
    public static void main(String args[])
    {
        class foo {};
        Graph<foo, foo, foo> g = new ConcreteGraph<foo, foo, foo>(null);
        
        var a = g.addVertex(null);
        var b = g.addVertex(null);
        var c = g.addVertex(null);
        var d = g.addVertex(null);
        g.addEdge(a, b, null);
        g.addEdge(a, c, null);
        g.addEdge(c, d, null);
        g.addEdge(a, c, null);
        g.addEdge(a, c, null);
        g.addEdge(d, a, null);
        g.addEdge(d, d, null);
        
        g.bfs(a, new myvis(g));
    }
}
42 Upvotes

39 comments sorted by

View all comments

Show parent comments

7

u/Ghordrin Apr 24 '21

Isn't the general thought that wellwritten code shouldn't really need comments?

1

u/MatthewTheMagician Apr 24 '21

Some people think that but it's just an encouragement to write cleanly. Still use comments in all code

1

u/Ghordrin Apr 24 '21

Why would you need to explain what a method does? Shouldn't you be able to figure it out by reading what happens in the method? If you have to explain in detail what a method does, then that is something a comment shouldn't fix. It should be refactored so it makes sense.

Perhaps I just haven't seen proper use of commenting yet, I don't know. But it feels weird to comment code to explain stuff.

1

u/MatthewTheMagician Apr 24 '21

You don't need to comment on things that should be obvious but it really helps for highly complex stuff where you're not quite sure how everything fits together and it's just a good practice overall. A simple //Main method or //Checks for duplicates or whatever it is allows the reader to quickly know what it's for instead of interpreting from the name.

1

u/Ghordrin Apr 24 '21

Everything you described feels like it should be documented in a java doc or something. The general flow of the program. But, I'm not claiming I'm right or anything. Just feels weird