Java Programming – Pros and Cons of Structuring Code via Classes

designjavalanguage-designprogramming-languages

Edit: my language allows for multiple inheritance, unlike Java.

I've started designing and developing my own programming language for educational, recreational, and potentially useful purposes.

At first, I've decided to base it off Java.

This implied that all the code would be written in form of classes, and that code compiles into classes, which are loaded by the VM.

However, I've excluded features such as interfaces and abstract classes, because I found no need for them. They seemed to be enforcing a paradigm, and I'd like my language not to do that. I wanted to keep the classes as the compilation unit though, because it seemed convenient to implement, familiar, and I just liked the idea.

Then I noticed that I'm basically left with a module system, where classes could be used either as "namespaces", providing constants and functions using the static directive, or as templates for objects that need to be instantiated ("actual" purpose of classes in other languages).

Now I'm left wondering: what are the upsides and the downsides of having classes as compilation units?

Also, any general commentary on my design would be much appreciated. An informative post on my language can be found here: http://www.yannbane.com/2012/12/kava.html.

Best Answer

what are the benefits of having classes as compilation units?

It can reduce the complexity of the language. No need for different constructs, everything is treated the same. In certain designs (though not yours it seems), you benefit from not having statics and the design issues they tend to run into (initialization order issues, concurrency limitations, awkwardness with generics/type classes). It also allows some benefits of the module concept like isolated module instances for sandboxing or parallelization; and module typing where dependencies fit some interface and the entire module worth of implementation can be instantiated and dropped in.

That said, the concept tends to have more issues than not. Realistically, you can't treat everything the same, since 'top level' classes need special rules like having a default constructor (or else you run into odd issues spinning them up). Modularity of compilation units tends to get really awkward too. How does a class even reference others when they're just classes? How are those dependencies dealt with, and how do you determine the correct order for spinning up the classes? How do you make sure that duplicate class references are reused by different parts of the app (or how do you deal with duplicate instances if that's the semantics you want)?

Having looked into it, I ran into a lot of issues with dependencies, scoping things properly, and initialization concerns. You end up running into issues that make 'top level classes' special, and many limitations to make them work that ends up shaping them into simple namespaces.

Related Topic