What are 'properties' in Groovy? - groovy

Properties in groovy seem like class fields in java without an access modifier. Is that true? Or they have a special meaning. It seems like there is no way to make the properties private?

When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.
class A {
String property
/*
private String property
public void setProperty(String property) { ... }
public String getProperty() { ... }
*/
}
If we declare a public instance variable field we just get a public field, without a setter/getter method pair.
class A {
public String field
/*
public String field
*/
}
From a Groovy client's pov, there is no difference between accessing a Groovy property and a public field at runtime
def a = new A()
println a.field
println a.property
although a.field accesses the instance variable directly and a.property actually calls a.getProperty() (or a.setProperty(...) when assigning a value). But as the property complies to the JavaBeans spec, the class can seamlessly be used in Java-based environments.
I do not see much sense in making a "private property". private restricts the use of a method or instance/class variable to the hosting class type. But maybe you were referring to making a private field instance variable.

Properties can normally be treated like fields, but they are actually backed by implicit getters/setters, so you can still reference them like fields or set them equal to values. Behind the scenes, they are using getters/setters (which you can redefine if you care to).
This page has details on properties/fields and access modifiers (see especially the "Property and field rules" section): https://groovy-lang.org/objectorientation.html#_fields_and_properties
It also shows that you can make a private property (private field backed by private getters/setters), but you have to be explicit in defining the getters/setters.

Related

Are private setters in C++/CX properties a thing?

Is it possible to create/design in a way to privately set a property but only expose the ability to get the properties to the consumers?
I've tackled a multiple inheritance property by making the base class wrapper a member of the concrete classes wrapper. I'd rather not allow someone to write over the base classes instance in the set of it's own property. But I can't seem to exclude set and set the base property and I can't make the set private.
Any ideas?
Code:
ConcreteClassWrapper(); // here I want to setup base class, i.e. give it a pointer to the actual C++ model I'm working with.
property BaseClassWrapper^ BaseClass
{
BaseClassWrapper^ get() { return baseClass; }
// I want to avoid giving my consumers the ability to set this property.
void set(BaseClassWrapper^ value) { baseClass= value; }
}
private:
BaseClassWrapper^ baseClass; // Having a base class wrapper makes it easier on code writing.. i.e. I don't need to implement interfaces. I just want to use my C++ code in C# Microsoft GOD!!!
EDIT:
I'm an idiot, I can access the private member...
This is just one answer... Still want to know why private setters arent' a thing
I just have to access my private member of my ConcreteClassWrapper and set the base class there. Then I can remove the set in the BaseClassWrapper property.
Did you try this :
property BaseClassWrapper^ BaseClass
{
BaseClassWrapper^ get() { return baseClass; }
private:
void set(BaseClassWrapper^ value) { baseClass= value; }
}
This is the way you write a private setter in a property. In the case of C++/CX, the property keyword is just a new keyword to allow C++/CX compiler to generate some C++ code, so the syntax for things like private, public, protected is the same.

Why doesn't a Groovy closure have access to injected class member?

We are using Groovy and Guice on a project and I came across the following error:
groovy.lang.MissingPropertyException: No such property: myService for class: com.me.api.services.SomeService$$EnhancerByGuice$$536bdaec
Took a bit to figure out, but it was because I was referencing a private class member, that was injected, inside of a closure. Can anyone shed any light as to why this happens?
Furthermore, is there any better way of doing this?
Here is a snippet of what the class looks like:
import javax.inject.Inject
import javax.inject.Singleton
#Singleton
class MyService extends BaseService<Thing> {
#Inject
private ThingDao thingDao
#Inject
private OtherService<Thing> otherService
#Override
List<Thing> findAll() {
List<Thing> things = this.dao.findAll()
things.each {
//Note: This doesn't work!
otherService.doSomething()
}
things
}
I either have to use a standard for loop or not use the injected member which then tends to lead to code duplication.
TLDR;
Either declare otherService public (remove private modifier) or add a getter OtherService<Thing> getOtherService(){otherService}
If you absolutely want to avoid exposing the field through a property, you can do the following trick: create a local variable outside the Closure scope that references your service:
OtherService<Thing> otherService=this.otherService
things.each {
//Note: This will work! Because now there is a local variable in the scope.
//This is handled by normal anonymous inner class mechanisms in the JVM.
otherService.doSomething()
}
Explanation
Under the hood, your closure is an object of an anonymous class, not the object that has your private field, otherService.
This means that it can't resolve a direct reference to the field. Accessing a symbol inside the closure will first look at local variables, and if no match is found, the getProperty() method in Closure will be called to find a property, depending on the resolution strategy that you defined. By default, this is OWNER_FIRST.
If you look the code of Closure#getProperty:
switch(resolveStrategy) {
case DELEGATE_FIRST:
return getPropertyDelegateFirst(property);
case DELEGATE_ONLY:
return InvokerHelper.getProperty(this.delegate, property);
case OWNER_ONLY:
return InvokerHelper.getProperty(this.owner, property);
case TO_SELF:
return super.getProperty(property);
default:
return getPropertyOwnerFirst(property);
}
You see that the owner, delegate and declaring objects need to have matching properties.
In groovy, if you declare a field private, you won't get auto-generated accessor methods, so no properties will be publicly exposed for outside objects.

Class name class variable = null - what does this line mean in Android?

I am having trouble understanding the meaning of the following code:
public class CustomListViewAndroidExample extends Activity {
ListView list;
CustomAdapter adapter;
public CustomListViewAndroidExample CustomListView = null; // What does this line mean?
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
Its instance of current activity you can use in oncreate like
CustomListView.addContentView(view, params);
It's just like an "ordinary" variable except that it's explicitly set to null when the class is created. It's no different in principal than the following line:
CustomListViewValuesArr = new ArrayList<ListModel>();
This isn't really any different than setting the value in the constructor or OnCreate method.
Note that, as with your other variables, you'll need to initialize this to something other than null in order to be able to use it.
It is slightly odd that it's public, though. I'd also recommend including explicit access modifiers in front of your other fields - it's a bad practice to omit them and rely on the defaults.

Using properties in C#, outside class can still access private variables ? Need some elaboration on this

I have this question about get set accessors in C#.
{
private string _mvalue
public string MyValue
{
get
{
return mvalue;
}
set
{
_mvalue = value;
}
}
Here, _mvalue is private. We made it private so that it should not be accessible outside the class.
But then again, we created a property 'MyValue' over this private variable. Using property we can access the private variable.
So don't you think we are compromising over the privateness of the variable. I mean, the variable is meant to be private. But, with the help of proprties, outsiders can still access this variable
_mvalue is not created to make the value of MyValue private. _mvalue is required to maitain the state of the public propery MyValue. No user of this object can access _mvalue as long as it is private. Also, MyValue may contain a different value than _mvalue. For example, you could return _mvalue+"/". Add to this the fact that not every private field like _mvalue need to have a public property of course.
There are several ways to prevent access to a data variable such as:
Use private members only
use a private property
The confusion may be reduced by using Automatic Properties, refer to the accepted answer in: Automatic Property.
This is perfectly fine. No one is making you add a public property to your class. If you really want _mvalue to really stay private, just don't make the public property that uses it.
Usually, we go for private variables in property when we want to do some additionally operations during set or get of the value. For example I always want to multiple the assigned value with 5, in that case we can use some thing like this
public int A
{
get
{
return a;
}
set
{
a=value*5;
}
}
But if you just want to store a value that should be accessed by outside the class in that case you can write a property with out private variable as below
public int A
{
get;
set;
}
if you want only to expose the value, but no one should set the value out side the class then you can even make set as private.
Always property is to expose the values outside the class, but it depends on your logic how you want to write, you can use private variables within that or you needed not, usually private variable is used with the property when it is Bind the to Wpf controls(MVVM) to implement INotifyPropertyChanged.
If your using private variable in a property without any custom logic in get or set, then it is bad programming style, it is like exposing a private member out side the class
First thing is the private variable "_mvalue" cannot be accessed from
outside world as it is Private. Secondly, if you want to really
protect "MyValue", ie, outsiders can access only "Get" property, then
use private keyword with "set".
private string _mvalue;
public string MyValue
{
get
{
return _mvalue;
}
private set
{
_mvalue = value;
}
}

Uses and differences in properties?

whats difference between Auto-Implemented Properties and manual properties in c#?
for Example:
Manual Properties:
private int uno;
public int Uno
{
get { return uno; }
set { uno = value; }
}
Auto Implemented Prop:
public string UserLeaveCount { get; set; }
i found the difference and uses here : Auto Implemented Prop
But Here is my Specific doubt thats "there is no instance variable in auto implemented properties and how is it stored,returned values?"
It's just syntactic sugar -- the compiler inserts the backing field for you. The effect is the same, except that, of course, there's no way for you to access the backing field from your code.
From the page you linked to:
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

Resources