Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
So i am creating a program that collects alot of different data from the database and creats / updates several charts for the end user to see.
Now at some level all of the data follows the same pattern:
Every data has a date attached to it this date is used to display the X Cordinate on the chart
Every data has a so called queue (which is simply a name)**
Now what i have done so far is to create a super class (abstract class). My idea was to create individual sub classes of this super class and allow them to have their own implementation and fields.
Now to my question some of these objects will be relativly small for example i have an object that only consists of three fields with getter and setter. Is best pratice to devide and conquere or have as few objects as possible?
The alternative to having small objects is that a larger object that in short are talking the same type of object but half of them has a field that the other half does not I.E why i wanted to split it into two objects to avoid having a field that will be null 50% of the times.
Here is an example of how my objects look:
Example on subclass
class Callback : ContactQueue
{
public int completedCallbacks{get; set;}
public int completed_within_timeframe{get; set;}
public int answerPercentage { get; set; }
public override String type {get; set;}
public override DateTime period { get; set; }
public Callback(String type,DateTime period)
{
this.type = type;
this.period = period;
}
public override String toString()
{
return type;
}
public double percentageCompleted {
get
{
return completed_within_timeframe / completedCallbacks * 100; // todo
}
}
}
I hope you can understand my question if not please leave a comment and i will respond as soon as possible
It really depends on your system. If you want to have a storage for your fields then you can have one object with many getters/setters.
But I would recommend splitting them by behaviour. You might want to add methods to your objects and there will be differences in behaviour you'll want to have. And at this point if you had gone with the first way, you'll have to make a lot of checks inside these methods to correctly execute it. You need to separate objects to scale easier.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have an application that runs several asynchronous methods to create messages that are sent with a unique id to a remote host.
Two types of messages are being created in two separate classes. One class is inherited from the other but the shared methods are shadowed meaning they are different.
I would like the ID to be an incremented integer.
Does anyone have a good way of accomplishing this task? I have looked up the use of static numbers and class generated ids but they don't cover the shared method issue.
I am also aware of a single shared method being able to use a static number but that doesn't help when my method is shadowed.
You'll need some single-instance way of doing this.
VB.NET natural way would be using Module:
Module IDHelper
Private fLastID As Integer
Public Function NextMessageID() As Integer
Return Threading.Interlocked.Increment(fLastID)
End Function
End Module
Nice way of doing this is using singleton. Or somehing like that. But your original idea with shared member works as well. Problem could be in missing synchronization.
Public Class Base
Private Shared fLastID As Integer
Protected Function NextMessageID() As Integer
Return Threading.Interlocked.Increment(fLastID)
End Function
Public Function CreateMessage() As String
Return "Base message is " & NextMessageID()
End Function
End Class
Public Class Inherited
Inherits Base
Public Shadows Function CreateMessage() As String
Return "Inherited message is " & NextMessageID()
End Function
End Class
Shadowing functions is almost never a good idea. Overriding is the good way to go.
I figured it out. I needed the ID to also be shared so it would share across all classes too instead of my two methods generating the ID independently and being aware of the others current ID number.
Code
Public Property MessageID As Long
Private Shared NextID As Long = 0
Public Shared Function GenerateNextID() As Long
NextID += 1
Return NextID
End Function
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've seen different ways of loading an object to and fro a database, with two common ones as shown below. Which one is better, and why?
Method 1: This includes defining two member methods for a class, load(id) and save(). These methods are called on instances of the class. For example,
class Wheel{
double diameter;
string tag;
public void Load(int id){
var result = ... // database query
this.diameter = result['diameter'];
this.tag = result['tag'];
}
public void Save(){
... // database query to update row
}
}
Wheel johnWheel = new Wheel();
johnWheel.Load(5); // In this case John's wheel has a row id of 5 in the database
Method 2: A utility method which loads/saves an object directly:
class DBUtils{
public static Wheel LoadWheel(int id){
var result = ... // database query
Wheel w = new Wheel();
w.setDiameter(result['diameter']);
w.setTag(result['tag']);
}
public static void SaveWheel(Wheel wheel){
...// Update DB
}
}
I ask because the notion of a 'wheel' itself does not include functions which loads and saves it from a database, so perhaps method 1 would be considered bad OOP design.
Both seem a bit off...
Method 1
For one thing, Load() should be a static factory in this case. This usage is a bit obtuse:
Wheel johnWheel = new Wheel();
johnWheel.Load(5);
Between those two lines of code, what is johnWheel? Is it in anything approaching a valid state? If not, then it seems like its construction is a little broken. OO principles would suggest encapsulating that into a single operation rather than expecting consuming code to perform multiple sequential operations every time. If it's a static factory, the usage is simpler:
Wheel johnWheel = Wheel.Load(5);
Method 2
This one is more of a naming concern than a structure concern. DBUtils? That's going to turn into a dumping ground for unrelated functionality quickly. You want to avoid that. How about something like this?:
class WheelRepository
{
public static Wheel Get(int id)
{
// ...
}
public static void Save(Wheel wheel)
{
// ....
}
}
As an object (this is still OOP after all), a WheelRepository represents (and therefore encapsulates) very specific functionality whereas a DBUtils doesn't.
Conclusion
I generally prefer method 2 in a structural sense, because the business object (Wheel) shouldn't know anything about the database (WheelRepository). The former is a core portable business concern, the latter is a periphery infrastructure concern. My only caveat is that I'd recommend standard patterns for improving method 2, such as a combination of the Repository Pattern and the Unit Of Work pattern, for example.
You should create a separate class that handles database connections and the creation/destruction of these connections. That way, the wheel is a separate entity from the database it is using.
Go with method 2.
I would go with Method 2 (like laiello proposed). I would however not name the class DbUtils but more something like WheelDao or WheelRepository (if for instance your Wheel class is an Root entity in your domain model).
If however you go with Method 1 the load(id) method should be static. Since it is not called on a particular instance of an object but it rather produces a new instance of an object. This is unlike the save() method for which it is correct to be called on a specific instance of Wheel.
Here briefly are the business requirements.
I have an entity called PricingSchedule that represents a "subscription" to a system. We use the term "Pricing Schedule", not "subscription" in our team's ubiquitous language, but in theory, a subscription is the same thing.
What determines the Price of the PricingSchedule is the combination of two things:
1. the "duration" of the PricingSchedule (aka, how long is your subscription... 1 year, 2 years, etc...
2. how many Styles (another entity) you want to include in your PricingSchedule. You have two options for how to include Styles; 1. pay per Style, 2. pay for all Styles
Number two is a newly added requirement. Before, it was primarily the PricingSchedule's Duration that determined the Price.
My problem is this... the Price of a PricingSchedule doesn't mean anything when either the Duration, or StylePricingType is applied by itself. I can only get the final Price when they're combined together; aka, 2 years duration with 5 styles.
We have four possible pre-determined durations, ranging from a couple of days, to a 3 or 4 years.
We have two possible ways to bill Style selection; 1. per Style or 2. all Styles. These two things combined then determined the overall Price.
I started thinking the Strategy design pattern could help me here, aka;
public interface IDurationPricingStrategy
public decimal GetDurationPriceFor(PricingSchedule)
public interface IStylePricingStrategy
public decimal GetStylePriceFor(PricingSchedule)
This is a good way to separate things that probably will change going forward, but herein lies the rub; I can't implement one Strategy without knowing the other Strategy's "conditionals."
For example, for the IStylePricingStrategy, I implement the unlimited style pricing option like so:
public class UnlimitedStylePricingStrategy : IStylePricingStrategy
{
public decimal GetStylePriceFor(PricingSchedule)
{
if (PricingSchedule.Duration.Type == DurationType.OneYear)
{
return decimal x;
}
if (PricingSchedule.Duration.Type == DurationType.TwoYears)
{
return decimal x;
}
}
}
if I take this approach, that means if and when I have to add or change a Duration pricing type, then I have to change my StyleStrategy implementation class, which breaks SRP, and basically puts me back to square one.
It's easy if there is only one "thing" that determines the Price for the PricingSchedule, but when I have two things like this, that's where I'm hitting a wall.
Is there another pattern I can use, or somehow use the Strategy pattern differently? I feel that the problem still pulls me towards Strategy, but I'm not sure how to incorporate two Strategies instead of one.
Thanks so much!
Mike
I think one way might be to create an interface for the duration:
public interface IDuration
{
int GetDuration();
decimal CalculatePrice(object whatever); // int something, or whatever.
}
The have your schedule class use it:
public class PricingSchedule
{
public IDuration Duration { get; set; }
}
Then your payment style classes could use the duration like so:
public class UnlimitedStylePricingStyle : PricingStyle
{
public override void GetStylePriceFor(PricingSchedule schedule)
{
int duration = schedule.Duration.GetDuration();
//.....
}
}
The tricky one is days, I'm not sure how you would deal with that, but I would think that using an interface is your best bet here. If you need to add a new duration, you simply implement the interface IDuration.
You could then calculate the price by something like:
public override void GetStylePriceFor(PricingSchedule schedule)
{
int duration = schedule.Duration.GetDuration();
int temp = 34;
decimal result = schedule.Duration.CalculatePrice(temp);
}
Hope this give you a rough idea.
This is quite a common problem I run into. Let's hear your solutions. I'm going to use an Employee-managing application as an example:-
We've got some entity classes, some of which implement a particular interface.
public interface IEmployee { ... }
public interface IRecievesBonus { int Amount { get; } }
public class Manager : IEmployee, IRecievesBonus { ... }
public class Grunt : IEmployee /* This company sucks! */ { ... }
We've got a collection of Employees that we can iterate over. We need to grab all the objects that implement IRecievesBonus and pay the bonus.
The naive implementation goes something along the lines of:-
foreach(Employee employee in employees)
{
IRecievesBonus bonusReciever = employee as IRecievesBonus;
if(bonusReciever != null)
{
PayBonus(bonusReciever);
}
}
or alternately in C#:-
foreach(IRecievesBonus bonusReciever in employees.OfType<IRecievesBonus>())
{
PayBonus(bonusReciever);
}
We cannot modify the IEmployee interface to include details of the child type as we don't want to pollute the super-type with details that only the sub-type cares about.
We do not have an existing collection of only the subtype.
We cannot use the Visitor pattern because the element types are not stable. Also, we might have a type which implements both IRecievesBonus and IDrinksTea. Its Accept method would contain an ambiguous call to visitor.Visit(this).
Often we're forced down this route because we can't modify the super-type, nor the collection e.g. in .NET we may need to find all the Buttons on this Form via the child Controls collection. We may need to do something to the child types that depends on some aspect of the child type (e.g. the bonus amount in the example above).
Strikes me as odd that there isn't an "accepted" way to do this, given how often it comes up.
1) Is the type conversion worth avoiding?
2) Are there any alternatives I haven't thought of?
EDIT
Péter Török suggests composing Employee and pushing the type conversion further down the object tree:-
public interface IEmployee
{
public IList<IEmployeeProperty> Properties { get; }
}
public interface IEmployeeProperty { ... }
public class DrinksTeaProperty : IEmployeeProperty
{
int Sugars { get; set; }
bool Milk { get; set; }
}
foreach (IEmployee employee in employees)
{
foreach (IEmployeeProperty property in employee.Propeties)
{
// Handle duplicate properties if you need to.
// Since this is just an example, we'll just
// let the greedy ones have two cups of tea.
DrinksTeaProperty tea = property as DrinksTeaProperty;
if (tea != null)
{
MakeTea(tea.Sugers, tea.Milk);
}
}
}
In this example it's definitely worth pushing these traits out of the Employee type - particularly because some managers might drink tea and some might not - but we still have the same underlying problem of the type conversion.
Is it the case that it's "ok" so long as we do it at the right level? Or are we just moving the problem around?
The holy grail would be a variant on the Visitor pattern where:-
You can add element members without modifying all the visitors
Visitors should only visit types they're interested in visiting
The visitor can visit the member based on an interface type
Elements might implement multiple interfaces which are visited by different visitors
Doesn't involve casting or reflection
but I appreciate that's probably unrealistic.
I would definitely try to resolve this with composition instead of inheritance, by associating the needed properties/traits to Employee, instead of subclassing it.
I can give an example partly in Java, I think it's close enough to your language (C#) to be useful.
public enum EmployeeProperty {
RECEIVES_BONUS,
DRINKS_TEA,
...
}
public class Employee {
Set<EmployeeProperty> properties;
// methods to add/remove/query properties
...
}
And the modified loop would look like this:
foreach(Employee employee in employees) {
if (employee.getProperties().contains(EmployeeProperty.RECEIVES_BONUS)) {
PayBonus(employee);
}
}
This solution is much more flexible than subclassing:
it can trivially handle any combination of employee properties, while with subclassing you would experience a combinatorial explosion of subclasses as the number of properties grow,
it trivially allows you to change Employee properties runtime, while with subclassing this would require changing the concrete class of your object!
In Java, enums can have properties or (even virtual) methods themselves - I don't know whether this is possible in C#, but in the worst case, if you need more complex properties, you can implement them with a class hierarchy. (Even in this case, you are not back to square one, since you have an extra level of indirection which gives you the flexibility described above.)
Update
You are right that in the most general case (discussed in the last sentence above) the type conversion problem is not resolved, just pushed one level down on the object graph.
In general, I don't know a really satisfying solution to this problem. The typical way to handle it is using polymorphism: pull up the common interface and manipulate the objects via that, thus eliminating the need for downcasts. However, in cases when the objects in question do not have a common interface, what to do? It may help to realize that in these cases the design does not reflect reality well: practically, we created a marker interface solely to enable us to put a bunch of distinct objects into a common collection, but there is no semantical relationship between the objects.
So I believe in these cases the awkwardness of downcasts is a signal that there may be a deeper problem with our design.
You could implement a custom iterator that only iterates over the IRecievesBonus types.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Which class design is better and why?
public class User
{
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee : User
{
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member : User
{
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
OR
public class User
{
public String UserId;
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee
{
public User UserInfo;
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member
{
public User UserInfo;
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship.
An employee IS A user
An employee HAS A userinfo
Which one is correct? This is your answer.
I don't like either one. What happens when someone is both a member and an employee?
Ask yourself the following:
Do you want to model an Employee IS a User? If so, chose inheritance.
Do you want to model an Employee HAS a User information? If so, use composition.
Are virtual functions involved between the User (info) and the Employee? If so, use inheritance.
Can an Employee have multiple instances of User (info)? If so, use composition.
Does it make sense to assign an Employee object to a User (info) object? If so, use inheritance.
In general, strive to model the reality your program simulates, under the constraints of code complexity and required efficiency.
Nice question although to avoid distractions about right and wrong I'd consider asking for the pros and cons of each approach -- I think that's what you meant by which is better or worse and why. Anyway ....
The First Approach aka Inheritance
Pros:
Allows polymorphic behavior.
Is initially simple and convenient.
Cons:
May become complex or clumsy over time if more behavior and relations are added.
The Second Approach aka Composition
Pros:
Maps well to non-oop scenarios like relational tables, structured programing, etc
Is straightforward (if not necessarily convenient) to incrementally extend relations and behavior.
Cons:
No polymorphism therefore it's less convenient to use related information and behavior
Lists like these + the questions Jon Limjap mentioned will help you make decisions and get started -- then you can find what the right answers should have been ;-)
I don't think composition is always better than inheritance (just usually). If Employee and Member really are Users, and they are mutually exclusive, then the first design is better. Consider the scenario where you need to access the UserName of an Employee. Using the second design you would have:
myEmployee.UserInfo.UserName
which is bad (law of Demeter), so you would refactor to:
myEmployee.UserName
which requires a small method on Employee to delegate to the User object. All of which is avoided by the first design.
You can also think of Employee as a role of the User (Person). The role of a User can change in time (user can become unemployed) or User can have multiple roles at the same time.
Inheritance is much better when there is real "is a" relation, for example Apple - Fruit. But be very careful: Circle - Ellipse is not real "is a" relation, because cirlce has less "freedom" than ellipse (circle is a state of ellipse) - see: Circle Ellipse problem.
The real questions are:
What are the business rules and user stories behind a user?
What are the business rules and user stories behind an employee?
What are the business rules and user stories behind a member?
These can be three completely unrelated entities or not, and that will determine whether your first or second design will work, or if another completely different design is in order.
Neither one is good. Too much mutable state. You should not be able to construct an instance of a class that is in an invalid or partially initialized state.
That said, the second one is better because it favours composition over inheritance.
Stating your requirement/spec might help arrive at the 'best design'.
Your question is too 'subject-to-reader-interpretation' at the moment.
Here's a scenario you should think about:
Composition (the 2nd example) is preferable if the same User can be both an Employee and a Member. Why? Because for two instances (Employee and Member) that represent the same User, if User data changes, you don't have to update it in two places. Only the User instance contains all the User information, and only it has to be updated. Since both Employee and Member classes contain the same User instance, they will automatically both contain the updated information.
Three more options:
Have the User class contain the supplemental information for both employees and members, with unused fields blank (the ID of a particular User would indicate whether the user was an employee, member, both, or whatever).
Have an User class which contains a reference to an ISupplementalInfo, where ISupplementalInfo is inherited by ISupplementalEmployeeInfo, ISupplementalMemberInfo, etc. Code which is applicable to all users could work with User class objects, and code which had a User reference could get access to a user's supplemental information, but this approach would avoid having to change User if different combinations of supplemental information are required in future.
As above, but have the User class contain some kind of collection of ISupplementalInfo. This approach would have the advantage of facilitating the run-time addition of properties to a user (e.g. because a Member got hired). When using the previous approach, one would have to define different classes for different combinations of properties; turning a "member" into a "member+customer" would require different code from turning an "employee" into an "employee+customer". The disadvantage of the latter approach is that it would make it harder to guard against redundant or inconsistent attributes (using something like a Dictionary<Type, ISupplementalInfo> to hold supplemental information could work, but would seem a little "bulky").
I would tend to favor the second approach, in that it allows for future expansion better than would direct inheritance. Working with a collection of objects rather than a single object might be slightly burdensome, but that approach may be better able than the others to handle changing requirements.