One model response for different models - oop

I am trying to cast/map an API endpoint response to APIResponse.groovy. This can simply be done if I have an APIResponse model like
APIResponse.groovy
Integer age
String gender
Integer zip
Education education
String marital_status
Boolean magazine_buyer
Boolean outdoor_and_adventure
I want to group them as Demographics, Household and InterestPurchase. Like..
Demographics.groovy
Integer age
String gender
Integer zip
...
Household.groovy
Education education
Integer household_income
...
InterestPurchase.groovy
Boolean magazine_buyer
Boolean outdoor_and_adventure
...
I thought of something like
APIResponse.groovy
inteface APIResponse implements Household, Demographics, InterestPurchase{
}
but of course, this would not work since members of an interface is final and static..

I am not sure what approach you are using to cast/map api response to APIResponse.groovy. If you can provide more on this, may be I can help in a better way.
Here are some approaches you can try:
Map Demographics.groovy, Household.groovy and InterestPurchase.groovy with api response individually and then map these with APIResponse.groovy.
If its not required to make APIResponse.groovy interface, then you can make Demographics.groovy, Household.groovy and InterestPurchase.groovy abstract class.
If you want to go with interface approach, then don't declare the fields, just make getter and setter methods for these variables in their respective interface.

Related

What type of array should I use for a database of information about the user? vb.net

So I'm trying to make a system where a person can input data about different people and I want to store it in a textile to search and sort the data, It would contain first name, surname, location, phone number.
If I were to use a 2d array how would I go about inputting the data through a loop instead of just writing it out myself.
Or I could use one dimensional arrays and store each type of data, first name, surname etc in separate text files but I am not sure if that would work/be efficient.
If you stored the data as JSON, it would be easier to maintain.
You would create a class to represent the data, read in the file, parse the contents to a collection of your class, and then use LINQ to do your filtering.
This would be efficient enough if you aren't doing any inserts/updates, in which case I would recommend moving to a database to handle these. You could still use the same approach and just serialize the JSON collection back to the file, but you would start to see some significant slow down of the write operation pretty quickly.
Here is an example of defining the class:
Public Class Person
<JsonProperty("firstName")>
Public Property FirstName As String
<JsonProperty("surname")>
Public Property Surname As String
<JsonProperty("location")>
Public Property Location As String
<JsonProperty("phoneNumber")>
Public Property PhoneNumber As String
End Class
Here is an example of reading a text file and parsing it to a collection of your class:
Public Function GetPeople(path As String) As IEnumerable(Of Person)
Dim literal = IO.File.ReadAllText(path)
Dim people = JsonConverter.DeserializeObject(Of IEnumerable(Of Person))(literal)
Return people
End Function
Here is an example of adding people to the collection and serializing it back to the file:
Public Function AddPerson(path As String, record As Person) As IEnumerable(Of Person)
Dim people = GetPeople(path).ToList()
people.Add(record)
IO.File.WriteAllText(path, people.ToString())
Return people
End Function
Keep in mind you'd want to add exception handling and business logic to check that the state is what you would expect it to be.

How do you create a class without knowing how many variables you will need for that class?

I was wondering how you would go about creating a class to store strings and integers without knowing how many strings or integer you will have. For example lets say I make a class call Person.
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property Gender As String
End Class
Now, to create a new person and give them their details I would do:
Dim Human As New Person With {.Name = "Bob", .Age=20, .Gender="Male"}
Well what if Bob has more information than just his Name, Age, and Gender? What if Bob also has a Height of 6ft and a Weight of 200lbs? How would I include this information in my Person class once its already been created?
What is this problem even called in the programming world?
The problem is called the open closed principle.
The solution depends on how bedded you are to it/SOLID principles. Things that spring to mind:
Simply adding the fields at a later date (this will violate the open
closed principle)
Extending the class (a new type of person with those new properties
for example)
The problem with the former (and a reason for OCP) is that it could have dependency implications for not only yourself but others. For example if you add property Age and start writing functionality that uses it what happens when you have a process that needs Age and you haven't set it.

Everything a Value Object in DDD

I just read about Value Objects, being immutable and described as:
A small simple object, like money or a date range, whose equality isn't based on identity.
Looking at my currently existing entities I figured I could make pretty much everything that's not an entity a value object.
Let's say I have an entity class User.
class User
{
public $id;
public $firstname;
public $lastname;
public $email;
}
I could make it consist of the value objects Id, FirstName, LastName, Email and Password, because none of these User attributes equality are based on identity, right? But then again I could probably go even further and make more VOs Int, String, Name (which consists of FirstName and LastName VOs), etc.
Where do I draw he line to prevent over-engineering?
Is it normal for a domain to contain that many VOs?
Is my understanding of value objects even right?
Yes, it is normal for a domain to contain lots of VO's if you want to set the bar of type safety and expressivity high enough -- which is generally a good thing.
No need to redefine Int and String, but identified ubiquitous language concepts should definitely have their own objects.
Admittedly, doing so is much more natural and painless in some languages than others. This can influence where you draw the line. In functional languages, for instance, it is not uncommon to wrap primitive types as in type UserId = UserId of int. Which I wouldn't bother doing in an OO language, class ceremony being what it is.

How to structure object: OOP, composition

I have an object, let's call it a Request, that has associations to several other objects like:
Employee submitter;
Employee subjectsManager;
Employee pointOfContact;
And several value properties like strings, dates, and enums.
Now, I also need to keep track of another object, the subject, but this can be one of 3 different types of people. For simplicity let's just talk about 2 types: Employee and Consultant. Their data comes from different repositories and they have different sets of fields, some overlapping. So say an employee has a
String employeeName;
String employeeId;
String socialSecurityNumber;
Whereas a consultant has
String consultantName;
String socialSecurityNumber;
String phoneNumber;
One terrible idea is that the Request has both a Consultant and an Employee, and setSubject(Consultant) assigns one, setSubject(Employee) assigns the other. This sounds awful. One of my primary goals is to avoid "if the subject is this type then do this..." logic.
My thought is that perhaps an EmployeeRequest and a ConsultantRequest should extend Request, but I'm not sure how, say, setSubject would work. I would want it to be an abstract method in the base class but I don't know what the signature would be since I don't know what type the parameter would be.
So then it makes sense to go at it from an interface perspective. One important interface is that these Request objects will be passed to a single webservice that I don't own. I will have to map the object's fields in a somewhat complex manner that partially makes sense. For fields like name and SSN the mapping is straightforward, but many of the fields that don't line up across all types of people are dumped into a concatenated string AdditionalInfo field (wump wump). So they'll all have a getAdditionalInfo method, a getName, etc, and if there's any fields that don't line up they can do something special with that one.
So that makes me feel like the Request itself should not necessarily be subclassed but could contain a reference to an ISubjectable (or whatever) that implements the interface needed to get the values to send across the webservice. This sounds pretty decent and prevents a lot of "if the subject is an employee then do this..."
However, I would still at times need to access the additional fields that only a certain type of subject has, for example on a display or edit page, so that brings me right back to "if subject is instance of an employee then go to the edit employee page..." This may be unavoidable though and if so I'm ok with that.
Just for completeness I'll mention the "union of all possible fields" approach -- don't think I'd care to do that one either.
Is the interface approach the most sensible or am I going about it wrong? Thanks.
A generic solution comes to mind; that is, if the language you're using supports it:
class Request<T extends Subject> {
private T subject;
public void setSubject(T subject) {
this.subject = subject;
}
public T getSubject() {
return subject;
}
}
class EmployeeRequest extends Request<Employee> {
// ...
}
class ConsultantRequest extends Request<Consultant> {
// ...
}
You could similarly make the setSubject method abstract as you've described in your post, and then have separate implementations of it in your subclasses. Or you may not even need to subclass the Request class:
Request<Employee> employeeRequest = new Request<>();
employeeRequest.setSubject(/* ... */);
// ...
int employeeId = employeeRequest.getSubject().getEmployeeId();

Data Transfer Objects return values

Should Data Transfer Objects always be used to transfer data? Please see the code below:
public function getPerson(ByVal id As integer) As Person
return Person
end function
public function getPersonAge(ByVal id As integer) As Integer
return age
end function
The first function returns every piece of information for the person and can probably be reused again and again, when getting information e.g. address about the person in other parts of the application. getPersonAge is slightly faster.
Please be more clear. But if your question is solely "Should DTOs only be used to transfer data" the answer is yes.
A good use of DTOs is keeping in mind that they are only a bunch of getters/setters/properties like: public int MyProperty { get; set; }.
In MVC you can see them as ViewModels but then not for views, but for the several layers in your application.