Dart - set method not defined - oop

I have two classes that work with each other, but some reason the set method in one of the classes is not considered defined in the other class. I am currently learning Dart (via Flutter), so I am wondering if I might be missing something.
class ClassA {
List<ClassB> _bunchOfClassBs = [];
void doSomething() {
for(ClassB foo in _bunchOfClassBs) {
foo.addCount('bar'); // Undefined method
}
}
}
class ClassB {
int_counting = 0;
set addCount(int number) => _counting += number;
}

You are calling setter incorrectly, should be:
foo.addCount = 123;
And for setters, name should not be addCount but count

Related

Hiding the interface of an extended class in dart

I'm trying to create a validation layer that wraps calls to business logic methods in entities in the domain layer.
A Validator must have the same interface as the Entity and give access to the state the Entity holds.
However, the type signatures of the Validator's interface methods need to different to the Entity's, as the Validator may validate and convert inputs from the UI (for example). The Validator also needs wraps these input validation/conversions calls and the underlying business logic method call in try catches.
This is an example of my current implementation:
class Entity {
// state
int _num;
int get num => _num;
// init the state
Entity(this._num = 0)
// business logic methods
void incrementBy(int n) {
// business logic validation
if (n <= 0){
throw Exception('[n] must be greater than 0'); // shouldn't throw raw Exceptions in general
}
// business logic
_num += n;
}
}
class Validator {
// have to hold an instance of the entity
final Entity _entity;
Validator(this._entity);
// have to copy the getters in the entity class
int get num => _entity.num;
// same interface as the Entity, but different type signature
void incrementBy(String n) {
try {
// validate user input
final inc = ConvertToInt(n); // -> could throw a FormatException
// call the underlying busines logic
_entity.incrementBy(inc); // -> could throw an Exception
} on Exception catch (e) { // shouldn't catch raw Exceptions in general
...
}
}
Is there a better way to wrap the entity?
It feels very clunky to do it the way shown above because there is no enforcement of which methods need to be overridden, as would be the case of implementing the Entity, which you can't do as the type signatures must be the same.
Something like class Validator hides Entity{...} would be great. It would be something like the combination of an extends, you wouldn't need to hold an instance of the entity or reimplement the getters, and an implements as you would be forced to override all interface methods.
I don't know if this solution is worth it but you might use the covariant keyword and an extra interface to achieve something similar to this. It requires an extra interface and I don't exactly know if the code is less clunky but here we go.
Edit: Just wanted to point out that you can also place the covariant keyword on the interface, basically allowing any subclass of EntityIf to tighten the type.
Here's the Dart Pad link to the code below
/// This is the common interface between the entity
/// and the validator for the entity. Both need to
/// implement this.
abstract class EntityIf {
// Private factory constructor to disallow
// extending this class
EntityIf._();
// We use 'dynamic' as the type for [num].
// We'll enforce type later using the
// 'covariant' keyword
dynamic get num;
// Same here, type is dynamic
void incrementBy(dynamic value);
}
class Entity implements EntityIf {
Entity(this._num);
int _num;
// Getters don't need the covariant keyword for some reason ?!? I'm not complaining!
#override
int get num => _num;
// Here we see the covariant keyword in action.
// It allows restricting to a more specific type
// which is normally disallowed for overriding methods.
#override
void incrementBy(covariant int value) {
_num += value;
}
}
class ValidatorForEntity implements EntityIf {
// Validator still needs to wrap the entity, coudln't
// figure out a way around that
ValidatorForEntity(this._entity)
: assert(_entity != null);
final Entity _entity;
#override
dynamic get num => _entity.num;
// Validator just overrides the interface with no
// covariant keyword.
#override
void incrementBy(dynamic value) {
assert(value != null);
int finalValue = int.tryParse(value.toString());
if (finalValue == null) {
throw '[value] is not an instance of [int]';
}
// int type will be enforced here, so you can't
// create validators that break the entity
_entity.incrementBy(finalValue);
}
}
void main() {
final x = ValidatorForEntity(Entity(0));
x.incrementBy(1);
print(x.num); // prints 1
x.incrementBy('1');
print(x.num); // prints 2
try {
x.incrementBy('a');
} catch (e) {
print('$e'); // should give this error
}
}

Why is this subclass' parent method call not polymorphic?

I've been dabbling in Dlang recently as C++ just wasn't quite sitting right with me after having used Python for so long. While dabbling, I came across what I thought would be a very simple exercise in polymorphism. I suppose how you would expect something to work and what it actually does are two entirely different things for reasons an end user probably can't comprehend. That being said, here is the source code of my "sandbox.D":
import std.stdio;
class Animal {
string voice = "--silence--";
void speak() {
writeln(this.voice);
}
}
class Dog : Animal {
string voice = "Whoof!";
}
int main() {
auto a = new Animal();
auto d = new Dog();
writeln(a.voice); // Prints "--silence--"
writeln(d.voice); // Prints "Whoof!"
a.speak(); // Prints "--silence--"
d.speak(); // Prints "--silence--" NOT "Whoof!"
return 0;
}
I guess my issue is why the "this" keyword just doesn't seem to be functioning how you would expect it to in the C++ successor language.
Methods are polymorphic, variables aren't. So instead of making the voice a variable, you want to override speak in the child.
Also, the auto return type doesn't work with polymorphism, you need to actually specify the types. (The reason is that auto return makes a function template in the compiler, which in theory could have multiple overridable slots in the function table, so it just doesn't try to put it in.)
So try this out:
import std.stdio;
class Animal {
void speak() { // changed to void instead of auto
writeln("--silence--");
}
}
class Dog : Animal {
override void speak() { // the override tells it to override the base method
writeln("woof");
}
}
int main() {
auto d = new Dog();
d.speak();
return 0;
}
If you have a lot of shared functionality and want to reuse one function with slight changes in child classes, you might make a method instead of a variable that just returns something.
Like string voice() { return "woof"; }, then it can be overridden in children.
Another way is to use template this parameter:
import std.stdio;
class Animal {
string voice;
void speak(this C)() {
writeln((cast(C)this).voice);
}
}
class Dog : Animal {
string voice = "Whoof!";
}
int main() {
auto a = new Animal();
auto d = new Dog();
a.speak(); // Prints ""
d.speak(); // Prints "Whoof!"
return 0;
}
Or when you do not need to have voice as a member:
import std.stdio;
class Animal {
static immutable voice = "";
void speak(this C)() {
writeln(C.voice);
}
}
class Dog : Animal {
static immutable voice = "Whoof!";
}
int main() {
auto a = new Animal();
auto d = new Dog();
a.speak(); // Prints ""
d.speak(); // Prints "Whoof!"
return 0;
}

Accesing arraylist property from another class using constructor

So i have a class that makes an array list for me and i need to access it in another class through a constructor but i don't know what to put into the constructor because all my methods in that class are just for manipulating that list. im either getting a null pointer exception or a out of bounds exception. ive tried just leaving the constructor empty but that dosent seem to help. thanks in advance. i would show you code but my professor is very strict on academic dishonesty so i cant sorry if that makes it hard.
You are confusing the main question, with a potential solution.
Main Question:
I have a class ArrayListOwnerClass with an enclosed arraylist property or field.
How should another class ArrayListFriendClass access that property.
Potential Solution:
Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass,
in the ArrayListFriendClass constructor ?
It depends on what the second class does with the arraylist.
Instead of passing the list thru the constructor, you may add functions to read or change, as public, the elements of the hidden internal arraylist.
Note: You did not specify a programming language. I'll use C#, altought Java, C++, or similar O.O.P. could be used, instead.
public class ArrayListOwnerClass
{
protected int F_Length;
protected ArrayList F_List;
public ArrayListOwnerClass(int ALength)
{
this.F_Length = ALength;
this.F_List = new ArrayList(ALength);
// ...
} // ArrayListOwnerClass(...)
public int Length()
{
return this.F_Length;
} // int Length(...)
public object getAt(int AIndex)
{
return this.F_List[AIndex];
} // object getAt(...)
public void setAt(int AIndex, object AValue)
{
this.F_List[AIndex] = AValue;
} // void setAt(...)
public void DoOtherStuff()
{
// ...
} // void DoOtherStuff(...)
// ...
} // class ArrayListOwnerClass
public class ArrayListFriendClass
{
public void UseArrayList(ArrayListOwnerClass AListOwner)
{
bool CanContinue =
(AListOwner != null) && (AListOwner.Length() > 0);
if (CanContinue)
{
int AItem = AListOwner.getAt(5);
DoSomethingWith(Item);
} // if (CanContinue)
} // void UseArrayList(...)
public void AlsoDoesOtherStuff()
{
// ...
} // void AlsoDoesOtherStuff(...)
// ...
} // class ArrayListFriendClass
Note, that I could use an indexed property.

Can I Use Ninject To Bind A Boolean Value To A Named Constructor Value

I have a constructor such as:
public AnalyticsController(ClassA classA, ClassB classB, bool isLiveEnvironment)
{
...
}
isLiveEnvironment is determined using a call to an existing static class such as:
MultiTenancyDetection.GetInstance().IsLive();
I would like to be able to make this call outside of the controller and inject the result into isLiveEnvironment. Is this possible? I can not see how this can be done.
You can accomplish this using WithConstructorArgument and using a callback:
kernel.Bind<AnalyticsController>()
.ToSelf()
.WithConstructorArgument("isLiveEnvironment", ctx => MultiTenancyDetection.GetInstance().IsLive() );
You can even achieve this more generally (but i would not really recommend binding such a generic type for such a specific use case):
IBindingRoot.Bind<bool>().ToMethod(x => MultiTenancyDetection.GetInstance().IsLive())
.When(x => x.Target.Name == "isLiveEnvironment");
Alternatively, if you need the same configuration value in several / a lot of classes, create an interface for it:
public interface IEnvironment
{
bool IsLive { get; }
}
internal class Environment : IEnvironment
{
public bool IsLive
{
get
{
return MultiTenancyDetection.GetInstance().IsLive();
}
}
}
IBindingRoot.Bind<IEnvironment>().To<Environment>();

Is this a good way to have class level member variables?

I'm trying to violate the laws of objective C a little by having static (class level) variables that have setters and getters:
+(CGRect*)defaultOpFr:(CGRect*)set{
static CGRect * defaultOpFr = nil;
if (set) {
if (!defaultOpFr) {
defaultOpFr = malloc(sizeof(defaultOpFr));
}
defaultOpFr->size.width = set->size.width;
defaultOpFr->size.height = set->size.height;
defaultOpFr->origin.x = set->origin.x;
defaultOpFr->origin.y = set->origin.y;
}
return defaultOpFr;
}
It seems to work, but I'm wondering if there's a better way. The idea is to call it with nil to retrieve the value, call it with a CGRect to set a new value.
Yup; that'll work, but be completely against any kind of common pattern.
Why don't you simply have a standard setter/getter pair? Even at the class level, that is fine:
static CGRect barf;
+ (CGRect) barf { return barf; }
+ (void) setBarf:(CGRect)aRect { barf = aRect; }
Done.