For example I have a field that I want to access in my app view. I have this provider
class User with ChangeNotifier{
String userNick = "test";
String get getName() => userNick;
}
What will be the difference, if I access the nick this way in my app vs getter?
context.watch<User>().userNick;
vs
context.watch<User>().getName();
If I don't use the getter and my userNick changes, will I not see it refreshing in my app or?
Getters/setters are preferred for use the data properly. If you use the data directly, you can update it when you even don't wanna update it and this type of logical mistakes takes too much time to detect and fix. Also, it is safe way to manipulate the data.
Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
from: https://en.wikipedia.org/wiki/Object-oriented_programming
For more, you can search for encapsulation online.
Related
I would like to create a wrapper around a third-party package Snackbar (the third party Snackbar is simply called like this: Get.snackbar(title, body, snackPosition: SnackPosition.BOTTOM);) in order to decouple my app from the package and be able to easily swap in another Snackbar implementation.
I figure it should be a singleton for performance reasons. I would like to call it like VpSnackBar(title, body); ideally. I found how to make a singleton in dart (Vp is my app prefix to identify it was made in my app):
Here I have created this singleton
class VpSnackBar {
VpSnackBar._privateConstructor();
static final VpSnackBar instance = VpSnackBar._privateConstructor();
static void show(String title, String body) {
Get.snackbar(title, body, snackPosition: SnackPosition.BOTTOM);
}
}
I would have to call it like VpSnackBar.show(title, body);. But then I'm like should I just make a plain class with a static method which would do what this does, without ever being instantiated? Is instantiation beneficial?
Another option is a global function with an uppercase name so it is used like a class:
void VpSnackBar(String title, String body) {
Get.snackbar(title, body, snackPosition: SnackPosition.BOTTOM);
}
This is the only way that I know how to call it like VpSnackBar(title, body);. Which is my preferred way to call it. However, is a global function a bad practice? Could I achieve calling it like VpSnackBar(title, body); without a global function? Which way is the best practice?
So that I can be safe against any potential changes to the package
You won't be in any sort of way.
If the package owner decides to completely change the method internals without touching its prototype, you'll still be affected by those changes.
If the package owner decides to change the method's prototype in a backwards incompatible way, which features a breaking change, you'll also be affected by those changes.
I figure it should be a singleton for performance reasons.
I see that you're not running any heavy processes (like IO) when instantiating your class, so I cannot see why you should be concerned about performance. Consider that, for each widget build() call, which happens a lot of times in one second, hundreds of classes get instantiated, and they do not affect app's performance.
However, is a global function a bad practice?
Not at all. The actual problem with your approach is capitalizing the function's first letter. This is a bad practice, since it leaves who's reading to believe that your function call is actually a constructor call.
Which way is the best practice?
As I stated, I cannot even see a reasonable motive to wrap snackbar in the first place. But leaving this matter apart, each of your solutions seem equally fair to me (as long as you the uncapitalize the first of the function). In such situation, you may want to use the one that you feel more comfortable with.
I've been refactoring my app to make more components stateless/pure components; i.e., they're just functions. However, I noticed that some components will need to connect with the redux store via mapStateToProps. Which causes me to do something like this:
const someComp = (props) => {
const {
funcFromReduxStore,
} = props;
return (
...
<SomeComponent
func={ funcFromReduxStore(myArgs) }
...
);
};
This will not work because I am executing funcFromReduxStore. An easy solution is to wrap the prop in an arrow function. However, this causes many unnecessary re-renders b/c the function won't be bound.
The question then becomes: How do I bind a function in a stateless component?
Is it still stateless if I make it a class, without a constructor, and create a class instance field as so:
class someComp extends React.Component {
const {
funcFromReduxStore,
} = this.props,
wrapper = (x) => funcFromReduxStore(x) // equivalent way to bind w/ ES8+
render() {
...
<SomeCompnent
func={ wrapper(myArgs) }/>
...
}
}
I don't have a constructor, nor state. I want to keep the comopnent stateless, but I also want to bind the function to avoid unncessary re-renders. I also want to continue to keep it stateless b/c React has stated there will be performance benefits for stateless comopnents. Does this qualify as a workaround?
Short answer, no. Stateless functional components need to be simple functions.
You should take a look at the Recompose library for some really cool helpers that allow you to beef up your SFCs.
If you're trying to prevent unnecessary re-renders, you could look into onlyUpdateForKeys() or pure().
EDIT: So, I've been thinking about this a bit more and found this really great article on React component rendering performance. One of the key points in that article that pertains to your question:
Stateless components are internally wrapped in a class without any optimizations currently applied, according to Dan Abramov.
From a tweet in July 2016
So it appears that I was wrong. "Stateless Functional Components" are classes...for now. The confusing thing is that there have been performance improvements theorized:
In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
At this point, I think the answer to your question becomes largely subjective. When you make a class that extends a React Component, any instances of your class get the setStateprototype method. Meaning you have the ability to set state. So does that mean it's stateful even if you're not using state? Thanks to #Jordan for the link to the code. SFCs only get a render method on the prototype when they are wrapped in a class by React.
To your point about wanting to bind functions, there's only two reasons I can think of that you'd want to bind the function:
To give the function access to this (the instance of the component). From your example, it doesn't seem like you need that.
To ensure that the function passed as a prop to a child component always retains the same identity. The wrapper function in your example seems unnecessary. The identity of the function is determined by the parent component (or mapStateToProps, or whatever HOC).
You should also take a look at React's PureComponent which does the same kind of shallow checking that the pure() HOC from recompose does.
I'm looking for a way of condensing some of my AS3 code to avoid almost duplicate commands.
The issue is that I have multiple variables with almost the same name e.g. frenchLanguage, englishLanguage, germanLanguage, spanishLanguage
My Controller class contains public static variables (these are accessed across multiple classes) and I need a way to be able to call a few of these variables dynamically. If the variables are in the class you are calling them from you can do this to access them dynamically:
this["spanish"+"Language"]
In AS3 it's not possible to write something like:
Controller.this["spanish"+"Language"]
Is there any way to achieve this? Although everything is working I want to be able to keep my code as minimal as possible.
It is possible to access public static properties of a class this way (assuming the class name is Controller as in your example:
Controller['propertyName']
I'm not sure how this helps to have "minimal code", but this would be a different topic/question, which might need some more details on what you want to achive.
Having said that, I like the approach DodgerThud suggests in the comments of grouping similar values in a (dynamic) Object or Dictonary and give it a proper name.
Keep in mind, that if the string you pass in as the key to the class or dynamic object is created from (textual) user input you should have some checks for the validity of that data, otherwise your programm might crash or expose other fields to the user.
It would make sense to utilize a Dictionary object for a set of variables inherited: it provides a solid logic and it happens to work...
I do not think this is what you are trying to accomplish. I may be wrong.
Classes in AS3 are always wrapped within a package - this is true whether you have compiled from Flash, Flex, Air, or any other...
Don't let Adobe confuse you. This was only done in AS3 to use Java-Based conventions. Regardless, a loosely typed language is often misunderstood, unfortunately. So:
this["SuperObject"]["SubObject"]["ObjectsMethod"][ObjectsMethodsVariable"](args..);
... is technically reliable because the compiler avoids dot notation but at runtime it will collect a lot of unnecessary data to maintain those types of calls.
If efficiency becomes an issue..
Use:
package packages {
import flash.*.*:
class This implements ISpecialInterface {
// Data Objects and Function Model
// for This Class
}
package packages {
import...
class ISpecialInterface extends IEventDispatcher
I have been really deep thinking about a general way of creating "data model", and been jiggling with best practices and MVC pattern. Currently I am using a singleton pattern to get my httprequest and json parser (which comes as NSDictionary). Now rather than accessing this parser directly, I was hoping to make a Data model that can be binded through this.
However, I have been struggling if there is an easy way to do that rather than assigning manually "[myObj setValue:[jsonDict objectForKey:#"name"]];" where myObj tends to be a simple NSString object.
Since NSDictionary is a nice KVC concept, how can I utilize this to enrich a better style of data model in which I can generally access myObj.name or myObj.address entity than "[myObj setValue:[jsonDict objectForKey:#"name"]];" behavior.
I have looked into "Core Data" model, however the current design doesn't require to store anything locally, but just within memory for security reasons.
Any good ideas or best practices solution here will be really helpful.
Just create your classes. Then crate an class that will serialize the data from your dictionaries to your object.
Let say you create an class Person that has properties firstName and lastName. Then you crate a Class like PresonController, that will do manage the person objects, and in it create class methods like
+(Preson *)personFromDictionary:(NSDictionary)peseonDictionary;
And every time you need to create an person from an dictionary you will do
Person *newPerson = [PersonController personFromDictionary:yourPersonDictionary];
And then in the code you just access the properties of the Person object
NSLog(#"Person first name:%#",newPerson.firstName);
Hope I was clear enough for you.
Say I have a class that looks like the following:
internal class SomeClass
{
IDependency _someDependency;
...
internal string SomeFunctionality_MakesUseofIDependency()
{
...
}
}
And then I want to add functionality that is related but makes use of a different dependency to achieve its purpose. Perhaps something like the following:
internal class SomeClass
{
IDependency _someDependency;
IDependency2 _someDependency2;
...
internal string SomeFunctionality_MakesUseofIDependency()
{
...
}
internal string OtherFunctionality_MakesUseOfIDependency2()
{
...
}
}
When I write unit tests for this new functionality (or update the unit tests that I have for the existing functionality), I find myself creating a new instance of SomeClass (the SUT) whilst passing in null for the dependency that I don't need for the particular bit of functionality that I'm looking to test.
This seems like a bad smell to me but the very reason why I find myself going down this path is because I found myself creating new classes for each piece of new functionality that I was introducing. This seemed like a bad thing as well and so I started attempting to group similar functionality together.
My question: should all dependencies of a class be consumed by all its functionality i.e. if different bits of functionality use different dependencies, it is a clue that these should probably live in separate classes?
When every instance method touches every instance variable then the class is maximally cohesive. When no instance method shares an instance variable with any other, the class is minimally cohesive. While it is true that we like cohesion to be high, it's also true that the 80-20 rule applies. Getting that last little increase in cohesion may require a mamoth effort.
In general if you have methods that don't use some variables, it is a smell. But a small odor is not sufficient to completely refactor the class. It's something to be concerned about, and to keep an eye on, but I don't recommend immediate action.
Does SomeClass maintain an internal state, or is it just "assembling" various pieces of functionality? Can you rewrite it that way:
internal class SomeClass
{
...
internal string SomeFunctionality(IDependency _someDependency)
{
...
}
internal string OtherFunctionality(IDependency2 _someDependency2)
{
...
}
}
In this case, you may not break SRP if SomeFunctionality and OtherFunctionality are somehow (functionally) related which is not apparent using placeholders.
And you have the added value of being able to select the dependency to use from the client, not at creation/DI time. Maybe some tests defining use cases for those methods would help clarifying the situation: If you can write a meaningful test case where both methods are called on same object, then you don't break SRP.
As for the Facade pattern, I have seen it too many times gone wild to like it, you know, when you end up with a 50+ methods class... The question is: Why do you need it? For efficiency reasons à la old-timer EJB?
I usually group methods into classes if they use a shared piece of state that can be encapsulated in the class. Having dependencies that aren't used by all methods in a class can be a code smell but not a very strong one. I usually only split up methods from classes when the class gets too big, the class has too many dependencies or the methods don't have shared state.
My question: should all dependencies of a class be consumed by all its functionality i.e. if different bits of functionality use different dependencies, it is a clue that these should probably live in separate classes?
It is a hint, indicating that your class may be a little incoherent ("doing more than just one thing"), but like you say, if you take this too far, you end up with a new class for every piece of new functionality. So you would want to introduce facade objects to pull them together again (it seems that a facade object is exactly the opposite of this particular design rule).
You have to find a good balance that works for you (and the rest of your team).
Looks like overloading to me.
You're trying to do something and there's two ways to do it, one way or another. At the SomeClass level, I'd have one dependency to do the work, then have that single dependent class support the two (or more) ways to do the same thing, most likely with mutually exclusive input parameters.
In other words, I'd have the same code you have for SomeClass, but define it as SomeWork instead, and not include any other unrelated code.
HTH
A Facade is used when you want to hide complexity (like an interface to a legacy system) or you want to consolidate functionality while being backwards compatible from an interface perspective.
The key in your case is why you have the two different methods in the same class. Is the intent to have a class which groups together similar types of behavior even if it is implemented through unrelated code, as in aggregation. Or, are you attempting to support the same behavior but have alternative implementations depending on the specifics, which would be a hint for a inheritance/overloading type of solution.
The problem will be whether this class will continue to grow and in what direction. Two methods won't make a difference but if this repeats with more than 3, you will need to decide whether you want to declare it as a facade/adapter or that you need to create child classes for the variations.
Your suspicions are correct but the smell is just the wisp of smoke from a burning ember. You need to keep an eye on it in case it flares up and then you need to make a decision as how you want to quench the fire before it burns out of control.