I would like to preface that I have not used Dynamic Objects very often, and only recently came across this problem. I have a specific scenario that I will explain below, but I was wondering what exactly were the advantages of implementing a dynamic object compared to creating a class for that object.
I have a method that takes a dynamic object as a parameter. For the sake of length I will not post much code just enough to get the point across:
public static Tax GetEmployeeTax(string Id, Employee employee, dynamic inputObject)
{
var temp = new Employee();
//use the dynamic object properties
return temp;
}
In this case, inputObject will have properties that help identify the employee taxes without directly being related to the employee class. Primarily I have given the inputObject the following properties:
dynamic dynamicEmployeeTax = new ExpandoObject();
dynamicEmployeeTax.FederalTaxInfo = "Some information";
dynamicEmployeeTax.StateTaxInfo = "Some other information";
Are there any advantages to making this it's own class versus using a dynamic object? Are there any benefits one way or the other?
There are several reasons why you want to create a class:
Strong typing leverages the compiler to ensure correctness.
Every class that encapsulates data is like a contract. You can imagine how's used by examining the class.
You force the guy after you to read how it works. It is simpler to read class properties and image its utility.
It is a sign a bad planning and engineering. You are creating blobs of data instead of structured data sets that solve a specific problem. Think mud pits versus Lego blocks.
The list goes on ad infinitum. I think the consensus here is to avoid it. There are extreme rare cases where this is useful. For most, stick to contracts and coding to abstractions not implementation details.
I'm modifying an app for performance gains. The app has a class with many properties. Typically this class is populated in its entirety by a primary key that pulls a large query from a database. The application is in great part slow because this happens constantly throughout, even though much of the time only one two properties in the class are needed in a given section of code. The existing large class has only a default constructor and all of its properties are nullable or have default values. In code below ignore lack of constructors and how these objects are populated.
public class Contract
{
public enum ContractStatus
{
Draft, Active, Inactive
}
private Int32 contractId = DALC.DefaultInt32;
private String name = DALC.DefaultString;
private ContractStatus status;
private ContractType contractType = null;
private CurrencyType currencyType = null;
private Company company = null;
}
As you can see it has its own properties, and also references other classes (e.g. ContractType, Company).
A few approaches I've thought of in light of common design patterns:
1) re-factor this hugely and break up those smaller sub-sections into their own classes with their own properties. Then reconstruct that large class with all of the smaller ones when it is needed. This will be quite laborious, though even if it sounds ideal and consistent with SOLID OOD principles.
2) Create new classes that simply contain the large class, but only expose one or two of its properties. I'm still creating a full blown version of the original, large class, but I will only populate the data I need. This will be via simple DB query, thus the bulk of the class will sit there unused and its null default classes it's referencing won't ever be constructed.
public class ContractName
{
Contract contract;
public ContractName()
{
contract = new Contract();
}
public String Name
{
get { return contract.Name; }
set { contract.Name = value; }
}
}
3) Add new constructors to existing large class with a parameter indicating what chunks of code I want to actually populate. This sounds messy and kind of nasty and wrong, and would leave me in the scenario where if Contract is created by a contract ID in one section of code it has different info than if created by contract ID elsewhere.
Thanks for any ideas!
I would recommend option 1: extract the classes you think you need to extract now. The other two options are just adding more technical debt which will take even longer to resolve in the future. Well-factored code is usually much easier to optimise than big complicated classes.
In my experience, breaking up classes is not all that laborious. In fact I usually find myself surprised by how quickly I can execute refactorings like Extract Class as long as I follow the recipe.
I know this may be purely a design preference, but from your perspective:
Should my functions that retrieve items from the database be static or instance based?
What is generally the most preferred method? (And most common)
What are the Pros/Cons of each method?
I have an class which has 3 properties: (No constructor for the object)
ObjectId - string
Name - string
Count - int
Instance Based Example
public async void Get(string objectId) {
// Gets specific item from "Tag" table
ParseQuery<ParseObject> query = ParseObject.GetQuery("Tag");
ParseObject tagObject = await query.GetAsync(objectId);
this.ObjectId = tagObject.ObjectId;
this.Name = tagObject.Get<string>("name");
this.Count = tagObject.Get<int>("count");
}
Setting my object would be done like so:
Tag myTag = new Tag();
await myTag.Get("123456");
// Properties are set and ready to work with
Static Example
public static async Task<Tag> Get(string objectId) {
Tag toReturnTag = new Tag();
// Gets specific item from "Tag" table
ParseQuery<ParseObject> query = ParseObject.GetQuery("Tag");
ParseObject tagObject = await query.GetAsync(objectId);
toReturnTag.ObjectId = tagObject.ObjectId;
toReturnTag.Name = tagObject.Get<string>("name");
toReturnTag.Count = tagObject.Get<int>("count");
return toReturnTag;
}
And would be set as such:
Tag myTag = await Tag.Get("123456");
I don't think there's an explicitly, definitively better way of doing this. This is the kind of thing that, to me, depends on how you best want to associate responsibilities with the objects in your application. As it stands, both of your functions are more or less the same.
Logically, though, do you want "accessing the database" to be something that each Tag object is responsible for? Should they have knowledge of the database, and, in a greater sense, about anything outside themselves? Or should they just be constructed with the all the information they (seem to) need, and not worry about communication?
In your case, it doesn't seem like you accomplish anything from allowing your objects to take on database-accessing responsibility, so it seems to me like you're better off restricting their concerns in favor of the static option. (If you have to choose between those only those two, I mean. I think you could do just as well with a non-static method in your ViewModel which constructs and returns a Tag object. Mostly my feeling here is that Tags should try to restrict their concerns, not static vs. instance.)
Also, in the static case, why no constructor? You're setting all Tag object's properties before it's returned, so unless you have some need to be able to construct a Tag object with some or all of its properties as null, why not have one?
Edit: A few people have pointed out, reasonably, that static methods tend to make unit testing harder. I agree with that in principle, but I think he'd be more okay in this case:
There's not any state being stored or modified by the method. What comes out is the Tag object, and you can test that regardless of whether it came from an instance or static.
It relies on an external data call (GetQuery) that would need to be mocked anyway.
Without knowing enough about ParseObject.GetQuery (I think this might be Xamarin?), though, I'm not really sure whether a static, or this specific construction, would make it more difficult to mock the data source.
TL;DR: the title says it all, and a simple answer would be great if the question can be answered simply
Longer Version:
I am using a pre-existing library to build invoices, and the library holds the instantiation of the invoice object and static functions which add items to the invoice. The items on the invoice include breakdowns of sub-items, and it has about a dozen columns. No item uses all the columns, and the column usage and values depends on the item listed and it's depth within a breakdown.
So, the invoice can be built with pseudocode like this:
Invoice customerInvoice = new Invoice();
MainItem widget = new MainItem(); //the entirety of the sale, this is shown as the top-level item
SubItem component = new SubItem(widget, values[]); //a component of widget. The parameters identify the main piece that this attaches to, and a set of values for the other columns.
SubItem piece = new SubItem(widget, values[]); //another component; the values[] will be slightly different but correspond to the same columns.
SubItem bolt = new DeepSubItem(piece, lowestValues[]); //an irreducibly small item which is a part of the "piece" item, with it's own set of values which fill a different arrangement of columns
Components and sub-components are shown on indented lines below their parent object.
I am trying to create a new class structure that can help simplify this. The largest problem is that values[] here represents about 20 individual parameters. Additionally, a maze of conditional statements is necessary due to quirks of individual products, variations based on sale location or time, and many other factors. The only constant is that each function corresponds to a single line on the invoice. The original library was great at nesting objects properly, but it can't handle the logic. The SubItem instantiations of piece, bolt, and component only exist so that they can be broken down. When SubItem() or DeepSubItem() are called, the objects are attached to the object that they include in their parameter.
First question: What is a good plan/design pattern/strategy to build a new structure that can use the existing library, but provide flexible logic?
Second question: If I could create an 'instance' of the static functions, I could use that instance without the great verbosity of the parameters. Is there any way to do this, or something that will have a similar effect?
I've been thinking of creating a new class that will conduct the logic and hold the needed sets of values. That class can then create 'objects' (ideally, instances of the static functions) which I can use in the code we already have, replacing the function calls. That would allow me to separate the verbosity (which rarely needs to change) from the logic (which often needs to change). I can't simply use the object "bolt" because the moment I instantiate it, it is added to the invoice - hence why I want to treat the function like an object.
Your wise input (and/or reality check) is greatly appreciated. Thanks,
One of the ways you could do this would be to use the Func object. This allows you to pass functions by reference. Here's an example:
private static object TestStaticFunction()
{
return "test";
}
public static Func<object> GetStaticFunction
{
get { return TestStaticFunction; }
}
Then, any function that calls GetStaticFunction will get TestStaticFunction returned to it. Likewise, Console.Write(GetStaticFunction()) will display "test".
Note that if you want to pass a method that does not return a value, use Action instead.
Here's the MSDN documentation on Func: http://msdn.microsoft.com/en-us/library/bb549151%28v=vs.110%29.aspx
And another StackOverflow thread with more explanation: What is Func, how and when is it used
As far as your program design, I'm not really sure that I understand the library well enough to point you towards a better pattern. Are you forced to work within this library?
Are you talking about delegates?
class Program
{
static void Main(string[] args)
{
var returnedFunction = TestClass.FunctionToReturnAStaticMethod();
returnedFunction();
}
}
public class TestClass
{
public delegate void TypeOfFunctionToReturn();
public static TypeOfFunctionToReturn FunctionToReturnAStaticMethod()
{
return () => StaticMethod();
}
public static void StaticMethod()
{
Console.WriteLine("\"StaticMethod\" called");
}
}
I'm new to the .NET world having come from C++ and I'm trying to better understand properties. I noticed in the .NET framework Microsoft uses properties all over the place. Is there an advantage for using properties rather than creating get/set methods? Is there a general guideline (as well as naming convention) for when one should use properties?
It is pure syntactic sugar. On the back end, it is compiled into plain get and set methods.
Use it because of convention, and that it looks nicer.
Some guidelines are that when it has a high risk of throwing Exceptions or going wrong, don't use properties but explicit getters/setters. But generally even then they are used.
Properties are get/set methods; simply, it formalises them into a single concept (for read and write), allowing (for example) metadata against the property, rather than individual members. For example:
[XmlAttribute("foo")]
public string Name {get;set;}
This is a get/set pair of methods, but the additional metadata applies to both. It also, IMO, simply makes it easier to use:
someObj.Name = "Fred"; // clearly a "set"
DateTime dob = someObj.DateOfBirth; // clearly a "get"
We haven't duplicated the fact that we're doing a get/set.
Another nice thing is that it allows simple two-way data-binding against the property ("Name" above), without relying on any magic patterns (except those guaranteed by the compiler).
There is an entire book dedicated to answering these sorts of questions: Framework Design Guidelines from Addison-Wesley. See section 5.1.3 for advice on when to choose a property vs a method.
Much of the content of this book is available on MSDN as well, but I find it handy to have it on my desk.
Consider reading Choosing Between Properties and Methods. It has a lot of information on .NET design guidelines.
properties are get/set methods
Properties are set and get methods as people around here have explained, but the idea of having them is making those methods the only ones playing with the private values (for instance, to handle validations).
The whole other logic should be done against the properties, but it's always easier mentally to work with something you can handle as a value on the left and right side of operations (properties) and not having to even think it is a method.
I personally think that's the main idea behind properties.
I always think that properties are the nouns of a class, where as methods are the verbs...
First of all, the naming convention is: use PascalCase for the property name, just like with methods. Also, properties should not contain very complex operations. These should be done kept in methods.
In OOP, you would describe an object as having attributes and functionality. You do that when designing a class. Consider designing a car. Examples for functionality could be the ability to move somewhere or activate the wipers. Within your class, these would be methods. An attribute would be the number of passengers within the car at a given moment. Without properties, you would have two ways to implement the attribute:
Make a variable public:
// class Car
public int passengerCount = 4;
// calling code
int count = myCar.passengerCount;
This has several problems. First of all, it is not really an attribute of the vehicle. You have to update the value from inside the Car class to have it represent the vehicles true state. Second, the variable is public and could also be written to.
The second variant is one widley used, e. g. in Java, where you do not have properties like in c#:
Use a method to encapsulate the value and maybe perform a few operations first.
// class Car
public int GetPassengerCount()
{
// perform some operation
int result = CountAllPassengers();
// return the result
return result;
}
// calling code
int count = myCar.GetPassengerCount();
This way you manage to get around the problems with a public variable. By asking for the number of passengers, you can be sure to get the most recent result since you recount before answering. Also, you cannot change the value since the method does not allow it. The problem is, though, that you actually wanted the amount of passengers to be an attribute, not a function of your car.
The second approach is not necessarily wrong, it just does not read quite right. That's why some languages include ways of making attributes look like variables, even though they work like methods behind the scenes. Actionscript for example also includes syntax to define methods that will be accessed in a variable-style from within the calling code.
Keep in mind that this also brings responsibility. The calling user will expect it to behave like an attribute, not a function. so if just asking a car how many passengers it has takes 20 seconds to load, then you probably should pack that in a real method, since the caller will expect functions to take longer than accessing an attribute.
EDIT:
I almost forgot to mention this: The ability to actually perform certain checks before letting a variable be set. By just using a public variable, you could basically write anything into it. The setter method or property give you a chance to check it before actually saving it.
Properties simply save you some time from writing the boilerplate that goes along with get/set methods.
That being said, a lot of .NET stuff handles properties differently- for example, a Grid will automatically display properties but won't display a function that does the equivalent.
This is handy, because you can make get/set methods for things that you don't want displayed, and properties for those you do want displayed.
The compiler actually emits get_MyProperty and set_MyProperty methods for each property you define.
Although it is not a hard and fast rule and, as others have pointed out, Properties are implemented as Get/Set pairs 'behind the scenes' - typically Properties surface encapsulated/protected state data whereas Methods (aka Procedures or Functions) do work and yield the result of that work.
As such Methods will take often arguments that they might merely consume but also may return in an altered state or may produce a new object or value as a result of the work done.
Generally speaking - if you need a way of controlling access to data or state then Properties allow the implementation that access in a defined, validatable and optimised way (allowing access restriction, range & error-checking, creation of backing-store on demand and a way of avoiding redundant setting calls).
In contrast, methods transform state and give rise to new values internally and externally without necessarily repeatable results.
Certainly if you find yourself writing procedural or transformative code in a property, you are probably really writing a method.
Also note that properties are available via reflection. While methods are, too, properties represent "something interesting" about the object. If you are trying to display a grid of properties of an object-- say, something like the Visual Studio form designer-- then you can use reflection to query the properties of a class, iterate through each property, and interrogate the object for its value.
Think of it this way, Properties encapsulate your fields (commoningly marked private) while at the same time provides your fellow developers to either set or get the field value. You can even perform routine validation in the property's set method should you desire.
Properties are not just syntactic sugar - they are important if you need to create object-relational mappings (Linq2Sql or Linq2Entities), because they behave just like variables while it is possible to hide the implementation details of the object-relational mapping (persistance). It is also possible to validate a value being assigned to it in the getter of the property and protect it against assigning unwanted values.
You can't do this with the same elegance with methods. I think it is best to demonstrate this with a practical example.
In one of his articles, Scott Gu creates classes which are mapped to the Northwind database using the "code first" approach. One short example taken from Scott's blog (with a little modification, the full article can be read at Scott Gu's blog here):
public class Product
{
[Key]
public int ProductID { get; set; }
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category category { get; set; }
}
// class Category omitted in this example
public class Northwind : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
You can use entity sets Products, Categories and the related classes Product and Category just as if they were normal objects containing variables: You can read and write them and they behave just like normal variables. But you can also use them in Linq queries, persist them (store them in the database and retrieve them).
Note also how easy it is to use annotations (C# attributes) to define the primary key (in this example ProductID is the primary key for Product).
While the properties are used to define a representation of the data stored in the database, there are some methods defined in the entity set class which control the persistence: For example, the method Remove() marks a given entity as deleted, while Add() adds a given entity, SaveChanges() makes the changes permanent. You can consider the methods as actions (i.e. you control what you want to do with the data).
Finally I give you an example how naturally you can use those classes:
// instantiate the database as object
var nw = new NorthWind();
// select product
var product = nw.Products.Single(p => p.ProductName == "Chai");
// 1. modify the price
product.UnitPrice = 2.33M;
// 2. store a new category
var c = new Category();
c.Category = "Example category";
c.Description = "Show how to persist data";
nw.Categories.Add(c);
// Save changes (1. and 2.) to the Northwind database
nw.SaveChanges();