binding to constant values in mvvm - mvvm

i have constant values (certain limits) i work with in the viewmodel but i need it in my view as well. what is the best way to do that?
constant:
private const int maxLevel = 4;
do i really need to make a property for each constant and bind to it like that:
private const int _maxLevel = 4;
public int MaxLevel
{
get { return _maxLevel; }
set
{
RaisePropertyChanged("MaxLevel");
}
}
maybe i could store all those values in a *.resx file like i do it with strings? what is the best practice here?

You can do:
namespace Foo.ViewModels
{
public class MainWindowViewModel{
public const int MaxLevel = 4;
...
}
}
and use it in the view:
<Label Content="{x:Static Foo.ViewModels:MainWindowViewModel.MaxLevel}"></Label>
Or generally speaking, bind to:
"{x:Static MyNameSpace:MyClass.MY_CONSTANT}"

Lose the setter. Property change notification is only needed to inform binding elements that the value has changed. Since MaxLevel is a constant its value never changes, thus you don't need it. You can't bind directly to a constant because in practice the compiler embeds the value into the code that accesses it at compile time, so for constant properties that are unlikely to need future modification I usually just do something like this:
public int MaxLevel { get {return 4;} }

Related

What does the 'get' keyword do in a dart class? [duplicate]

I am struggling with the concept of getters and setters in Dart, and the more I read, the more I cannot grasp the underlying purpose. Take for example the following code:
main() {
Car car = new Car();
car.doors = 44;
print(car.doors); // 44
}
class Car {
int doors = 4;
}
Later, I decide to make “doors” a private variable, so I do the following:
main() {
Car car = new Car();
car.doors = 44;
print(car.doors); // 44
}
class Car {
int _doors = 4;
int get doors => _doors;
set doors(int numberOfDoors) => _doors = numberOfDoors;
}
According to the code, _doors is now a private variable, and so I cannot access it in main(). However, by manipulating doors, I can indirectly change the value of _doors, which is what I thought I wanted to prevent in the first place by making it a private variable. So what is the purpose of making a previously public variable into a private one, if you can still indirectly manipulate it? And, how are getters and setters even working to change the properties of these variables? I am trying to understand the fundamental concept, because without that, I don't understand how or why getters and setters are used.
Instance variables in Dart have implicit getters and setters. So for your example code, it will operate in exactly the same way, since all you have done is changed from an implicit getter and setter to an explicit getter and setter.
The value of explicit getters and setters is that you don't need to define both if you don't want. For instance we can change your example to only define a getter:
main() {
Car car = new Car();
print(car.doors); // 4
car.doors = 6; // Won't work since no doors setter is defined
}
class Car {
int _doors = 4;
int get doors => _doors;
}
Additionally, you can also add extra logic in a getter or setter that you don't get in an implicit getter or setter:
class Car {
int _doors = 4;
int get doors => _doors;
set doors(int numberOfDoors) {
if(numberOfDoors >= 2 && numberOfDoors <= 6) {
_doors = numberOfDoors;
}
}
}
The getter and setter functions allow us to make the class appear to have a property, without a explicit property being declared (_doors in your case). The property value may be calculated from other properties.
The getters and setters allow us to execute arbitrary code when the property is get or set.
Omitting a setter makes the property immutable.
An abstract class may declare getters and setters without bodies as part of a required class interface.

How to make a class-wide ID number

Perhaps I am simply reading old material, but I can't see a way to do something seemingly very simple.
I have a class called Robot, each instance of which needs a unique id. The id is simply an Int that should be 1,2,3... The normal solution would be to have a class var MaxId that you increment in the init() and then assign that to the instance's id.
Swift (4?) does not have class vars, but does have computed properties at the class level. However, I am a bit mystified about how one might use this to do a MaxId. Am I missing something blindingly obvious here?
a unique id. The id is simply an Int that should be 1,2,3.
You can certainly use a static property and increment it, but note that
those are two different requirements. If all you really want is a unique id, there is no need for the “least available integer” approach. Just use the built-in UUID struct and move on.
Static variables are essentially class variables. Try this in a playground:
class Numbered {
static var serial: Int = 1
let myID: Int
init() {
myID = Numbered.serial
Numbered.serial = Numbered.serial + 1
}
}
print(Numbered().myID)
print(Numbered().myID)

What Is the Proper Way to Handle Calculated Properties in an Object?

From what I can tell, there are two main ways to accomplish this:
Option 1: Calculate each property "on demand" via their getter method (e.g.
getTotal()).
Option 2: Populate all calculated properties on construction and any time a public property changes by using a
generic calculate() method.
I created two examples using a simple insurance policy object. Each class initializes with a few properties like premiumRateBase, brokerFee, termYears, effectiveDate, and agentCommissionRate. The calculated columns would be things like the prorated premiumRate, total, or agentCommission.
Here's an example of option 1:
component {
// public properties (getters + setters)
property name="premiumRateBase";
property name="brokerFee";
property name="effectiveDate";
property name="termYears";
property name="agentCommissionRate";
function init(
required numeric premiumRateBase,
required numeric brokerFee,
required date effectiveDate,
required numeric termYears,
required numeric agentCommissionRate
) {
// setters
...
return this;
}
function getExpirationDate() {
return dateAdd( 'yyyy', effectiveDate, termYears );
}
function getPremiumRate() {
// run proration and calcuation determination
// based on premiumRateBase, getExpirationDate(), and maybe a few other methods
...
return premiumRate;
}
function getTotal() {
return getPremiumRate() + brokerFee;
}
function getAgentCommission() {
return getPremiumRate() * agentCommissionRate
}
function getAgentCompensation() {
return getAgentCommission() + brokerFee
}
}
In the above example, the calculations are run any time you call a method like getTotal(). The advantage of this approach is that the code is pretty straightforward. The disadvantage of this approach is that if needed to run getTotal(), getAgentCommission() and then getAgentCompensation(), you wind up running a lot of redundant math. For this example, it wouldn't equate to much additional processing time, but in a more complex example, I could see this adding up.
Here's an example of option 2:
component {
// public properties (getters + setters)
property name="premiumRateBase";
property name="brokerFee";
property name="effectiveDate";
property name="termYears";
property name="agentCommissionRate";
function init(
required numeric premiumRateBase,
required numeric brokerFee,
required date effectiveDate,
required numeric termYears,
required numeric agentCommissionRate
) {
// setters
...
// run the calculation
calculate();
return this;
}
// primary calculation method which sets all private properties
function calculate() {
variables.expirationDate = calculateExpirationDate();
variables.premiumRate = calculatePremiumRate();
variables.total = calculateTotal();
variables.agentCommission = calculateAgentCommission();
}
/***************************
Public Getters
***************************/
function getExpirationDate() {
return expirationDate;
}
function getPremiumRate() {
return premiumRate;
}
function getTotal() {
return total;
}
function getAgentCommission() {
return agentCommission;
}
/***************************
Private Calculations
***************************/
private function calculateExpirationDate() {
return dateAdd( 'yyyy', effectiveDate, termYears );
}
private function calculatePremiumRate() {
// run proration and calcuation determination
// based on premiumRateBase, expirationDate and maybe a few other variables
...
return premiumRate;
}
private function calculateTotal() {
return premiumRate + brokerFee;
}
private function calculateAgentCommission() {
return premiumRate * agentCommissionRate;
}
private function calculateAgentCompensation() {
return agentCommission + brokerFee;
}
}
In the second example, we only run a generic calculate() method after the constructor method init() fires. I didn't include this, but you would also need to run calculate() again if you ever update any of the public properties through their setter methods. The advantage of this approach is that the calculation math only occurs when the properties change. The downside is that the code seems a little more convoluted and harder to read.
What is the best-practices or proper approach to solving this type of problem?
It is a common dilemma and ultimately it resolves to the cost of recalculating the property every time. If it is cheap, I would always prefer getter approach.
Another dimension to think about is staleness of calculated property. Option #2 performs calculation only upon initialisation and possibly the properties involved in calculation may change afterwards. The calculated metric will be stale now. You can fix it by recalculating metrics on modification. This will further increase the complexity of code. If this modification isn't well encapsulated, recalculation responsibility will be shared with caller too!
In summary, for cheap calculations I would prefer option #1 and for complex calculations, I would first encapsulate modifications to ensure recalculation on each update.

How should the enum type look like in the bottom part of a UML diagram?

I know what the enum type should look like in the middle section of a UML diagram but how should it look in the bottom section where it contains the actions/methods of the class? Isn't there accessors and mutators for enum types?
+GetTypeOfAttack:TypeOfAttack
Is probably the answer but you need to ask yourself a question about whether this is a 'classic' accessor mutator
A classic accessor/mutator (getter/setter) is usually like the following
private bool hiddenField = true;
//Accessor
public bool GetHiddenField()
{
return hiddenField;
}
//mutator
public void SetHiddenField(bool input)
{
hiddenField = input;
}
BUT you may (more often than not) have situations where you need to do some logic evaluation before either getting or setting the field... This is not a pure accessor/mutator but essentially it is.
In answer to your question:
+SetHiddenField(bool): void
+GetHiddenField:bool
See how they map to the previous code. +/- = public/private, (denoteParameters) and : denotes return type

Finding a on object in a vector by one of its values

The problem I encountered and am unable to solve goes something like this. I have two classes:
class1
{
private:
int identifier;
double value;
public:
setters,getters,etc...
}
class2
{
private:
vector<class1> objects;
vector<int> some_value;
vector<double> other_value;
...
}
The problem is I need to search through the vector of objects in an object of the second class by its identifier in the class1 object(from a member function of class2). I tried something like:
int getObj(const int &ident, double &returnedValue, double &returnedOther_value)
{
int p;
p = find(objects.begin()->getIdentifier(),objects.end()->getIdentifier(),ident);
..
.. and then i was hoping to find a way to return from the found iterator values of corresponding(non-const) member variables value and other_value from both classes, but the code so far does not compile, because I'm likely doing the search all wrong. Is there a way I could do this with the find(or any other algorithm) or should I stick to my previous working realization with no algorithms?
You need to use find_if with a custom predicate. Something like:
class HasIdentifier:public unary_function<class1, bool>
{
public:
HasIdentifier(int id) : m_id(id) { }
bool operator()(const class1& c)const
{
return (c.getIdentifier() == m_id);
}
private:
int m_id;
};
// Then, to find it:
vector<class1>::iterator itElem = find_if(objects.begin(), objects.end(), HasIdentifier(ident));
I haven't tested it, so maybe it needs some tweaking.
If you have C11, I guess you can use lambdas, but I don't have it, so I haven't had the chance to learn them.
UPDATE:
I've added an example in http://ideone.com/D1DWU