Standard C# class/approach for representing a cash-flow "umbrella" value? - c#

I am creating a program to model my financial ingoings and outgoings
For example, one value is "outgoings", made up of "rent" and "livingCosts",
and then "livingCosts" is made up of "food", "entertainment" and "houseBills" etc.
I want to define this "umbrella-term" relationship between the numeric values. I could create my own class, but I suspected there might already be a class / special approach in C# to do this, as it seems like a common problem. Is there?

There is no such class for two reasons: it's trivial to create and everyone needs it to be a bit different. So actually making a class for it that then has to be customized, where the customization takes more work and code than the actual class is not very efficient.
You will have to roll your own.

Related

How to structure classes in a C# program

I have a VSTO (Excel) project written in C#. Three questions:
I have a lot of variables that are populated once and then referenced extensively throughout the project. So I created a public static class which I called "Omni" - since that is both descriptive and short. Is something like this the recommended approach?
I put common functions in a public static class that I named "Utilities". I then used the "this" keyword as the first parameter, making them extension methods. They can then be accessed from anywhere - without using a "Utilities." prefix (although I'm not exactly sure why). Same question: is this the preferred way of doing this?
Finally, I have some common 'subroutines', i.e., public void methods. So parameters are passed in and processed, but nothing is returned. Should such common code just go in its own appropriately named public static class and then get called with the class name as a prefix? If so, is there any convention as to what the name of the class would be?
I realize these are newbie type questions (and I have been searching for a while!). Thanks.
Regarding your points
I have a lot of variables that are populated once and then referenced
extensively throughout the project. So I created a public static class
which I called "Omni" - since that is both descriptive and short. Is
something like this the recommended approach?
Yes, it is common practise to centralize for example string constants that
are often used.
If you have more of those, I would start to structure those to different
classes.
If you want that to be flexible and e.g. have cases where there are
mappings between constants, like Green = 1, I would move to some
enumeration value technology.
More on that idea can be found in this article
If the value does not change between different starts of your application,
check if you can use resources for that, which is often a good choice
for string constants to.
I put common functions in a public static class that I named
"Utilities". I then used the "this" keyword as the first parameter,
making them extension methods. They can then be accessed from
anywhere - without using a "Utilities." prefix (although I'm not
exactly sure why). Same question: is this the preferred way of doing
this?
Extension methods are a handy way of getting things like conversions done.
Just do not everything as an extension, just conversions as a rule of thumb.
Finally, I have some common 'subroutines', i.e., public void methods.
So parameters are passed in and processed, but nothing is returned.
Should such common code just go in its own appropriately named public
static class and then get called with the class name as a prefix? If
so, is there any convention as to what the name of the class would be?
This, in opposite of the others, looks like a design flaw.
Perhaps you can provide more information on what those subroutines do.
In object oriented code, code is distributed near the objects it is working
with. If you depend heavily on code that is in static classes, probably there
is something wrong. Do your static classes have members? Do they share some
knowledge between different calls to your static classes?

what is the benefit of get set for simple variables [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Public Fields versus Automatic Properties
I figured this would be answered someplace, but I'm not finding it in the usual places. I was wondering, what is the benefit of doing this
private int _foo;
public int foo {get {return _foo;} set{_foo = value;}}
or
public int foo {get; set;}
over just
public int foo;
I can see the benefit if more complex manipulation was required, but what is the benefit for a simple case like this?
Actually, all the guidelines are about creating reusable libraries. There, when you create a property (using get/set), you also create the opportunity to later add code that is executed when someone gets or sets the value (like adding validation etc.) without changing the external definition of your code (and thus not needing to recompile the other libraries). But this has no value if you always recompile your whole solution and noone else is using the library.
Another benefit from using a property is that you can limit who can get or set the value. For example, everyone can get the value but only derived classes can set it (protected).
This said, it is still the recommendation to use properties always when they are public (as opposed to private fields).
I only expose fields when I need the best possible performance (like accessing the value million times in a row).
So to summarize
Benefits of properties (get/set) over fields:
Ability to add code later on without recompiling assemblies that reference this.
Ability to provide private/protected/internal set and public get (or any other combination).
Public fields are not CLS compliant.
Drawbacks of properties:
Slower to access (both read and write).
Can't pass as ref arguments to methods.
This question was asked many times here.
There is no clear benefit evidence fo these cases (no logic inside property).
Would say more, that using a field, you get some minimal (nano) speed benefit, but not relevant for 99.99% cases.
The guideline defined by MS suggests using properties, for expandibility and maintanability of your code. So following that guideline make easier work for someone that not familiar with the code to reading it.
See this Jon Skeet tutorial or When to use properties instead of functions for discussion of this matter. There is also a billion related questions and resources on this topic, which a Google/SE seach will expose.
I hope this helps.
According to me, using 'get-set' is providing a property. Basically you are implementing the concept of Encapsulation while providing the get-set property to a variable.
Imagine you have public variables in a class to store data.
But, if you need to do data validation, you are unable to do so with public variables in a class. Because you have no control over them. Outsiders, other programmers, anyone who access your project could edit those public variables in a class.
MAINLY, In order to control the access to data in your class we use properties. They are still variables but within the authority of your class. These variables may be from any data type (Eg. String, Int, Bool, Objects, etc)
Properties can be impemented using three main options, based on what/how you want to achieve with a property.
Get - access to the property and retrieve its value
Let - access to the property and update its value
Set - access to the property and used with objects
It's vital that one understands the real use of Get/Set methods. I agree with Tigaran on his comment.
If anyone is going to vode me down, I would like to know the reason!
I think you've answered your own question.
For simple cases like this, there is no real advantage. Automatic get/set methods are created by using the shorthand properties:
public int Foo { get; set; }
For more complex examples where transformation is needed then you have the flexibility to alter things using explicit get and set methods.

Translating one object to another via an extension method - looking for alternate solutions

This may be a bit of an odd question, and what I have in place now works, but it feels a bit strange to me and I wonder it's because of poor design/architecture. Any thoughts here would be appreciated.
The initial design is in a code base I inherited from someone else. We have a linq-to-sql class (auto generated in the dbml's designer file).
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ARCustomers")]
public partial class ARCustomer : INotifyPropertyChanging, INotifyPropertyChanged
{
// variables
// extensibility method defs
// ctor
// properties
// etc.
}
Then another class class called ArCustomer (notice the lower case "r") that is an extended version of the auto-generated class. When I say extended, I mean it has all the properies of the LINQ class, plus a few more that requires some logic to populate.
There are a lot of places in code that we want to take an ARCustomer and turn it into an ArCustomer. So I wrote an extension method (this is what felt strange) on the ArCustomer class.
public static ArCustomer FromDatacontextObject(this ArCustomer customer, ARCustomer datacontextObject)
{
var arCustomer = new ArCustomer();
arCustomer.Id = datacontextObject.ProjectID;
// more of the same
// now populate the other fields that don't exist on the datacontextObject
return arCustomer;
}
It's called as such.
var customerfromDb = accountReceivableRepository.GetCurCustomer(arId);
ArCustomer customer = new ArCustomer();
customer = customer.FromDatacontextObject(customerfromDb);
This feels wrong to me, but I don't know of any better alternatives off the top of my head. (Would a partial class that contains the extended properties work? Populate them in it's constructor?) Or maybe it's fine... I'm interested in a few things...
Am I right in feeling that this is wrong/odd/bad?
Specifically, what are the cons to be found in the solution I've implemented? I feel like one is that I scratch my head too often trying to differentiate between the two classes and figure out which is which.
Are their any pros?
Any better solutions (and why they're better)?
(Unrelated - I hope this kind of question is OK for stack overflow. I almost feel like I'm asking for a mini code review, which can be subjective; on the other hand, I tried to ask some concrete questions and feel I must not be the only developer to have ran into a situation like this ("I have one object and need to turn it into another"), so hopefully there is something to be gained from leaving the thread open).
Thanks guys!
Your instincts serve you well.
Having two classes with the same name (differing only be case) is technically allowed by the C# compiler, but it is a bad idea. Also, it is not CLS compliant.
It is a bad idea for the exact reason that you already stated: readability. Don't underestimate the importance of readability. Personally it is my number one measure of code quality. Readable code tends to have fewer bugs, and is easier to debug/maintain.
The classes generated by LINQ to SQL are already partial classes. You can add a separate code file to define any extra parts that you want. And, this is the preferred method to accomplish what you are describing. It is easier to maintain and understand.
Alternatively, you could create a "ViewModel" class that contains the ARCustomer. (This depends on your architecture).
If you change the extension method to extend the database object you have a more natural API IMO
public static ArCustomer ToDomainObject(this ARCustomer datacontextObject)
{
var arCustomer = new ArCustomer();
arCustomer.Id = datacontextObject.ProjectID;
// more of the same
// now populate the other fields that don't exist on the datacontextObject
return arCustomer;
}
then the data access code looks like this
var customerfromDb = accountReceivableRepository.GetCurCustomer(arId);
ArCustomer customer = customerfromDb.ToDomainObject();
Few days ago I had the same problem. And I did find some discussions on this topic.
These threads might help: Thread one, Thread two
As I figured out, there is no better way to do what you are doing. However, you might try to use reflection to iterate through all the fields in parent object to copy them to relevant fields in child object. Some example code here, And discussion here.
For my problem, ended up going field by field manually, as some of the fields I needed to be deeply cloned, some had to be copied only by reference.

How much info should I put into a class? (OOP)

I'm a 1st level C# programming student, though I've been dabbling in programming for a few years, and learning above and beyond what the class teaches me is just what I'm doing so that I'm thoroughly prepared once I get out into the job environment. This particular class isn't OOP at all, that's actually the next class, but for this project the teacher said he wouldn't mind if we went above and beyond and did the project in OOP (in fact you can't get an A in his class unless you go above and beyond anyways).
The project is(at this point) to read in an XML file, byte by byte, store element tags to one array, and the data values to another. I fought with him on this(given the .net frameworks dealing on XML) but that was a losing battle. He wants us to code this without using .net XML stuff.
He did provide an example of OOP for this program that he slopped together (originally written in Java, ported to C++, then ported from C++ to C#)
In his example he's got three classes. the first, XMLObject, which contains the arrays, a quasi constructor, getter and setter methods(not properties, which I plan to fix in my version), and a method for adding the < and > to tags to be stored in the arrays (and output to console if need be.)
The second class is a parseXML class. In this one he has fields that keep track of the line count, file offset, tag offset, and strings to hold elements and data.
Again, he's got getter and setter methods, several parse methods that search for different things, and a general parse method that uses the other parse methods(sort of combines them here). Some of these methods make calls to the XMLObject class's methods, and send the parsed element and data values to their respective arrays.
The third class he has is one that has no fields, and has two methods, one for doing ATOI and one for dumping a portion of the file stream to the console.
I know we're essentially building a less efficient version of what's already included in the .net framework. I've pointed this out to him and was told "do not use .net's XML class, end of discussion" so let's all agree to just leave that one alone.
My question is, should those really be 3 separate classes. Shouldn't the parsing class either inherit from the XML object class, or just be coded in the XML object class, and shouldn't the ATOI and dumping methods be in one of those two classes as well?
It makes sense to me that if the parsing class's aim in life is to parse an XML file and store elements and data fields to an array, it should be in the same class rather than being isolated and having to do it through getters and setters(or properties in the version I'm going to do). I don't see why the arrays would need to be encapsulated away from the parse methods that actually give them what to store.
Any help would be appreciated, as I'm still designing this, and want to do it at least as close to "proper"(I know it's a relative term) OOP form.
The general rule is that we count the size of a class in the number of responsibilities that it has:
A class should have a single
responsibility: a single reason to
change.
It seems to me that your teacher did separate his responsibilities correctly. He separated the presentation from the xml parsing logic, and he separated the xml data from the xml parsing behavior.
First: If you're in a programming class, there may be a good reason he wants you to do this by hand: I really don't recommend arguing with your professors. You'll never win, and you can hurt your grades.
Second: His version is not (considering the fact that it is largely a re-writing of parts of the System.XML namespace) too terrible. Basically you have one class that "Is" your XML. Think of it like the XDocument or XmlDocument classes: Basically it just contains the Xml itself. Then You have your Xml Parser: think of that like XmlReader. And your last one is sort of his equivalent of XmlWriter.
Remember that with OOP, your Xml class (the one that represents the document itself) should neither know nor care how it came into possession of the information it has. Further, the Parser should know how to get the Xml, but it shouldn't much care where it gets stored. Finally, your Writer class shouldn't really care where the data is coming from, only where it's going.
I know it's over-used, but think of your program like a car- it has several parts that all have to work together, but you should be able to change any given part of it without majorly affecting the other pieces. If you lump everything in one class, you lose that flexibility.
Some points:
Classes are nouns; methods are verbs.
Your class should be called XmlParser.
Since the XML parser is neither part of the XMLObject nor extends the XMLObject, it should be a separate class.
The third class has nothing to do with either of the other two; it's just an ordinary Utilities class.
In general, each class should be responsible for a single unit of work or storage.
Don't try to put too much into a single class (see the "God object" anti-pattern).
There's nothing wrong with having lots of classes. (As long as they all make sense)
Let's summarize what the system must do :
to read in an xml file, byte by byte,
store element tags to one array,
the data values to another.
I would probably slice it up in the following way:
Reader : Given a file path, yields the contents byte-wise (IEnumerable<byte>)
Tokenizer: Given an enumeration of bytes, yields tokens relevant to the XML-Context (IEnumerable<XmlToken>)
XmlToken : Base class to any output that the tokenizer produces. For now you need 2 specializations :
Tag : An opening tag
Value : Contents of a tag
TokenDelegator : Accepts a Tokenizer and an instance of
IXmlTokenVisitor: (See Visitor pattern)
TagAndValueStore: Implements IXmlTokenVisitor. Visit(Tag tag) and Visit(Value value) are implented and the relevant content stored in arrays.
You see, I ended up with 7 classes and 1 interface. But you may notice that you have laid the foundations for a fully-fledged XML parser.
Often code that is sold to be OO just plain isn't. A class should adhere to the Single-Responsibility principle.

Regarding Passing Many Parameters

I have around 8-9 parameters to pass in a function which returns an array. I would like to know that its better to pass those parameters directly in the function or pass an array instead? Which will be a better way and why?
If I would do anything, then it would be to create an structure that holds all parameters to get nice intellisence and strong names.
public struct user
{
public string FirstName;
public string LastName;
public string zilionotherproperties;
public bool SearchByLastNameOnly;
}
public user[] GetUserData(user usr)
{
//search for users using passed data and return an array of users.
}
Pass them individually, because:
that is the type-safe way.
IntelliSense will pick it up in Visual Studio and when you write your calling functions, you will know what's what.
It is faster to execute that way.
If the parameter really IS the array, though, then pass the array. Example:
For functions which look like this, use this notation:
Array FireEmployee(string first, string middle, string last, int id) {...}
For functions that look like this, use the array:
Array FireEmployees(Employee[] unionWorkers) {...}
Your scenario is covered by the Introduce Parameter Object refactoring in Martin Fowler's refactoring book. The book is well worth owning, but for those who don't, the refactoring is described here. There's also a preview on the publisher's site, and on Google books. It recommends replacing the parameters not with an array, but a new object.
Regarding Skeets comment on my example above that he would use a class instead of a structure and maybe make it clearer where to use a class and where to use a structure i post this too. I think there are other out there who are curious about this too.
The main reason to use a class as I could see was you could make it immutable, but thats possible with structures too?
for example:
struct user
{
public user(string Username, string LastName)
{
_username = Username;
}
private string _username;
public string UserName {
get { return _username; }
}
}
I have long time felt that I dont know the differences anymore between classes and structures now when we can have propertys, initializers, fields and exactly everything that a class has in a structure too. I know classes are refernce types and structures are value types but what difference does it make in the case above when using it as a parameter in a function?
I found this description of the differences on the site http://www.startvbdotnet.com/oop/structure.aspx and that description is exactly how I mapped it in my head:
Structures can be defined as a tool
for handling a group of logically
related data items. They are
user-defined and provide a method for
packing together data of different
types. Structures are very similar to
Classes. Like Classes, they too can
contain members such as fields and
methods. The main difference between
classes and structures is, classes are
reference types and structures are
value types. In practical terms,
structures are used for smaller
lightweight objects that do not
persist for long and classes are used
for larger objects that are expected
to exist in memory for long periods.
Maybe this should be a own question but I felt it was related when we all had different views on the structure vs class-thing as parameter.
I assume you're using C# 4 and can just use named parameters:
FireEmployee(
first: "Frank",
middle: "",
last: "Krueger",
id: 338);
These make the code almost as readable as VB or Smalltalk. :-)
If not, I would go with what Dave Markle has to say.
If this is library code that will see a lot of use, and if some of the parameters have typical values that are candidates for default values, then you should consider Dave Markle's advice, and provide a selectio of overloads with progressively fewer parameters. This is the approach recommended in the Microsoft Framework Design Guidelines.
Alternately, you can get a similar effect with Stefan's approach, by setting default values with member initializers and using a progression of ctor overloads.
If you really don't want to pass in your arguments separately I would suggest creating a new class which encapsulates all of your arguments. You can (in Java and most likely in C#) declare a public inner class inside the class containing the gnarly method for this purpose. This avoids having classes floating around which are really just helper types.
I would say pass them individually as well. I don't like the idea of creating a class, then passing that class through as an argument. Its a form of stamp coupling, which means making changes will be harder since one class uses the other. And reusing one class means you would have to reuse the other as well.
You could use an interface to reduce stamp coupling, but that's too much overhead for my tastes, so that's why I like to pass the arguments individually.
Do you really need 8-9 parameters for a single function? It seems to me that if you need that many parameters, then you're probably doing too many different things in that function. Try refactoring the code into separate functions so that each function has exactly one purpose.
Do not pass them as an array unless the function acts on an array, I wouldn't create a new data structure either to group the parameters for the following reasones
Passing a new data structure hides what the function really needs as input (does it need all the data structure/part of it?)
Related to 1 it makes UTs more difficult (when writing a UT you need to recreate the entire data structure)
If the input parameters are not related you end up with a new data structure that groups unrelated data types for no other reason than to make a function call look neater
If you chose to pass the new data structure to your function the function can not be used in a scope where the new datastructure was defined
Really the only disadvantage to passing each paramater to the function is that you might not be able to fit the function in one line of code, but don't forget the lines you need before the function call in which you will fill up your data structure.

Categories