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

27

u/anthropaedic Apr 23 '21

Definitely a c coder’s Java. For variable names, try to be descriptive. See here for some basics.

I am a bit confused why you are implementing interfaces without anything defined in them.

5

u/mikaijin Apr 23 '21

I wanted to get stable refs of vertices and edges and thought it would be a nice idea to give them their own type instead of using a generic Object, if only to aid overloading. There is no interface because they are just handles.

8

u/hugthemachines Apr 23 '21

The comment still stands.

It might be a good idea for you to read the book "clean code" by robert c martin to learn a bit about these things.

17

u/[deleted] Apr 23 '21

The way you've placed brackets is heresy in Java.

The most popular style guides for Java, the Sun style guide and Google style guide, put the opening bracket on the same line as the statement. Seriously though, at least read the Google Java style guide.

I associate your bracket placement with C#.

We don't put underscores in our member variables around here.

Vector is long deprecated. Use List. When the Java language designers came up with Vector, they added a ton of synchronization to it to make it "thread safe", but ended up just making it slow. List isn't synchronized and depends on you for external synchronization, which isn't necessary in single threaded code.

Some other observations;

  • null is just bad. Avoid it if you can, opting for empty containers enstated.

  • Why are you catching on add? That smells suspiciously like "using exceptions for flow control', which is a no-no.

6

u/mikaijin Apr 23 '21

> Vector is long deprecated. Use List.

Wow. I was like 100% certain to have picked the right container. Investigating ArrayList now.

> Why are you catching on add? That smells suspiciously like "using exceptions for flow control', which is a no-no.

To enforce strong exception guarantee. Removing previously added entries before rethrowing. Is this not a thing in Java?

Bookmarked the guide. Thanks!

5

u/Tomato_Sky Apr 24 '21

This was mostly my critique from it. I am Java trained, but C educated. And in my free time, I stay away from C and C++. ArrayList is much more productive than vectors. I see why you’re doing some of the things you’re doing which is unique in java. I’ve never really seen someone switch over and see the old stuff like this. It’s like the redneck speaking spanish videos on YouTube. Great post!

4

u/darksounds Apr 24 '21

To enforce strong exception guarantee. Removing previously added entries before rethrowing. Is this not a thing in Java?

It's not useful in this context. Everything is in memory, and you never catch the exceptions again, so they'll kill your program every time anyway. If your program dies, you don't really need any guarantees.

1

u/[deleted] Apr 24 '21

To enforce strong exception guarantee. Removing previously added entries before rethrowing. Is this not a thing in Java?

It is a thing in Java. It's called failure atomicity.

Which leads to another suggestion. Write some friggin' comments!

7

u/IAmNotMyName Apr 24 '21

Your code style is not consistent with Java conventions.

  • brackets should open on the same line as the class, constructor, method etc

  • else, else if, catch, finally etc should be placed on the same line as the closing bracket of the previous block

  • Rarely will underscore be used in field names in Java.

  • Classes are always Capital Letter first, myvis is a no- no. It should also be camel case MyVis.

  • Single line functions are generally frowned upon

  • Use of whitespace between methods is preferred.

  • You don't need the Type arguments on the instantiation of a class.

    • List<Int> intList = new ArrayList<>();

      • works and is preferred

  • As someone else mentioned use

    • this.blank = blank;

      • when setting a field from an argument.

Beyond your code style you are typecasting all of your input. This is reeks of code smell as they say. This can lead to runtime exceptions if the input type does not match the typecast. You can fix the need for this by removing the interfaces that don't define any behavior (Edge, Vertex)

1

u/mikaijin Apr 24 '21

Thank you, that's great advice!

1

u/[deleted] Apr 24 '21

Technically that’s not camelCase, that’s PascalCase

0

u/darksounds Apr 25 '21

Technically it's not NOT camel case, as Pascal case is a special case of camel case.

1

u/[deleted] Apr 25 '21

Huh, TiL: some people call PascalCase “upper camelCase”

1

u/darksounds Apr 25 '21

Well, I'd say they call it UpperCamelCase, but that's just being pedantic at this point.

https://en.wikipedia.org/wiki/Pascal_case

10

u/darksounds Apr 24 '21

Just did a quick code review, in the form of comments.

Enjoy.

https://pastebin.com/m6uTeGYp

9

u/darksounds Apr 24 '21

For anyone who doesn't want to read it, the biggest flaws are the use of XProperty generic types that are then ignored completely, the overuse of abstract classes when they're not necessary or useful, the poor use of interfaces, and the poor selection of data structures.

Obviously the names of almost everything are awful, the formatting is not good Java, nothing is documented with Javadoc comments, and the access modifiers are all over the place, too, but those can be cleaned up after the worst things are dealt with!

0

u/[deleted] Apr 24 '21

[deleted]

2

u/darksounds Apr 24 '21

They said to roast it.

Shrug.

1

u/redderper Apr 24 '21

Wait, you're right. Totally missed that part

2

u/darksounds Apr 24 '21

Yeah, I wasn't trying to be a total asshole, but I let loose a little more than I do at work.

Tbf, at work, this would be an immediate block, followed by a chat to get on the same page. Too much reworking needed to just make comments and send it back.

6

u/mladensavic94 Apr 23 '21 edited Apr 23 '21

You don't need to add an underscore to a variable name; public variables in Java are only static constants, and they have a special naming structure. Take a look at Java bean specification.

Also, I noticed you are using something like:

index_ = index__;

there is no need for that; if your constructor argument is the same name as your class field, use this keyword, ie.

this.index = index;

edit: I am not sure if you planned to implement these methods in your Visitor class but you did:

   public void start(Vertex root) {}     
   public void finish() {}

If you don't want to implement them right there you need to mark them as abstract like this:

   public abstract void start(Vertex root);
   public abstract void finish();

5

u/darksounds Apr 24 '21

Technically those are implementations of those methods!

5

u/qelery Apr 23 '21

I’d definitely read a book on Java. If you told me this was another programming language other than Java I’d probably believe it.

1

u/guitarhippo Apr 25 '21

Hahaha me too. How long have you being programming in Java?

4

u/asterik-x Apr 24 '21

I would suggest dont underestimate urself. Its good start.

2

u/loomynartylenny Apr 24 '21

1: I'd definitely suggest using JavaDocs. It'll save you a lot of pain later on when trying to work out what the hell everything's supposed to be doing.

2: What's the point of the Vertex and Edge interfaces? They don't have any methods (meaning you can't use them for any practical purpose), they don't extend another interface, so what's the point of them being there?

3: Give your getters and setters actual names. For example, with your GraphProperty property() and void property(GraphProperty x) methods, rename them to GraphProperty getGraphProperty()and void setGraphProperty(GraphProperty x) so it's clear what they're supposed to be doing.

4: JavaDocs. Seriously. Please use them.

3

u/MatthewTheMagician Apr 24 '21

Great start but use comments. A well commented document is huge and very important in the tech world. Helps both you and others to code more efficiently and work better and understand the code easier.

7

u/Ghordrin Apr 24 '21

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

3

u/darksounds Apr 24 '21

It shouldn't need many internal comments. There should still be full javadoc documentation on all public methods. Someone who wants to use your code shouldn't have to read the implementation to figure out what it does!

1

u/loomynartylenny Apr 24 '21

I'd argue that it's worth putting javadocs on non-public methods and attributes as well, mostly so you don't end up writing something, working on something else for a few days, and then returning to the method and asking yourself 'what is this supposed to be'

2

u/darksounds Apr 24 '21

I mean, yes. Please document everything! Public ones are 100% mandatory, though, while private ones are "please add documentation" not "you will never get approval on this until you add documentation" (subject to context, of course).

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.

2

u/loomynartylenny Apr 24 '21 edited 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?

Put it this way: would you rather waste time having to re-read the method to work out what it does every time you forget what the method does, or would you rather just have a tl;dr you can look at to state what the method does?

JavaDocs exist. Use them.

If you want an example of them in use, just look at the Java API documentation (and if you want a direct link to a specific example from aforementioned documentation, there's this: https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html). Yes, all of that documentation was automatically generated from JavaDoc comments.

But wait, there's more!

With a bunch of IDEs, if you hover your mouse over a method call/usage of a class attribute/etc, and the aforementioned method/attribute has been given a JavaDoc comment, it'll show you a tooltip with the contents of the JavaDoc comment on it. So, if you're trying to remember what a certain method does, assuming that you put a JavaDoc comment on it, you don't even need to bother looking at the method itself to remember what it does. (and yes, it's been a thing for years in IntelliJ and Eclipse: https://stackoverflow.com/questions/6615516/intellij-show-javadocs-tooltip-on-mouse-over)

tl;dr Use JavaDocs.

2

u/Ghordrin Apr 24 '21

I see comments as something separate of java docs, though. Everyone should use some form of documentation. Just comments that say stuff like "this is the main method", "this is a helper method", "this method does X by using Y" feels.. weird.

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

-1

u/[deleted] Apr 24 '21

No

1

u/mikezyisra Apr 24 '21

haha can definitely tell by the “__” that you come from C++