Search code examples
javacompiler-constructionparadigmsdialectcustom-error-handling

Adding immutable programming rules to the Java language within a program


I'm writing a program in Java. I find that reading and debugging code is easiest when the paradigm techniques are consistent, allowing me very quickly assume where and what a problem is.

Doing this has, as you might guess, made my programming much faster, and so I want to find a way to enforce these rules.

For example, lets say I have a method that makes changes to the state of an object, and returns a value. If the method is called outside of the class, I don't ever want to see it resolve inside parameter parentheses, like this:

 somefunction(param1, param2, object.change_and_return());

Instead, I want it to be done like this:

 int relevant_variable_name = object.change_and_return();

 somefunction(param1, param2, relevant_variable_name);

Another example, is I want to create a base class that includes certain print methods, and I want all classes that are user defined to be derived from that base class, much in the way java has done so.

Within my objects, is there a way I can force myself (and anyone else) to adhere to these rules? Ie. if you try to run code that breaks the rules, it will terminate and return the custom error report. Also, if you write code that breaks the rules, the IDE (I use eclipse) will recognize it as an error, underline and call the appropriate javadoc?


Solution

  • For the check and underline violations part:

    You can use PMD, it is a static code analyzer.

    It has a default ruleset, and you can write custom rules matching what you need.

    However your controls seem to be quite complex to express in "PMD language".

    PMD is available in Eclipse Marketplace.

    For the crash if not conform part

    There see no easy way to do it.

    Hard/complex ways could be:

    • Write a rule within PMD, run the analysis at compile time, parse the report (still at compile time) and return an error if your rule is violated.
    • Write a Java Agent doing the rule check and make it crash the VM if the rule is violated (not sure it is really feasable, agents are meant for instrumentation).
    • Use reflection anywhere in your code to load classes, and analyze loaded class against your rules and crash the VM if the rule is violated (seriously don't do this: the code would be ugly and the rule easily bypassable).