I was just writing a small asp.net web page to display a collection of objects by binding to a repeater, when this came to mind.
Basically the class I've created, let's call it 'Test', has a price property that's an integer data type (ignore the limitations of using this type, I'm just using it as an example). However I want to format this property so it displays a currency and the correct decimal places etc.
Is it best practice to have a function within the class that returns the formatted string for the object, or would it be better to have a function in the back end of my web form that operations on the object and returns the formatted string?
I've heard before that a class should contain all it's relative functions but I've also heard that presentation should be kept in the 'presentation layer' in my N-tier app.
What would be the best approach in my situation? (and apologies if I haven't explained this clearly enough!)
Thanks!
In my opinion, both options are valid from an OO point of view.
Since the value is a price (that just happens to have the wrong data type), it makes sense to put the formatting into the data class. It's not something that's specific to the web interface, and, if you develop a different kind of user interface, you are very likely to require this formatting again.
On the other hand, it's a presentation issue, so it also makes sense to put it into the presentation layer.
For general OOP stuff, the object should not be exposing implementation details. I choose to interpret this as "avoid setters and getters when possible".
In the context of your question, I suggest that you have a getPriceDisplay() method that returns a string containing the formatted price.
The actual implementation of the formatting is hidden in the implementation details. You could provide a generic function for formatting, use some backend call, or something else. Those details should make no difference to the consumer of the 'Test' object.
Though it's not an OOP approach, in my opinion, this is a good time for an extension method. Call it .ToCurrency() which has the format of the currency...this could be taken from the Web.Config file if you wanted.
Edit
To elaborate, I would simply call .ToString("your-format") (of course this could be as simple as .ToString("C") for your specific question) in the extension method. This allows you change the format throughout the UI in one place. I have found this to be very useful when dealing with DateTime formats in web applications.
Wouldn't .ToString("C"); do the job? This would be in the presentation layer I would imagine.
Related
I have a component that acts as a middle man between 2 web services. Both of them communicate using JSON.
The data that goes back and forth from the web services is very similar. However, it does need to be massaged a little.
I currently have this working by deserializing the JSON, build a new JObject and serialize it. It seems like there should be better way.
I'm looking at JsonConvert, JsonConverter, JsonSerializer, JsonReader, etc. trying to see if there's a better way to do this.
Any guidance on what classes to use/override to make this process more efficent?
Thanks!
You can write a custom JsonConverter using the approach described in the documentation, so you'll only have one concrete class, but this class can translate to a slightly different JSON representation of your object.
Another, more verbose, blog post about writing custom JsonConverters can be found here: http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/
I've wondered this in many different situations, so here I come, looking for the experts knowledge.
Let's say I have to model something that requires a collection. A simple example: an application that stores famous quotes along with their author and a set of tags or keywords. The user should be able to enter a tag or keyword and get matching quotes for it.
My question is: do I really need a class that contains my collection of quotes? Something like this:
Or would this also be correct?
I'm asking this in the more abstract way possible (after all, UML should never depend on the implementation).
I've always thought the second example (just 1 class) was incorrect, but now I'm thinking that maybe the user can press a button on some interface and that button executes some code that gets a quote stored somewhere, and the second example would also be correct?
Basically, should I always have a collection stored somewhere, even if the storing class does nothing else but just store the collection (and provide the methods to access it)?
I definitelly prefer only one class, if there is no strong reason to have another container class (especially on abstract conceptual level). Then I add the collection methods as static functions. A separate container class would only bring more complexity, more dependencies and doubts like yours. :) Doubts often indicate the lack of a real need. When you really need something, you know it.
Here an example with some explanations. I find it simple, clear, elegant and abstract, meaning non-restrictive, easy to transform to any implementation you like:
When it comes to relationships of this class to other class, then you actially have your collection, without introducing new class. This diagram shows two examples. "Other class" actually sees a collection "quotes" which is ordered, like Vector. "One more class" also has a collection of Quotes with different characteristics.
Later on implementation level you can implement it directly like this or eventually adding a Factory or Container class, according to concrete, implemention resctrictions and special reqs.
Question:
Is there a static way to reliably determine the type contained by a type derived from CollectionBase, using Reflection or Microsoft.Cci?
Background:
I am working on a code generator that copies types, makes customized versions of those types, and converters between. It walks the types in the source assembly via Microsoft.Cci. It prints out source code using textual templates. It does a lot of conversion and customization, and tosses out code that I don't care about.
In my resulting code, I intend to replace List<T> everywhere that a CollectionBase, IEnumerable<T>, or T[] was previously used. I want to use List<T> because I am pretty sure I can serialize it without extra work, which is important for my application. T is concrete in every case. I am trying not to copy CollectionBase classes because I'd have to copy over the custom implementation, and I'd like to avoid having to do that in my code generator.
The only part I'm having a problem with is determining T for List<T> when replacing a custom CollectionBase.
What I've done so far:
I have briefly looked at the MSDN docs and samples for CollectionBase, and they mention creating a custom Add method on your derived type. I don't think this is in any way enforced, so I'm not sure I can rely on that. An implementor could name it something else, or worse, have a collection that supports multiple types, with Object as their only common ancestor.
Alternatives I have considered:
Maybe the default serialization does some tricks that I can take advantage of. Is there a default serialization for CollectionBase collections, or do you generally have to implement it yourself? If you have to do it yourself, is there some reliable metadata I could look at in order to determine the types? If it supports default serialization, does it rely on the runtime types of the items in the collection?
I could make a mapping in my code generator of known CollectionBase types, mapped to their corresponding T for List<T>. If a given CollectionBase type that I encounter isn't in the list, throw an exception. This is probably what I'll go with if I there isn't a reliable alternative.
I'm still not sure enough about what you want to do to give advice. Still, do your CollectionBase-derived classes all implement Add(T)? If so, you could look for an Add method with single parameter of type other than object, and use that type for T.
We're developing a business ASP.NET application. Is it better to pass an entire entity to a method or pass each property of this entity as parameters? What is the best practice?
Case 1. Pass Customer entity to a manager - InsertCustomer(Customer cust)
Case 2. Pass each property as a parameter - InsertCustomer(string name, string address...etc)
P.S. We're using Entity Framework as our data access layer
Pass the entire entity, not only for reasons given in the other answers, but generally methods with long parameter chains are bad. They are prone to error, and tough to work with from a development standpoint (just look at Interop with Office)
In general, if I see I am getting too many parameters (usually more than three), either I have a method trying to do too much, or I explore ways of encapsulating this data in a struct.
You should pass the entire entity as when you update the entity, e.g. add or remove members you do not have to update all your method calls in all your layers. You only need to change your datalayer and the layer where you are consuming the entity. asp.net is Object Oriented and therefore you should orientate your code around your objects
The whole concept of object orientation requires objects to be passed around. If all is happening internally I would go with this.
If this is being posted to a webservice / across a network etc you would need to serialize, and hence may find it better to pass each individual parameter, especially if the receiving framework is different.
Don't forget your Strings etc are all objects too.
I agree with another poster, passing a whole entity "encapsulates" everything so that it can be updated/modified so you have less to worry about.
I've got a person object with a name and age property that implements INotifyPropertyChanged. I want to hook this object up to an ASP.NET form so that the 'name' and 'age' properties bind to textboxes in a way that, when changes happen in either place (in the control or in the object) the other will get updated.
Do I create an intermediary class that listens to each textbox change events and the objects change events and handle the updates between them? What's the best way to do this?
I'm unclear on how to get business objects and the UI talking to each other.
I've stressed over this exact problem a lot.
The short answer is, yes, an intermediate item.
The trick is to NOT write ANY code per control. You should be able to place a GUI control on the screen (That may or may not take code), and then bind your business logic to it through a generic binding mechanism.
I have defined the bindings through XML, through properties files, and through constant arrays--there are a million ways...
You probably have to write code per TYPE of object bound (a listbox binds differently than a text control) and you may have to write validators (but specifying the parameters to the validators and which control the validators bind to should also be done in data)
Now all that said, I'd be really surprised if some data-driven auto-binding mechanism didn't already exist, Microsoft has been into that since VB first came out (although their implementations used to be pretty inflexible, I'm sure they do a better job now).
I'm very insistent about the 0 lines of code per control because my job has typically involved configuring complex devices with dozens of pages of controls. A typical client/server system will have 7(!) lines of code PER CONTROL just to transport data from the DB, to the server, to the client, to the screen and back (this is a minimum for plain ole "dumb" code with no smart binding tricks).
0LOC/control may not be a requirement for everyone, but it's a good goal.
Comment response:
I've done most of my stuff manually in Java, so I'm not sure I can be too much help with the specifics.
Searching for C# and binding gave me this which looks promising, although it may be binding straight to a database which is too much IMO, it should bind to a business object, but the concepts should be the same.
One way to create the bindings at first is to manually instantiate binding objects... (Please excuse my Java)
TextControl textCtrl1=new TextControl("Name Goes Here");
new TextBinder(textCtrl1, personObject, nameField);
In Java, that second line gets tricky. When you are binding to a particular field, you HAVE to use reflection to find the setter and getter for that field of the personObject. In C# I think it should be easier.
Anyway, the binder should add itself as a listener to the control and the object, then forward changes back and forth.
Does that help any?
Edit2:
As you noticed, the hard part is noticing when your property is updated. Luckily, that is optional. More often than not, you don't need to update the component once the object is set (I had to deal with this a few times when I had distributed UIs that could update each other).
So, if you assume your object won't change, the "Binding" has to do the following:
get the value from the property and set it in the component.
add itself as a listener to the component.
store the property/object (if you can manipulate properties, you're set here. If not, you need to store the object and property name, and use reflection)
bail and wait for an "updated" event from your component.
When you get the update from your component:
- store the value in the property.
- You may want to set an "Updated" flag or store the original so that if you iterate through all the binding components, you can tell if any updates need to be saved/enable the "ok" button.
Your object should always be pretty much up-to-date now.
As you build a form, you may want to put all your binding controls into a collection so that you can do a few other operations...
A "Save" operation could call each binding control and tell it to copy from the control to the property, that way you don't need to use a listener.
A "Reset" operation can reset all the controls to their original value.
A "Test" operation can ask each control if it's been updated.
. etc
The neat thing about doing it this way is that every "Operation" you wish to add is pretty trivial to add, but automatically affects the entire UI.
You probably also want a little object hierarchy of controls with an abstract base "bind" class, then a specific binder for each type of control (text field, number field, date, spinner, table, pulldown)--I think that's about it.
This can be very simple, but gains complexity rapidly. Try it with a text field and see what you can do. A simple text binding object should just be like 5 lines of code if you can pass "properties" around in C#...
Okay, totally separate answer. As I told you, I'm not very up-to-date with C# technologies, but from what I've heard, LINQ may do this entire job for you.
In fact, LINQ may be made to do exactly what you are trying to do. It doesn't exist in Java, so that's why I gave you the "Manual" version in the other answer.
The comment at the bottom of this page: http://msdn.microsoft.com/en-us/library/z919e8tw.aspx alludes to a better way.