Where should I put util functions - OOP best practices - oop

I wonder, where general (or util functions) should be placed?
For example:
public class Credit {
private Integer _duration;
private Double _interestRate;
private Integer _creditSum;
private PaymentStream _paymentStream;
private Date _openDate;
}
PaymentStream impements strategy pattern for gettin paymentList.
Question:
I have a construnctor (duration, interestRate, creditSum, paymentStream, openDate). But I also want followin functions:
getCreditDuration(creditSum, monthlyPayments, interestRate)
getCreditSum(montlyPayment, interestRate, duration)
etc
Obviously, they can't be on credit instance, as I don't have enough info for a constructor. So where they should be placed?
Added: I've also need to store all the calculations (getCreditDuration, etc) into db. So, if this is static functions returning double(int) I can't image of a good way to store them into DB. What object should I save?
Requirments are: user can choose between Duration calculation and Credit sum calculation (and etc.) There are separate views for calculations. Every time user click "Calculate button" calculation result must be persisted into DB. User can has a view with all calculation, where he can click any item.
For ex (с means value is calculated):
Sum Duration Interest Payment
10000 2 yrs 12% 1000(с) -> opens view to calculate monthly payment
12000(с) 3 yrs 10% 1200 -> opens view to calculate credit sum

They are stateless methods (all data they work on is passed as a parameter) whose logic is clearly tied the concepts of the Credit object. So one possibility is just to make them static methods of the Credit class.

Related

AURELIA - Computed fields

I have an issue with computed fields in aurelia framework...
Background:
eg: we have tree structure of classes (3 levels) for better expression we have HouseOfFlats, Floors and Flats. All classes are json array, every class has some properties as Price.
And what I need:
I need to create class 'Compute' which encapsulate the observe of the fields and the class input will be function like
this.Price = ko.computed(function() {
return self.Quantity() * $Flat.PricePerBoxStatic();
});
Meaning, 1 house of flats, 3 floors, 5 flats on each floor. And when I change the price on flat I need to compute the price of all falts on the floor and the price of whole houseofflats. So the prices will be recalculated in whole tree immediately the price of flat has changed.
Thank you all for any idea how to solve this with some smart solution.
picture for better understanding:
so let's say total is what you are looking for.
in your view model:
get total(): number {
// put here your calculation logic and return your total
}
in your view, simply use string interpolation:
<p>${total}</p>
whenever any of the variables that participate in the calculation of total change its values - the total will be recalculated and you will see the updated value in the view.

iPhone Card Game Deck Generator

I am trying to program an iPhone App that will create a card set of 10 cards.
The total deck includes about 100 cards with different properties:
Each card has a name, a suit and a cost.
For an example:
card.name = "Test"
card.cost = 2
card.suit = "BasicSet"
Let's suppose there are 4 "Sets"* with 20 cards each.
I want the user to be able to select the suit themselves, because most of the suits come from extension sets.
To make it more balanced, I will also decide a maximum and minimum amount of cards with a specific cost (the cost ranging from 2 - 6).
In the end, there will be 2 functions. One function that selects all valid cards (from the available card suits) and another that picks 10 cards at random (taking into account the cost).
What is the easiest way to implement the cards? Defining the class card and implementing the 100 cards? Or creating 3 arrays with name, cost and origin where one card has the same index in all 3 arrays?
Help would be appreciated?
EDIT:
Each Suit contains unique cards. So if my suits are diamond, spade and so on, there will only be a diamond king, but no spade king.
Just an example how it could look like:
Suit Basic {
name=Village, cost=2
name=City, cost=3
name=NewYork, cost=6
}
Suit Advanced {
name=Tree, cost=4
name=Forest, cost=5
}
Suit Special {
name=Cocktail, cost=2
name=OrangeJuice, cost=4
}
One class Card could store all necessary information and functions for basic operations. When Card class is ready, you could create objects of that class with your data parsed from plist or any other format. It's not really necessary to hardcode your data inside the app.

How to Structure Lists

I am working on a vb.net auto-focus routine and have the image processing part worked out, basically I do some edge detection, convert to gray-scale and then measure the standard deviation to work out the most 'in focus' point of the image.
I have done this with a number of images, and it almost comes out as a normal distribution, now I want to start to integrate this with my microscope and a stepper motor.
The concept is that I would move through a lower and upper limit on the stepper motor, and measure the above through live-view, recording the values in a list. In my case the two things I want to record are the position, and the double standard deviation value.
I am wondering what the best way to record these are, should it be
recorded as a typed list, or a dictionary or another method?
Once I record all of these values, I would want to go through the values to conduct some simple analysis of them, so if that was the case
how would I then be able to determine the average, min, max etc?
My first attempt of storing the information was in a typed list, where I had essentially done the below;
Public ZPositions As New List(Of Zfocus)
Public Class Zfocus
Public Position As Integer
Public GreyStDev As Double
End Class
The second way was to use a dictionary;
Public ZPosition As New Dictionary(Of Integer, Double)
However in both cases, I am not sure how I can either pull out a single maximum position value (e.g. Position integer,) or from the dictionary the position value (integer) which (sort of) corrosponds to the best auto-focus position.
The Third added bonus, is to be able to pull out any postions above a
specific value, which may corrospond to having some focus information
within them for focus stacking?
Many thanks
Big thanks to jmcilhinney, this solved my issue and works a treat!
Went with a strongly typed list (the ZFocus list) and then I could do the below;
MaxPosition = ZPositions.First(Function(zp1) zp1.GreyStDev = ZPositions.Max(Function(zp2) zp2.GreyStDev))
This allowed be to set up an auto-focus routine which loops through a number of images (as a test), stores the position (e.g. image number in this case) and the intensity edge information, and at the end then pull out the strongest intensity information which forms the best auto-focus point in my case

Defining the structure of hierarchical data versus actually storing the data

I'm trying to develop a survey application that can deal with various types of responses, such as boolean, multiple choice, as well as ranges from 1-5, 1-10, 1-100, -2 to +2, even decimal values. So, I've created a hierarchy of Response types:
class Response {
String name
}
class BooleanResponse extends Response {
boolean score
}
class SimpleGradeResponse extends Response {
char score // A-F
}
class ComplexGradeResponse extends Response {
char score // A-F
char modifier // +, -, blank
}
class IntegerResponse extends Response {
int min, max, score
}
class DecimalResponse extends Response {
double min, max, score
}
I think of that as the metadata. It describes the survey response types. You could have question 1 that's an IntegerResponse from 1 to 10, question 2 that's an IntegerResponse from 0-100, question 3 that's a DecimalResponse, etc.
Where I'm uncertain is where to store the actual responses from users. Do you mingle the scores in with the metadata, as I've done with the score field above? That seems awkward, since every range-type response carries with it the min and max.
What I really want (I think) is to be able to curry the range response parameters to create a new type, and then reflect that type in a table of actual responses. So, a question that takes a 1-10 range would be a row in IntegerResponse with min=1 and max=10. But how does the ActualResponse table (I need to improve the naming convention, once I figure this out!) hold a score and refer to the curried IntegerResponse with min and max set?
If there is a better way to approach this whole problem, I'm eager to hear it.
Thanks,
Lee
min and max should rather be stored in a Question object, or even in QuestionType - depending on how flexible the system should be in runtime.
Will there be arbitrary limitations to different kinds of Responses? Data structure hugely depends on it. You can either hardcode different Response types or support them in runtime. First approach is one order of magnitude simpler.

Game Design: Data structures for Stackable Attributes (DFP, HP, MP, etc) in an RPG (VB.Net)

I'm wrangling with issues regarding how character equipment and attributes are stored within my game.
My characters and equippable items have 22 different total attributes (HP, MP, ATP, DFP). A character has their base-statistics and can equip up to four items at one time.
For example:
BASE ATP: 55
WEAPON ATP: 45
ARMOR1 ATP: -10
ARMOR2 ATP: -5
ARMOR3 ATP: 3
Final character ATP in this case would be 88.
I'm looking for a way to implement this in my code. Well, I already have this implemented but it isn't elegant. Right now, I have ClassA that stores these attributes in an array. Then, I have ClassB that takes five ClassA and will add up the values and return the final attribute.
However, I need to emphasize that this isn't an elegant solution.
There has to be some better way to access and manipulate these attributes, including data structures that I haven't thought of using. Any suggestions?
EDIT: I should note that there are some restrictions on these attributes that I need to be put in place. E.g., these are the baselines.
For instance, the character's own HP and MP cannot be more than the baseline and cannot be less than 0, whereas the ATP and MST can be. I also currently cannot enforce these constraints without hacking what I currently have :(
Make an enum called CharacterAttributes to hold each of STR, DEX, etc.
Make an Equipment class to represent any equippable item. This class will have a Dictionary which is a list of any stats modified by this equipment. For a sword that gives +10 damage, use Dictionary[CharacterAttributes.Damage] = 10. Magic items might influence more than one stat, so just add as many entries as you like.
The equipment class might also have an enum representing which inventory it slots to (Boots, Weapon, Helm).
Your Character class will have a List to represent current gear. It will also have a dictionary of CharacterAttributes just like the equipment class, which represents the character's base stats.
To calculate final stats, make a method in your Character class something like this:
int GetFinalAttribute(CharacterAttributes attribute)
{
int x = baseStats[attribute];
foreach (Equipment e in equipment)
{
if (e.StatModifiers[attribute] != null)
{
x += e.StatModifiers[attribute];
}
}
// do bounds checking here, e.g. ensure non-negative numbers, max and min
return x;
}
I know this is C# and your post was tagged VB.NET, but it should be easy to understand the method. I haven't tested this code so apologies if there's a syntax error or something.