Flutter/Dart: get and set with private variables - get

if I read that setters and getters have to be explicity developed in Dart only when you want to do something more than only retrieve those values. But if I have private variables, like:
Class User {
User _user;
String _password;
}
How can I access to those private variables?
Even if I implement the set password like
set password(String value) => _password = value;
It will of course give me an "error".

If you want public getter/setter what's the point of having private variable for that?
Just make it a public variable and be done.
If you insist having a private variable with public access, then you still need to add the getter and setter.

Private variable is import due to some reasons, If you conditionally set or get your Class property values then setter and getter is important on private variables. Example given below:
class User {
int _id;
String _firstName;
String _password;
int get id => _id;
set id(int value) {
_id = value;
}
String get firstName => _firstName;
set firstName(String value) {
if(value.length > 7)
_firstName = value;
}
String get password => _password;
set password(String value) {
if(some condition against this value like password)
_password = value;
}
}
Note: you can set condition in getter like setter that I have given in above example.

Related

How can I set global field in method

I have some problem, so I have a few global fields in class, for each I want to do the same code but I don't want to repeat code - just use one method for that. And there I want to send these global fields in argument of this method and as second argument I want to send value for this field.
I tried with object, generic type but I don't know how to do that. Here is example:
private void setName(String _name) {
if(isNull(_name)) {
this.name = "";
} else {
this.name = _name.toString();
}
}
And a few other methods use the same code but with other fields and argument and I want to do something like that:
private void setField(some_field, _value) {
if(isNull(_value)) {
this.some_field = "";
} else {
this.some_field = _value;
}
}
Could someone help?
For example I have 2 global fields:
String name, int age.
For them I need to use the same code (if) and I want do it in one method. In this case I have to use global field as argument and as second argument use correct value for this field so instead:
this.name = argument;
this.age=argument;
use: globa_field_argument = argument;
Example:
setField( this.name, "Test" );
setField( this.age, 5 );
First off I would probably declare your global fields as 'public static'.
for example:
public static int myNumber = 10;
public static String myString = "foo";
Secondly you should have to pass your fields as an argument since you can access them inside the method itself.
When you redefine the fields anywhere in your code you will do this:
this.myNumber = newNumber;
this.myString = newString;

Can I use any kind of method within a get and set accessor of a public property of a public class

I have a class BaseTableC inheriting from an interface I_BaseTableC ,both having a set of public properties.
Can I access the "altered"(altered by MethodAlterValue) value provided by get/set accessors by reference of BaseTableC.Property1 or BaseTableC.I_BaseTableC I_refernce as I_reference.Property1?
As of now, I don't get an error, but the Property1 never shows the altered value as provided by the get/set accessor.
public class BaseTableC : IBaseTableC
{
public string Property1
{
get { return MethodOriginalValue(_Property1); }
set
{
if (! String.IsNullOrEmpty(value))
_Property1 = MethodAlterValue(value.TrimEnd());
else
_Property1 = value;
}
}
}

Are accessors / mutators auto-defined in Groovy?

In the section on handling Java Beans with Groovy of Groovy In Action, I found this script (slightly modified):
class Book{
String title
}
def groovyBook = new Book()
// explicit way
groovyBook.setTitle('What the heck, really ?')
println groovyBook.getTitle()
// short-hand way
groovyBook.title = 'I am so confused'
println groovyBook.title
There are no such methods in the class Book so how does that work ?
Yes, they are auto defined and calling book.title is actually calling book.getTitle()
See http://groovy.codehaus.org/Groovy+Beans
You can see this in action with the following script:
def debug( clazz ) {
println '----'
clazz.metaClass.methods.findAll { it.name.endsWith( 'Name' ) || it.name.endsWith( 'Age' ) }.each { println it }
}
class A {
String name
int age
}
debug( A )
// Prints
// public int A.getAge()
// public java.lang.String A.getName()
// public void A.setAge(int)
// public void A.setName(java.lang.String)
// Make name final
class B {
final String name
int age
}
debug( B )
// Prints
// public int B.getAge()
// public java.lang.String B.getName()
// public void B.setAge(int)
// Make name private
class C {
private String name
int age
}
debug( C )
// Prints
// public int C.getAge()
// public void C.setAge(int)
// Try protected
class D {
protected String name
int age
}
debug( D )
// Prints
// public int D.getAge()
// public void D.setAge(int)
// And public?
class E {
public String name
int age
}
debug( E )
// Prints
// public int E.getAge()
// public void E.setAge(int)
Several notes:
For all property fields(public ones only), there are autogenerated accesors.
Default visibility is public. So, you should use private/protected keyword to restrict accessor generation.
Inside an accessor there is direct field access. like this.#title
Inside a constructor you have direct access to! This may be unexpected.
For boolean values there are two getters with is and get prefixes.
Each method with such prefixes, even java ones are treated as accessor, and can be referenced in groovy using short syntax.
But sometimes, if you have ambiguous call there may be class cast exception.
Example code for 4-th point.
class A{
private int i = 0;
A(){
i = 4
println("Constructor has direct access. i = $i")
}
void setI(int val) { i = val; println("i is set to $i"); }
int getI(){i}
}
def a = new A() // Constructor has direct access. i = 4
a.i = 5 // i is set to 5
println a.i // 5
​
4-th note is important, if you have some logic in accessor, and want it to be applied every time you call it. So in constructor you should explicit call setI() method!
Example for 7
class A{
private int i = 0;
void setI(String val) { println("String version.")}
void setI(int val) { i = val; println("i is set to $i"); }
}
def a = new A()
a.i = 5 // i is set to 5
a.i = "1s5" // GroovyCastException: Cannot cast object '1s5' with class 'java.lang.String' to class 'int'
​
So, as I see property-like access uses first declared accessor, and don't support overloading. Maybe will be fixed later.
Groovy generates public accessor / mutator methods for fields when and only when there is no access modifier present. For fields declared as public, private or protected no getters and setters will be created.
For fields declared as final only accessors will be created.
All that applies for static fields analogously.

Creating object in entity after all instance variables were set by Eclipse Link

The following JPA entity is given:
#Entity(name = "MyEntity")
public class MyEntity {
#Id
protected String id = null;
protected String name = null;
protected String adress = null;
#Transient
protected User user = new User(name, adress);
// Required by JPA
protected MyEntity() {
}
public MyEntity(String id, String name, String adress) {
// assign instance variables
}
public String getUser() {
return user.toString();
}
...
}
When getUser() will be called on MyEntity created by Eclipse Link the desired String will not be returned. The problem is that User was instantiated before the instance variables of MyEntity were set by Eclipse Link. In other words User was created with name = null and adress = null.
How can I ensure that User will be created after Eclipse Link has set all instance variables?
You can use the #PostLoad annotation like this:
#PostLoad
private initUser(){
user = new User(name, adress);
}
The method will be executed once your entity is fully loaded and it's fields are set.

How to get a string representation of a property name of a Model in MVC3?

I have the following model:
Public Class MyModel
Public Property MyModelId As Integer
Public Property Description As String
Public Property AnotherProperty As String
End Class
Is there a method to get a property name of the Model as a string representation like the following code?
Dim propertyName as String = GetPropertyNameAsStringMethod(MyModel.Description)
So the propertyName variable has "Description" as value.
Check the Darin Dimitrov' answer on this SO thread - Reflection - get property name.
class Foo
{
public string Bar { get; set; }
}
class Program
{
static void Main()
{
var result = Get<Foo, string>(x => x.Bar);
Console.WriteLine(result);
}
static string Get<T, TResult>(Expression<Func<T, TResult>> expression)
{
var me = expression.Body as MemberExpression;
if (me != null)
{
return me.Member.Name;
}
return null;
}
}
Hope this help..
Here is a helper extension method you can use for any property:
public static class ReflectionExtensions
{
public static string PropertyName<T>(this T owner,
Expression<Func<T, object>> expression) where T : class
{
if (owner == null) throw new ArgumentNullException("owner");
var memberExpression = (MemberExpression)expression.Body;
return memberExpression.Member.Name;
}
}
However, this will only work on instances of a class. You can write a similar extension method that will operate directly on the type instead.
You need to do it using reflection.
There are already loads of posts on stack overflow like this:
How to get current property name via reflection?
Reflection - get property name
Get string name of property using reflection
Reflection - get property name
I believe that the answer will be along the lines of:
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
Create an extension method and then use it where needed.
Private Shared Function GetPropertyName(Of T)(exp As Expression(Of Func(Of T))) As String
Return (DirectCast(exp.Body, MemberExpression).Member).Name
End Function
have a look at this post as well.
I have solved this issue editing a bit #NiranjanKala's source example,
converting the code in vb.Net like this
<System.Runtime.CompilerServices.Extension()> _
Public Function GetPropertyName(Of T, TResult)(expression As Expression(Of Func(Of T, TResult))) As String
Dim [me] = TryCast(expression.Body, MemberExpression)
If [me] IsNot Nothing Then
Return [me].Member.Name
End If
Return Nothing
End Function
Then I am able to call the extension like this
Dim propertyName as String = GetPropertyName(Of MyModel, String)(Function(x) x.Description)
Then propertyName variable has "Description" as string value.

Resources