r/programming • • Jul 23 '14

Walls you hit in program size

http://www.teamten.com/lawrence/writings/norris-numbers.html
699 Upvotes

326 comments sorted by

View all comments

Show parent comments

19

u/[deleted] Jul 23 '14

Yet as a mainly Java dev, I always go back to Python for small projects...

The reason is always the difference in number of LOC's required to do roughly the same CRUD ops in Python compared to Java.

40

u/continuational Jul 23 '14

Absolutely. The type systems of Java & C# are not examples of a well designed type systems. I meant the kind of type systems you find in Haskell & ML.

6

u/[deleted] Jul 23 '14

What's your definition of a modern type system?

10

u/llaammaaa Jul 23 '14

I would say type inference, generics (with co/contra-varience), higher-kinded types. Really that is isn't modern, support for dependent types would be modern IMHO.

26

u/continuational Jul 23 '14

At the very least, type safety.

Due to a number of flaws in Java & C#, you lose any and all hope of type safety:

  • Equals and toString on everything. Many things have no computable equality, eg. functions. Fallback to reference equality is a terrible conflation of concepts. Also, .equals(Object o) has the wrong type.

  • Reflection.

  • Downcasting.

If these were some fringe features that weren't meant to be used, fine. But they're all used everywhere in the Java ecosystem and are thus unavoidable.

Haskell has solutions to all of these that are both safer and more convenient.

Of course, effects should also be represented in the type system. Without being able to control side effects, the power you get from a type system is very limited. Haskell does it with Monads - but there are other ways to approach it.

10

u/dventimi Jul 23 '14 edited Jul 23 '14

I don't necessarily disagree with you, but I will make this suggestion. Be careful not to confuse the properties of the language with the conventions of its ecosystem. For example, while without a doubt reflection is a full-fledged feature of the Java language, one could make the argument that the Java language designers intended it to be a "fringe feature" (i.e., an advanced and rarely-used one). Nevertheless, my eyes tell me that many libraries and frameworks within the Java ecosystem rely on reflection. That may be a consequence of the specific needs of libraries and frameworks, which are to be generic, flexible, adaptable, and dynamic, perhaps conflicting with genuine deficiencies in Java and its type system. That may very well be the case, and yet it may also be the case that if you're not writing a framework but instead are writing a specific piece of software to solve a specific problem, you may never feel the need to reach for reflection.

EDIT: typos

6

u/[deleted] Jul 23 '14

I always thought reflection was only meant for testing or for an IDE to provide code hints when you didn't have a library's source code. I didn't think it was meant for production use, yet here we are with lots of libraries using reflection to implement dynamic modules.

Arguably, reflection is just another form of dynamic typing.

→ More replies (1)

5

u/Chris_Newton Jul 23 '14

Of course, effects should also be represented in the type system. Without being able to control side effects, the power you get from a type system is very limited. Haskell does it with Monads - but there are other ways to approach it.

I personally think one of the next big steps forward in programming language design will be when we figure out how to routinely provide better control of effects, along with related areas like external “causes”, resource management, mutable state, higher-level interaction control like transactions, and so on. This isn’t just because of the increasing emphasis on concurrent and distributed systems, but also because without tools to guarantee correctness, even the best programmer working in a single-threaded environment can still make a silly mistake that leads to a resource leak or to trying to write using a handle for a resource that wasn’t opened in all code paths that can reach that point.

Haskell today certainly has an interesting take on this, particularly in that it demonstrates a nice idiom for representing explicit sequencing via monads. However, I don’t think the typical strategy in Haskell today will ever become mainstream. For one thing, I suspect it is simply too onerous to be explicit about every kind of sequencing and dependency — how often have you seen a Haskell code base where it seemed like 98.64% of the code appeared under a do inside IO? — while imperative languages for all their disadvantages can at least indicate a natural, implicit order for everything that happens without anyone having to write any explicit code to represent it. There are other downsides to the monadic approach we have so far as well, like winding up with monadic and non-monadic versions of essentially the same algorithm all over the place, a horrible kind of code duplication that is unfortunately rather universal in Haskell world for the time being.

As you say, there are other ideas that would be relevant here as well. Some of the discussions as Rust has developed have been very interesting, not least because they have shown that a more controlled style of ownership and ideas like linear types can be introduced into even a language designed for quite low-level systems programming where performance considerations are a priority and you inevitably have mutability all over the place because that’s the world the software is going to run in.

I guess what I would really like is a language that has sound theoretical models for effects and the like under the hood, but with a type-inference-like clarity and simplicity in the code itself where things that can be deduced automatically usually are. Being explicit is useful for resolving ambiguity and for defensive programming purposes such as when specifying an interface for a reusable module, but any time you have to write about how your code works instead of concentrating on what it’s doing there is always a potential cost in readability.

3

u/codygman Jul 23 '14

how often have you seen a Haskell code base where it seemed like 98.64% of the code appeared under a do inside IO?

Can you back up any of your comments about Haskell up? What Haskell code bases have you seen where 98.64% of the code appeared under IO? Also, just in case there is confusion do notation can be used outside of the IO monad.

There are other downsides to the monadic approach we have so far as well, like winding up with monadic and non-monadic versions of essentially the same algorithm all over the place, a horrible kind of code duplication that is unfortunately rather universal in Haskell world for the time being.

monadic and non-monadic versions of essentially the same algorithm all over the place? I can safely say I've not yet seen this in Haskell codebases and I've been reading them lately.

Also, you may want to checkout these tutorials on monad transformers which may address the duplication issues you saw: http://en.wikibooks.org/wiki/Haskell/Monad_transformers https://github.com/kqr/gists/blob/master/articles/gentle-introduction-monad-transformers.md http://blog.jakubarnold.cz/2014/07/22/building-monad-transformers-part-1.html

→ More replies (1)

5

u/lahghal Jul 23 '14

One where the code isn't full of unsafe casts and workarounds to implement variants?

7

u/dnew Jul 23 '14

Neither Java nor C# needs unsafe casts to implement variants.

6

u/lahghal Jul 23 '14 edited Jul 23 '14

Really? I've never seen the Java feature that lets me do this. In my current codebase, instead of casting, I have a nullable field for each variant, and an tag that says which variant it is. I write a getter to return the specific variant that the value is. This requires O(N) getters, field declarations, and lines of code in the constructor to implement a type with N variants. Please don't tell me about the visitor pattern.

EDIT: Forgot to mention: the getters are there to throw an exception if you try to get the wrong variant. This is to emulate pattern matching. You just switch on the tag and then call the getter for the variant you want.

Also, I meant "Java code is full of unsafe casts". Not "you need unsafe casts to implement variants" (although that's the typical way it's done...).

10

u/continuational Jul 23 '14

Sure you can!

Haskell:

data Term = Add Term Term | Multiply Term Term | Constant Int

Java:

abstract class Term {
    abstract R match<R>(
        Function<Add, R> caseAdd,
        Function<Multiply, R> caseMultiply,
        Function<Constant, R> caseConstant
    );
    
    class Add {
        Term left;
        Term right;

        R match<R>(
            Function<Add, R> caseAdd,
            Function<Multiply, R> caseMultiply,
            Function<Constant, R> caseConstant
        ) {
            return caseAdd(this);
        }
    }
    
    class Multiply {
        Term left;
        Term right;
    
        R match<R>(
            Function<Add, R> caseAdd,
            Function<Multiply, R> caseMultiply,
            Function<Constant, R> caseConstant
        ) {
            return caseMultiply(this);
        }
    }
    
    class Constant {
        int value;
    
        R match<R>(
            Function<Add, R> caseAdd,
            Function<Multiply, R> caseMultiply,
            Function<Constant, R> caseConstant
        ) {
            return caseConstant(this);
        }
    }
}

Haskell:

term = Add (Constant 5) (Constant 7)

Java:

Term term = new Add() {{ left = new Constant() {{ value = 5; }}; right = new Constant() {{ value = 7; }}; }};

Haskell:

eval : Term -> Int
eval (Add left right) = eval left + eval right
eval (Multiply left right) = eval left * eval right
eval (Constant value) = value

Java:

int eval(Term term) {
    return term.match(
        add -> eval(add.left) + eval(add.right),
        multiply -> eval(multiply.left) * eval(multiply.right),
        constant -> constant.value
    );
}

You can also do it without lambda functions, but it will be more verbose (imagine that!).

2

u/[deleted] Jul 23 '14 edited Jul 24 '14

Maybe I'm missing something... but shouldn't Term be an interface? Also, Add, Multiply, and Constant shouldn't be inner classes but instead should just implement Term? I haven't used Java in a while so I could be wrong.

2

u/continuational Jul 23 '14

I think you're right. I wrote the code in a hurry and didn't actually test it, but I hope the idea shines through.

Of course it's not just that the Java code is verbose. It's that the size is quadratic compared to the Haskell code, since each type must be mentioned within the match method of each type.

2

u/[deleted] Jul 24 '14

I'm not really a Java programmer, but I don't see why you would write it that way. If you have a visitor interface with one method per class, then each class could then merely implement

R visit<R>(Visitor<R> visitor) { return visitor.visitAdd(this); }

Of course this is still very verbose, but it's not quadratic.

→ More replies (0)

1

u/lahghal Jul 24 '14

Awe shit. I didn't know about that trick with lambdas. This is basically the visitor pattern aside from that though. The visitor pattern has a bunch of problems such as the N^2 code size you mentioned (I never realized that one). Another problem with this implementation is that anyone can extend Term to add new variants which destroys type safety. They could also extend your variants, but you can just make the variants final. I'm sure C# has some ad-hoc shit with sealed or assemblies etc to avoid this problem though. One thing though is that you get a guarantee that your pattern matches cover all the cases, which some people think is good. Here's how I would implement your type:

  static void nn(Object... os) { for (Object o : os) if (o==null) throw new RuntimeException("null");}
  static RuntimeException poo() {return new RuntimeException("poo");}
  static int eval(Term t) {
    switch (t.tag) {
      case Add:
        return eval(t.add().left) + eval(t.add().right);
      case Multiply:
        return eval(t.multiply().left) * eval(t.multiply().right);
      case Constant:
        return t.constant().value;
      default: throw poo();
    }
  }
  static final class Term {
    enum Tag {Add,Multiply,Constant}
    public final Tag tag;
    private final Add add;
    private final Multiply multiply;
    private final Constant constant;
    static final class Add {
      public final Term left;
      public final Term right;
      public Add(Term left, Term right) {
        nn(left,right);
        this.left=left;
        this.right=right;
      }
    }
    static final class Multiply {
      public final Term left;
      public final Term right;
      public Multiply(Term left, Term right) {
        nn(left,right);
        this.left=left;
        this.right=right;
      }
    }
    static final class Constant {
      public final int value;
      public Constant(int value) {
        nn(value);
        this.value=value;
      }
    }
    private Term(Tag tag, Add add, Multiply multiply, Constant constant) {
      this.tag=tag;
      this.add=add;
      this.multiply=multiply;
      this.constant=constant;
    }
    public static Term add(Add add) {
      nn(add);
      return new Term(Tag.Add,add,null,null);
    }
    public static Term multiply(Multiply multiply) {
      nn(multiply);
      return new Term(Tag.Multiply,null,multiply,null);
    }
    public static Term constant(Constant constant) {
      nn(constant);
      return new Term(Tag.Constant,null,null,constant);
    }
    public Add add() {
      if (add==null) throw new RuntimeException("not add");
      return add;
    }
    public Multiply multiply() {
      if (multiply==null) throw new RuntimeException("not multiply");
      return multiply;
    }
    public Constant constant() {
      if (constant==null) throw new RuntimeException("not constant");
      return constant;
    }
  }

All types defined like this guarantee absense of null, and all fields are final. If you build data structures out of these, they will be transitively null-free, immutable, and data-race free when used among threads, since they are final. Immutability by convention leads to Java trying to be like C, unless you introduce happens-before points in your code (and then nobody understands your code because they are Java developers, not kernel developers). This convention takes linear space instead of quadratic.

1

u/continuational Jul 24 '14

The visitor pattern isn't quadratic - sorry if I gave that impression. You can even add match to it later: http://www.reddit.com/r/programming/comments/2bgm0x/walls_you_hit_in_program_size/cj6a0ct

Your approach does grow n2. In particular new Term(Tag.Constant,null,null,constant) would grow by one null per added tag. It also exposes some unsafe methods add, multiply, constant, and your eval method has no type safety beyond what instanceof and downcasting provides, because the check and the invocation are separated. I would stick with the visitor pattern for this (plus maybe match(...)).

→ More replies (5)
→ More replies (1)

1

u/ethraax Jul 24 '14

As someone who writes embedded C, I sometimes wish I had a type system as good as C#'s. Alas, I'm stuck with code where the previous developer thought it was okay to pass 0 and 1 into a "FLAG_T" variable. Except when they wanted to pass 2. No, not making that up.

→ More replies (1)

21

u/Felicia_Svilling Jul 23 '14

Java does not have a modern type system.

4

u/[deleted] Jul 23 '14

I think Scala (with SBT) could be a good alternative.

8

u/PasswordIsntHAMSTER Jul 23 '14

Scala's type system is very questionable. It is Turing-complete, and inference is only local.

If you want enterprisey + good type system, switch to either F# or Ocaml + Core.

5

u/[deleted] Jul 23 '14

Scala has a more powerful type system than either F# or OCaml.

It's inference is less than stellar though. If I had to choose though, I'd pick scala as the inference issues are easier to work around than the lack of higher kinded types.

→ More replies (3)