Why are all fields public in playframework?

I still doubt why with playframework all the fields in the classes should be publicly accessible?

class A { public int a; public int b; } 

Some short explanation would be nice.

How do I know if they are public, then playframework uses generated invisible getters and setters for them? But if they are private, then .. there are no getters and setters, and then I have to write them alone?

If this works like this, then why is it no longer Java? It's just too easy to understand, I think.

+4
source share
2 answers

The documentation provides an explanation for this . Play breaks a series of Java conventions with the idea of ​​making code more readable.

Basically, if you are just going to write:

 class A { private int x; public int getX() { return x; } public void setX(int x) { this.x = x; } } 

Why don't you create a framework for getters and seters for you ( similar to C # )? Of course, since, as indicated in the documentation, the generated getters and setters are available only at run time, the fields must be declared public, so the Java compiler will not cause an error if the code outside the class accesses the variable.

Basically, this allows you to write:

 class A { public int x; } class B { public void process() { A a = new A(); ax = 42; } } 

instead:

 class B { public void process() { A a = new A(); a.setX(42); } } 

Even better, if you need specific logic in getter or setter, you can add it, for example:

 class A { public int x; public void setX(int x) { if (x < 0) throw new IllegalArgumentException("x must be positive"); this.x = x; } } 

and still use it like this:

 class B { public void process() { A a = new A(); ax = 42; } } 

Regardless of whether this is the right way to handle things, it is, of course, a matter of opinion, but Java developers quite often have to look for easier ways to write all these template getters and setters (regardless of their relative merits, Groovy , Jython , JRuby , and Fantom provide a mechanism to create and access properties that result in syntax similar to that achieved game; Rhino at least provides the same syntax to invoke the accessories and even Scala has a simple mechanism for adding ksessuarov).

+8
source

The playback structure does a lot of manipulation of bytecodes behind the scenes to achieve stronger syntax than is possible with Java. Therefore, although the code is similar to Java, it has different semantics - using a field or calling a method does not always do what you think.

The way the game was developed. I have not used it enough to give an opinion whether this is good or bad, but it would be nice to have a list of all the bytecode manipulation tricks that Play uses. I don’t like to use things that I don’t understand (either I will recognize them or I will avoid them). Does anyone know where they are listed (in addition to the source code)?

+1
source

All Articles