I'm using a Dart package and need to extend or otherwise change some of the state in a singleton class called Constants, i.e. a class with a private constructor. It appears I have to change the singleton to extend/subclass it. Having poured over their code, I admire their work and want to avoid changing their code. Is their another way to add some constants and change some of the values of the static const's in their Constants._() class? I'm new enough to Dart to be missing something obvious, so don't be shy about giving me obvious advise. I know I can change the class to have a public const constructor and then I'm able subclass it. Is a mixin the way to tackle this?
Thanks in advance for any help.
I'm trying to do something that would be a basic feature in any other Object Oriented Language but for some reasons in Dart, I can't manage to do it. I'm new to Dart so this question might be dumb, but I couldn't find any answer online.
I have a property that need to be calculated once and on the constructor. This is my code so far :
class Game {
String _wordChosen;
Game() {
final _random = Random();
_wordChosen = WORDS[_random.nextInt(WORDS.length)];
}
}
WORDS is a list defined outside the class. My error is on the Game constructor :
not_initialized_non_nullable_instance_field.
I don't want to set the _wordChosen variable to a default value as that would make no sense (it would be overwritten right when the constructor is run).
I also don't want to set the property as nullable as again, it would make no sense.
i think the answer is using the keyword late to make compiler know that you will initialize the variable before using it but not now like below
late String _wordChosen;
i think this is your solution and it in null safety documents here
i hope this answer helps you
While hearing talk around the objective-c programming community, I hear the term "override" thrown around a lot. I'm fairly familiar with general object oriented programming terms, but from an iOS and Objective-c standpoint, the definition is a little unclear to me. According to Wikipedia:
Method overriding, in object oriented programming, is a language
feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its
superclasses or parent classes.
Cool. That makes sense. But what throws me off is... isn't that the whole point of the "family relationship", where the subclass inherits all of the public methods and variables of it's superclass. The standard "hierarchy" model. That has never quite made sense to me. I hear some of the senior developers say things such as "Once he said it's okay to override a category I was done listening".
That got me to thinking, I should probably get a better grasp on what exactly overriding is. Could someone explain it in greater detail related specifically to Objective-C / Cocoa Touch?
This is very common in all OOP languages.
Often times a base class will provide a default (i.e. simple, unexciting) implementation for a method. Then, derived classes will override that default implementation and provide a specific (i.e. more interesting) implementation.
Consider an Animal base class that exposes a Speak() method. Well there is no common way that animals speak, so that default implementation would probably just do nothing.
A Dog class, which is derived from Animal, can override Speak() to actually make a barking sound, which is more appropriate than the default mute case.
Your quote from your senior seems to me like it's mis-heard or -remembered. I'd bet it was "...it's okay to override a method in a category I was done..."
Using a category to "override" a method on the same class is a Bad Idea: the original method is clobbered and cannot be called. In addition, if the original method was itself implemented in a category, then which version is actually used is undefined. This is not the same as overriding an inherited method (thus my scare quotes).
Overriding an inherited method works as expected: a class defines a method which was already defined in one of its ancestors. When the method is called on an instance of the subclass, the redefined code is run. The class itself can invoke the non-overridden version by using the super keyword as the receiver of the appropriate message.
im trying to create a tagging solution which is a bit flexible. I have previously thought about solving it like this: Polymorphic belongsTo in many to many mapping in grails? . But as this doesn't seem to bear any fruit so I wen't ahead in another direction.
What im trying to do now is to detect wheter a domain class has a hasMany reference to the Tag class. If it does, then i try to assign method delegation to the taggableService.
All the following code is trying to do is to find the specified method and invoke it on the current object. However if it doesn't find it then try to invoke it on the delegate object instead. And if all fails, throw a MissingMethodException.
for(GrailsClass c in grailsApplication.getDomainClasses()){
Map hasMany = c.getPropertyValue('hasMany')
//continue of has a many mapping with Tag class as its endpoint
if(hasMany && hasMany.containsValue(Tag)){
//replace invokeMethod with a delegate strategy
c.clazz.metaClass.invokeMethod = { String name, args ->
def metaMethod = c.clazz.metaClass.getMetaMethod(name,args)
if(metaMethod){
return metaMethod.invoke(delegate,args);
}
metaMethod = taggableService.class.metaClass.getMetaMethod(name, args)
if(metaMethod){
return metaMethod.invoke(taggableService,args);
}
throw new MissingMethodException(name,delegate.class,args)
}
}
}
This however doesn't seem to have the desired effect. I've have gone a bit lost in groovyland, can anyone help me?
Turns out it was just the test framework who didn't handle the bootstrap correctly. if i tested it in a controller class instead. it worked fine... :(
I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!