Is it bad practice to have my getter method change the stored value? - class

Is it bad practice to change my getter method like version 2 in my class.
Version 1:
public String getMyValue(){
return this.myValue
}
Version 2:
public String getMyValue(){
if(this.myValue == null || this.myValue.isEmpty()){
this.myValue = "N/A";
}
return this.myValue;
}

I think it is actually quite a bad practice if your getter methods change the internal state of the object.
To achieve the same I would suggest just returning the "N/A".
Generally speaking this internal field might be used in other places (internally) for which you don't need to use the getter method. So in the end, the call to foo.getMyValue() could actually change the behaviour of foo.
Alternatively, the translation from null to "N/A" could be done in the setter, i.e. the internal value could be set to "N/A" if null is passed.
A general remark:
I would only add states such as "N/A" if they are expected by some API or other instance relying on your code. If that is not the case you should rely on the standard null types that are available to you in your programming language.

In my opinion, unless you are doing lazy-loading (which you are not in that case), getters should not change the value. So I would either:
Put the change in the setter
public void setMyValue(String value) {
if(value == null || value.isEmpty()){
this.myValue = "N/A";
} else {
this.myValue = value;
}
}
Or make the getter return a default value if value not set properly:
public String getMyValue() {
if(this.myvalue == null || this.myvalue.isEmpty()){
return "N/A";
}
return this.myValue;
}
In the case of lazy-loading, where I would say that changing your members in a getter is fine, you would do something like:
public String getMyValue() {
if (this.myvalue == null) {
this.myvalue = loadMyValue();
}
return this.myValue;
}

No. You're doing two things here. Getting and setting.

Yes. It's a bad practice.
Why?
When the value is set (in a constructor or setter method), it should be validated, not when a getter method is called. Creating a private validate* method for this is also a good idea.
private boolean validateThisValue(String a) {
return this.myValue != null && !this.myValue.isEmpty();
}
public void setThisValue(String a) {
if (validateThisValue(a)) {
this.myValue = a;
}
else {
// do something else
// in this example will be
this.myValue = "N/A";
}
}
And, in the getter method, never ever change the state of the object. I have worked on some projects, and the getter often must be made const: "this method cannot change internal state".
At least, if you do not want to complicate things, in the getter method, you should return "N/A" rather than change internal state and set myValue to "N/A".

I usually define a specific getter.
Never alter original getter:
public String getMyValue(){
return this.myValue
}
And create a specific getter:
public String getMyValueFormatted(){
if(this.myvalue == null || this.myvalue.isEmpty()){
return "N/A";
}else{
return this.myValue;
}
}

I think it's better to initialize this.myValue = "N/A". And subsequent calls to setMyValue should modify the this.myValue according to your business conditions.
The getMyValue shouldn't modify in any way this.myValue. If your needs are to return a certain value, you should return that value (like "N/A") and not alter this.myValue . Getters must not modify member's value.

I would change better the setter method so, if the value is null or empty, the N/A is assigned to the attribute. So, if you use the attribute in other methods inside the class (v.g. toString()) you will have the intended value there.
Alternatively, change the setter method to launch an exception when the value being set is not right, so the programmer is forced to improve its handling prior to setting the value.
Other than that, it is ok.

I do feel this is a bad practice unless and until you explain the reason why it is so necessary for you modify the object inside the getter method instead of doing it inside the setter method.
Do you feel this cannot be done for some reason? Could you please elaborate?

Do what ever you like. After all getters and setters are just another public methods. You could use any other names.
But if you use frameworks like Spring, you are bound to use those standard names and you should never put your custom codes inside them.

absolutely yes, it's a bad pratice.
Imagine you communicate accross network with a third party (remoting, COM, ...), this will increase the round-trip and then hit application performance.

A setter could modify as part of validation, but a getter should return the value and let the validation be done by the caller. If you do validate, then how should be documented.

This actually highly depends on the contract you want to enforce with your get()-method. According to design-by-contract conventions the caller has to make sure that the preconditions are met (which means doing a validation in a setter method often is actually bad design) and the callee (I do not know if that's the correct english term for that, i.e., the called one) makes sure that the post conditions are met.
If you define your contract so that the get()-method is not allowed to change the object then you are breaking your own contract. Think about implementing a method like
public isValid() {
return (this.myvalue == null || this.myvalue.isEmpty());
}
Advantage of this approach is that you do not have to check wether the return of your get() is "N/A" or something else. This also can be called before calling set() to validate that you do not insert illegal values into your object.
If you want to set a default value you should do that during initialization.

State changes in getters should be a hanging offence. It means that client code must be careful about the order in which it accesses getters and setters and to do this it must have knowledge of the implementation. You should be able to call the getters in any order and still get the same results. A related problem occurs when the setter modifies the incoming value depending on the current state of the object.

You can use some value holder for this purpose. Like Optional class in guava library.

Related

Unnecessary usage of bang operator

I have a problem understanding, and living with, the excessive use of bang operators in dart/flutter.
Consider this example:
if(model != null && model!.someValue != null) {
print(model!.someValue!);
}
The first condition check is verifying that the model is not null. In the second condition I have to put in a bang operator after model, else the compiler gives me an The property 'someValue' can't be unconditionally accessed because the receiver can be 'null' error. But why is this necessary? I´ve just checked the variable! And same goes for the print(model!.someValue!); line.
Another example where I have these classes:
class GeoPosition {
double lat = 0;
}
class Wrapper {
GeoPosition? position;
}
...
Wrapper wrapper = Wrapper();
wrapper.position = GeoPosition();
wrapper.position!.lat = 1;
Now why do I need to put this bang operator (or ? operator) after position? I´ve just created a new instance of GeoPosition in the Wrapper instance - position cannot be null.
My best guess is that the compiler cannot see or understand the current context of the class. But in Typescript the linter is smart enough to know when these operators are not necessary.
I know that I can create local variables from the properties that I am trying to access, but this would be just as ugly ;)
So why are ! and ? necessary in these (and many other) situations? And is there anything I can do about it?
This is what happens with nullable properties (hence the message you get). It is explained here: Understanding null safety: Working with nullable fields.
You should be able to work around this issue by declaring the field as late, as in
class Wrapper {
late GeoPosition position;
}
Wrapper wrapper = Wrapper();
wrapper.position = GeoPosition();
wrapper.position.lat = 1;
This will remove the need to add a bang to every access to position The compiler will add a non-null check at appropriate places. Of course, the program will fail if you don't assign a non-null value before accessing the field.
If explained in Late variables
Nullable properties of a class can still be null between two access.
For your first example you can extract the variable then check it:
var someValue = model?.someValue;
if(someValue != null) {
print(someValue); // not null
}
For your second example an elegant way will be the .. operator :
Wrapper wrapper = Wrapper();
wrapper. Position = GeoPosition()..lat = 1;
If you want the GeoPosition to be not null you have to make it not nullable:
class Wrapper {
GeoPosition position;
Wrapper(this.position);
}
You can set the position field final to be immutable.
Be careful with the late keyword, if you forget to init the field you've got a crash like the ! operator.

A way to read a String as dart code inside flutter?

I want to build a method to dynamically save attributes on a specific object
given the attribute name and the value to save I call the "save()" function to update the global targetObj
var targetObj = targetClass();
save(String attribute, String value){
targetObj.attribute = value;
print(targetObj.attribute);
}
But I'm getting the following error:
Class 'targetClass' has no instance setter 'attribute='.
Receiver: Instance of 'targetClass'
Tried calling: attribute="Foo"
The only thing that I can think of is that "attribute" due to being type String results in an error.
That lead me to think if there is a way to read a String as code, something like eval for php.
As #Randal mentioned, you cannot create class..method at runtime. Still, you can try something like this.
A certain class
class Foo {
dynamic bar1;
dynamic bar2;
// ...
}
Your save method
save(Foo fooObject, String attribute, dynamic value) {
if ("bar1" == attribute) fooObject.bar1 = value;
else if ("bar2" == attribute) fooObject.bar2 == value;
// ...
}
Dart (and thus flutter) does not have a way to compile and execute code at runtime (other than dart:mirrors, which is deprecated). You can build additional code that derives from other code using the various builder mechanisms, although it can be rather complicated to implement (and use!).

Drools RuleRuntimeEventListener's objectUpdated method has same value for getObject and getOldObject methods

I am using Drools version 6.5.0.Final and I have a simple rule like:
rule "Test Rule"
when
$obj : MyObject(testValue == null || testValue != "NEW")
then
$obj.testValue = "NEW";
update($obj);
end
So I also implemented a RuleRuntimeEventListener class and it gets invoked when this rule is executed. The problem is the passed in ObjectUpdatedEvent instance's getObject() and getOldObject() calls return the same exact object - which is the object after the update. So for this the getOldObject() call returns an object that has a value of "NEW" for the testValue property. I am expecting getOldObject to return me the value of testValue that isn't "NEW" which is after it was changed by the rule.
This seems like a bug to me and was wondering if anybody had any similar issues with this or if there is any workaround? I want to be notified when any property of an object is changed by a rule and what the old and new values were.
I see that there is support for using the java bean's PropertyChangeListener, but that looks like I have to create the fact objects with a addPropertyChangeListener and removePropertyChangeListener methods and also in all my fact's setter methods I have to use PropertyChangeSupport and fire a property change event via firePropertyChange method. I really don't want to have to do that.
Thanks
This seems to be a bug in Drools, the issue is also present in 7.16.0.FINAL. By doing the following
System.out.println(getOldObject() == getObject());
You will get an output of "true" indicating that both objects are of the same reference.
I just raised it as a bug on the Drools site
https://issues.jboss.org/browse/DROOLS-4305
public class Differ implements AgendaEventListener {
private List<Object> oldFacts;
public void beforeMatchFired(BeforeMatchFiredEvent event){
List<Object> facts = event.getMatch().getObjects();
// copy (!) facts into oldFacts
}
public void afterMatchFired(AfterMatchFiredEvent event){
List<Object> facts = event.getMatch().getObjects();
// compare facts with oldFacts
}
//...
}
You may want to be more selective in copying and comparing. Also, a generic way of comparing using the stringified object contents might be considered.
BeforeMatchFiredEvent

Setter for Bool in Swift

I'm using a custom getter like so
var currentShowLiked: Bool {
get {
return [some condition met] ? true : false
}
set {
self.currentShowLiked = newValue
}
}
and it works fine. However, I would expect to be able to set true or false value back to my variable, but Swift forced my to implement a setter, which does not produce any warnings, but at runtime if I'm to change value of my variable, app crashes with no apparent reason or sane explanation pointing to setter line with EXC_BAD_ACCESS (code=2...) and a message in console warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.
Why do I do?
You are in recursive context.
You can't use currentShowLiked in the currentShowLiked property body as below:
// Recursive, Infinite loop
self.currentShowLiked = newValue
To fix this:
private var _currentShowLiked : Bool
var currentShowLiked: Bool {
get {
return [ some condition met on _currentShowLiked ] ? true : false
}
set {
self._currentShowLiked = newValue
}
}
A Swift property that defines a custom getter and / or setter operation is a computed property which does not actually stores a value. The custom setter can be used to modify the internal state of other properties.
See also: "The Swift Programming Language" page 180
You can not set value in its setter because you are creating a recursion -method calling itself because:
self.currentShowLiked = newValue
will call set method you defined which will go and go. If you are overriding setter and getter you probably want to have some backing store property which will be private.
Moreover you defined a getter which base on some condition so anyway you are not using the value you set on this property. I think you do not need this set
The error here is caused by a misunderstanding.
When you declare a
var a:Type
A member value a is allocated inside the object, and accessors and mutators are automatically created to allow you to read and write that variable.
However, when you declare
var a:Type { get { ... } set { ... } }
No member value is allocated - you have indicated that when the value is accessed (read) or mutated (written) from a user of the object, your code will do all necessary action to respond to it. If you ultimately want the value to be stored, you will need to store it to an actual value, (which will need a different name).
Since you are invoking the mutator of the object inside the mutator of the object, you have set up an infinite loop, which causes your program to crash due to stack overflow (all function call memory is used to store the record of the function calling itself over and over again).
The code you have above will crash because it causes an infinite loop - your setter for currentShowLiked sets currentShowLiked to the new value, so then that calls the setter again, and so on.
You don't have to implement a setter, but you then don't use get - the syntax is like this:
var currentShowLiked: Bool {
return [some condition met]
}

non-static method call from the drl file?

Using optapllaner, is it possible to call "Graph.getInstance().mdm()" method in the score calculation drl file ?
I read somewhere that i can only invoke static methods but i'm not sure.
Yes it's possible. Of course, for it to make any sense to call a method during score calculation it will need to have a parameter that accepts an entity or a variable-dependent property.
Accept an entity:
when
$p : Process()
eval(Graph.getInstance().mdmForProcess($p) == true)
then
Accept an variable-dependent property:
when
Process($c : computer)
eval(Graph.getInstance().mdmForComputer($c) == true)
then
Overall, I don't like that design, I prefer a design like this:
when
Process(mdmIsGood() == true)
then
#PlanningEntity class Process {
public boolean mdmIsGood() {
return Graph.getInstance().mdmForProcess($p);
}
...
}
Note: Why doesn't it make sense if the method isn't based on an entity or variable-dependent property? Because than you can precalculate it! So it would be very inefficient to calculate it during every score calculation. See docs section "cached problem facts".