So I got the Address class:
class Address
{
private String streetAddress;
private int number;
private String postalCode;
private City city;
private State state;
private Country country;
}
And I want to get its readable version to, lets say, show in a grid column.
Whats the best and concise way to implement this?
toString method inside class Address (I personally don't like this approach, as 'toString' is not directly related to an Address)
class ReadableAddressFormatter
ReadableAddressFormatter(Address addressToFormat)
public String getFormatted()
Previous class but getFormmated would be static, receiving the Address instance and returning the string
Other? Suggestions please.
I'm looking for a good design, focusing also in Clean Code, Decoupling and Maintainability.
All of these methods have been used, and there's no way to offer a "context independent" best practice. The best answer in Software Engineering is usually "it depends." That's said, let's analyze each:
The KISS approach at its finest. I do this for all my basic "print to console, make sure things are working" kind of thing. If you have a specific format you can expect for addresses, this is the low-hanging fruit/easy win solution. You can always override this or print out the object differently in one off situations.
This is the most extensible solution, in that it will nicely allow for localization and custom formatting. Whether it is appropriate depends on how often you expect addresses to be shown in different formats. Do you really need that Death Star to knock out a fly, or is the ability to change to all uppercase or change between languages pivotal to your app?
I would not suggest this approach, as it generally started to bleed "view level" logic into the Domain, which is usually best handled by other tiers (in a class MVC approach). One could argue that toString() does the same thing, but toString() can also be thought of as the "name" or "essence" of how an object appears to the external world, so I'd say it's more than just presentational.
Hope this helps, and kudos for thinking about Clean Code, Decoupling, and Maintainability from the beginning.
For an example of principle #2 in action--using the Strategy Pattern, adhering to the Single Responsibility Principle, the Open/Closed Principle and allowing for Inversion of Control via Dependency Injection-- compare the following approach (graciously provided by #SteveJ):
public class Address {
private String streetAddress;
private int number;
private String postalCode;
private String city;
private String state;
private String country;
public String toLongFormat(){
return null; // stitch together your long format
}
public String toShortFormat(){
return null; // stitch together your short format
}
public String toMailingLabelFormat(){
return null; // stitch together your mailing label format
}
#Override
public String toString(){
return toShortFormat(); // your default format
}
}
}
With this one (in "mostly correct" Groovy):
public interface AddressFormatter {
String format(Address toFormat)
}
public class LongAddressFormatter implements AddressFormatter {
#Override
public String format(Address toFormat){
return String.format("%sBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAHBLAH%n%s", toFormat.streetAddress, toFormat.postalCode)
}
}
public class ShortAddressFormatter implements AddressFormatter {
#Override
public String format(Address toFormat){
return String.format("%d", toFormat.number)
}
}
public class Address {
private String streetAddress;
private int number;
private String postalCode;
private String city;
private String state;
private String country;
public AddressFormatter formatter = new ShortAddressFormatter(); // just to avoid NPE
public void setFormatter(AddressFormatter fr) { this.formatter = fr; }
#Override
public String toString(){
return formatter.format(this); // your default format
}
}
def addrr = new Address(streetAddress:"1234 fun drive", postalCode:"11223", number:1)
addr.setFormatter(new LongAddressFormatter());
println "The address is ${addrr}"
addr.setFormatter(new ShortAddressFormatter());
println "The address is ${addrr}"
As #SteveJ has observed:
" So the you have different formatting "strategies" and you can switch
between them...I had this idea that you would set the formatting once
and be stuck with it...AND if you want to add another formatting
style, you don't have to open up and rewrite the address class, but
write a new separate style and inject it when you want to use it."
.NET SOLUTION:
Overriding Object.ToString() seems to be the most logical solution. This makes it clean to use in situations such as: Console.WriteLine("Home Address: {0}", homeAddress);
If you wish to provide additional formatting, the Address class should implement IFormattable.
Also, you should create an AddressFormatter class that implements from IFormatProvider and ICustomFormatter.
The MSDN links provide very well put examples (a BinaryFormatter and a AcctNumberFormat), but if those aren't enough also look at this good example: PhoneFormatter
Additionally, if you do decide to go full out on this and implement IFormattable and a custom IFormatProvider/ICustomFormatter then I'd suggest having your ToString() simply call to your ToString(String format, IFormatProvider formatProvider) with a default provider. That way you can account for things like localization and types of addresses (short, long, etc).
Using toString requires no additional baggage outside the function itself; seems like the simplest solution. It's there for a reason, right?
Usually i divide presentation layer from data layer. Presenting it to a GUI seems to me something related to the presentation layer, not the data layer.
I would suggest you to put a function somewhere in your presentation layer that will convert the address to string.
Presentation of data is not related to data!
A static method is good.
A converter class would be better, you can keep one single instance for your application but you can replace it or write another if you are moving your application from GUI to WEB with another format, or if in one window you want to show everything and in another window you want to show only part of the informations or informations formatted in another way.
There are several model you can follow, for example Microsoft WPF uses totally another approach, the MVVM, Model View View Model, that will allow you to divide very well data layer from business logic from presentation layer.
I usually override ToString in C# or toString in java only for debugging purposes (presenting a string that i can use for debug) or for some kind of simple serialization to string, usually putting also a FromString (or fromString method in java). One example is custom types like Point, Vector, Matrix and so on.
Talking about C# world..
public class AddressToStringConverter
{
public virtual string ToString(Address address)
{
return address.Street + ", " + address.City
}
}
Then in your form (for example).
AddressToStringConverter myConverter = new AddressToStringConverter();
public Address CurrentSelectedAddress { get { ... } }
public button1_click(object sender, EventArgs e)
{
button1.Text = myConverter.Convert(address);
}
If you want you can imlpement other useful interfaces like for example ITypeConverter
toString() is the most flexible and convenient, being implicitly called when you combine an object of the Address class with a String, as in System.out.println("My address is " + objectOfAddressClass).
The only reason I can think of to not override toString() is if you need to alter the formatting. Then you would need different methods (as in toMailingString() and toShortFormString() and so on) or a parameterized method (as in toMailingString(boolean useShortForm) or whatever), but either way, toString() won't cut it.
Of course, you can (and should) do both. Have toString() as your default, probably calling one of your specific format methods, and then have your other helper methods for alternate formats.
public class TestClass {
class City{};
class State{};
class Country{};
class Address {
private String streetAddress;
private int number;
private String postalCode;
private City city;
private State state;
private Country country;
public String toLongFormat(){
return null; // stitch together your long format
}
public String toShortFormat(){
return null; // stitch together your short format
}
public String toMailingLabelFormat(){
return null; // stitch together your mailing label format
}
#Override
public String toString(){
return toShortFormat(); // your default format
}
}
}
You've tagged your post with Java, so I'll answer for Java (and Swing, more specifically). This task is normally the task of a specific TableCellRenderer. If the same format must be used for other visual components, I would indeed extract the formatting inside an instantiatable class (solution 2). This would allow subclasses to customize the format if needed.
I think that a toString() method that returns a string is your best approach. If you have an Address instance, let's say address, then it is obvious what address.toString() does. The fact that toString() isn't directly associated with Address doesn't really change anything.
Related
Please feel free to modify the title, I couldn't come up with any better one =\
Given the following example class
public class Person
{
public string Name;
public int ID;
public string City;
}
I need to create another mirror class, where every field is actually a wrapper of the original class:
public class PersonMirror
{
public FieldWrapper<string> Name;
public FieldWrapper<int> ID;
public FieldWrapper<string> City;
}
public class FieldWrapper<T>
{
public T Value;
public bool someBool;
public int someCounter;
// ..whatever
}
The thing is, I have many classes to mirror, and some of them have many fields! Moreover, the original class may be changed from time to time (add / remove / rename field), and every change must be applied to the mirrored class - not a good practice for maintainability.
My question is - is there a type safe way automate the decleration (rather then creation, such as generated code) of such mirrored classes?
EDIT:
Let's start from the beginning. In our SOA system, there is a resource access service (serviceX) responsible for updating items in the DB. Other services send it the modifications they would like to perform - in json that would be something like: {ID: 123, name : "myNewName"}. serviceX would then build an update query to send to the DB. However, there is a requirement that serviceX will expose a POCO interface, so that the interface will be language independent, so expressions such as (p=> p.name, "MyNewName") are not allowed. Another requirement is type safety, so json is not allowed either. Currently, the above solution is the best one we came up to answer all the requirements. Any better solutions are more then welcome!
IMO, there's no way to do what you want, except code generation.
Approaches for code generation could differ (this maybe source code generation + compilation, emitting IL code, either your own or existing one), but this is the only way.
use T4 to autogenerate your "WrapperClass".
Below, a proposition of how you could implement your FieldWrapper.
public class FieldWrapper<T, O>
{
private T _item;
private O _owner;
private PropertyInfo _setter;
public T Value
{
get { return _item; }
set {
if (!EqualityComparer<T>.Default.Equal(_item, value))
{
_item = value;
// do some personal check
_setter.SetValue(_owner, value);
}
}
}
public bool someBool;
public int someCounter;
// ..whatever
// CTOR
public FieldWrapper(O owner, Expression<Func<T, O>> propertyExpressionInTheOwner)
{
_owner = owner;
propertyName = (propertyExpressionInTheOwner.body as MemberExpression).Member.Name;
// get PropertyInfo using the owner and propertyName
}
}
Using the expression behavior permits you to create your fieldWrapper this way.
var p = new Person();
new FieldWrapper(p, (pers) => pers.Name);
The good point with this technique it is that if you person class change you will directly receive a compilation error.
With T4 the must is to load the assembly where all you class are, tag you class model with a specific attribute. Look into the assembly to found every class that have this attribute and generate the wrapper class associate.
You would have to run it after every code change, but you could create a code parsing application.
List desired keywords to substitute, such as " string ", " int ". Read the file, line by line. Find definition of classes (line contains "class"), then replace every instance of any given keyword in it with:
"FieldWrapper<" + keyword + ">"
You might want to drop keyword substitution inside methods (and perhaps in the method signatures / return types themselves) of by checking for "(" and ")", and the opening curly brace. Resume operation when you reach the closing curly brace. You can achieve that by storing the nesting level in an integer, incrementing it when hitting '{' and decrementing it when reaching '}'.
See my solution below -- search for UPDATE.
I have an extensive state machine architecture, which I'm implementing by creating a class for each state (there are multiple machines, but the states for all inherit from the same 'MachineState' class). Each state has a static property "StateName":
public class SomeState: MachineState
{
// THIS BLOCK SHOULD BE COPIED TO ALL STATE CLASSES!!
private static string _StateName;
public static string StateName
{
get {
if (_StateName == null)
{
_StateName = MethodBase
.GetCurrentMethod()
.DeclaringType
.ToString()
.Split(new char[] { '.' })
.ToList()
.Last();
}
return _StateName;
}
}
// END OF BLOCK
public SomeState(Queue<string> messages) //
: base(messages)
{
...
}
...
}
Ugh.
At least I'll call the processor-intensive stuff to get the name only once per class -- for my purposes, that's an acceptable cost. But I would really like to find some way for them to "inherit" this code -- or at least some way for them to include it something like a macro. I have an abstract property, so if it's not implemented I'll catch it at compile time; but still, there's got to be a way to avoid copying that mess into EVERY class -- and then having to CHANGE it in every class if the need ever arises.
Any ideas?
Thanks.
------------ UPDATE ---------------------------------------
Life is full of compromises; this one I can live with. #Tallek suggested this in the base class:
public static string GetStateName<T>() where T : MachineState
{
return typeof(T).Name;
}
I integrated that with my static property, like this (for class 'SomeState'):
// THIS BLOCK SHOULD BE COPIED TO ALL STATE CLASSES!!
public static string StateName { get { return GetStateName<SomeState>(); } }
It isn't perfect; I'll have to be sure to get the correct state name in the GetStateName call for each class. But it does two things I was anxious to do: it moves the logic into a single location, and it is easier to read. Keeping StateName abstract will help me catch any state that hasn't implemented StateName.
Thanks again, to all.
You have a state
Your states are classes
You want to compare that state to another
You don't want to instanciate states in order to compare
I don't see you doing it easier than:
if(state.GetType() == typeof(SomeState))
I potentially agree with CodeCaster. 20 or 30 states is not that large for an enum.
Based on your description of receiving a message and identifying the handler for that message, combined with looking at your example:
if(stateName == SomeState.StateName) { }
This implies you have stateName as a parameter. So you have an if block for every state so you can identify which one the message applies to?
if(stateName == SomeState.StateName) {
}
if(stateName == OtherState.StateName) {
}
If that is the case...
(big if given limited use case information, the rest of this answer is based on that premise so don't flame me if the rest of this doesn't apply)
You desire to have all classes automatically have this StateName property. This seems DRY, but then we see you still have to have an if block for each state, which is less DRY since there's more code to that IMO. You've traded a DRY for another DRY.
I would have enums which each have a
public enum States {
...
[Handler(typeof(SomeState))]
SomeState = 5,
...
Combined with a factory pattern, and now you throw out all the if blocks and only need a call to your factory:
MachineState newState = StateFactory.Create(stateName);
The factory uses Enum.Parse to convert the stateName into an enum, from which you access the attribute to get the type you need to instantiate. No switch/case/if/else needed.
This means every time you implement a new state class, you only need to touch one place, and that is the enum, and that has minimal code repetition.
If each if block has specific logic in it for that particular State
Move that code into a HandleMessage method defined in a MachineState or IMachineState interface, which has an implementation for each SomeState to do the stuff specific for that state. Let's assume your message indicates the stateName and maybe there's some "content" or "data" in the message that needs to be processed:
MachineState newState = StateFactory.Create(stateName);
newState.HandleMessage(messageContent);
I realize it's probably more complicated than that. You might need to seperate state from state handling into separate classes to make this work well. It's hard say. I would certainly mull this over pretty heavily though if I were in your shoes.
Its not great, but maybe worth considering...
public class MachineState
{
public static string GetStateName<T>() where T : MachineState
{
return typeof(T).Name;
}
}
Use like this:
if("MyState" == MachineState.GetStateName<MyState>()) { ... }
You could accomplish this with an extension method:
public static string GetStateName(this MachineState state) {
return state.GetType().Name;
}
Use it like this:
if(state.GetStateName() == "SomeState") { /* Do something */ }
Bake in your own caching if you want: you have access to any static structures you want here.
I'm trying to refactor some code that is passing different combinations of parameters depending on the type of configuration an object needs. For example:
public MyWidget(string server, string port)
{
...
}
public MyWidget(string server)
{
...
}
public MyWidget(bool createAThing,
string nameOfThingToBeCreated,
string server,
string port)
{
...
}
public MyWidget(bool createAThing, string nameOfThingToBeCreated)
{
...
}
...etc
I don't want to use properties, because it feels like it's hiding some possible dependencies e.g. the object might require the server to be passed in if there's the port property has been assigned. Don't get hung up on the example params, this is just something I'm pulling out of the air.
I looked at the Builder pattern, but it's not quite what I need. Any suggestions would be great!
I'm using .NET 2.0
You could use a configuration object and pass that to your constructor.
Something like this:
public class WidgetOptions
{
public string Server { get; set; }
public string Port { get; set; }
...
}
public class MyWidget
{
public MyWidget(WidgetOptions options)
{
Server = options.Server;
Port = options.Port;
...
}
}
Actually, if the intent is to always create a "valid" object such that the object is not ever in a half-configured state, then the Builder pattern is appropriate. The builder holds the data points until they are all assigned and can then create a completely configured object in one go.
But it sounds like you don't trust your developers to read the documentation to know what to configure...you do provide documentation, right ;)
In that case, perhaps provide a set of builders that each only exposes the properties that relate to the "mode" your final object needs.
So something like this (pseudo code and made up, since you didn't provide any hinst about what you are really trying to model)
WidgetBuilder
+ whatever properties are common to all widget creation
+ MakeWidget
VectorWidgetBuilder : WidgetBuilder
+ get/set Lines
+ MakeWidget
BitmapWidgetBuilder : WidgetBuilder
+ get/set Image
+ MakeWidget
AnimatedWidgetBuilder : WidgetBuilder
+ get/set Images
+ get/set FrameRate
+ MakeWidget
A variation of this would be to define these permutations as various WidgetOptions, as Master Morality called them, but each distint set of options is its own class. So you might have VectorWidgetOptions, BitmapWidgetOptions, and AnimatedWidgetOptions that just exposes the related set of properties.
I study C# and I'm trying to understand the overloaded constructor, how it works and the point using them like a chain call? Why just not have only one constructor with all necessary parameters? Below I have some helping code for a task I'm working with, and I need some help to understand the point with all this constructors. Preciate some help! Thanks!
public class Email
{
//private email
private string m_personal;
//work mail
private string m_work;
public Email()
{
}
public Email(string workMail) : this(workMail, string.Empty)
{
}
public Email(string workMail, string personalMail)
{
m_work = workMail;
m_personal = personalMail;
}
public string Personal
{
//private mail
get { return m_personal; }
set { m_personal = value; }
}
public string Work
{
get { return m_work; }
set { m_work = value; }
}
public string GetToStringItemsHeadings
{
get { return string.Format("{0,-20} {1, -20}", "Office Email", "Private Email"); }
}
public override string ToString()
{
string strOut = string.Format("{0,-20} {1, -20}", m_work, m_personal);
return strOut;
}
}
Why just not have only one constructor with all necessary parameters?
What if users of your class are only interested in some parameters? Using your example, what if somebody doesn't have personal email? Should they pass null or string.Empty? This kind of type-level knowledge is best handled by type itself.
By exposing extra constructor with work email only, you're essentially telling your class consumers "Don't have personal email? Don't worry, I will handle it".
On top of that, chaining definitions naturally helps to avoid code redundancy.
This is not about Constructors. All kind of overloaded functions simplify library usage. When we code a class, we are going to encapsulate all the complexities in a black box and this is possible with some known best Practices. The good example is .NET libraries which you can use easily (remember those overloaded functions/constructors).
This is not about right or wrong, we use overloaded functions to make usage simpler so there would be no need to pass null parameters when it is not needed.
Secondly we call the function with most parameters nested by the next function with less parameters to reduce Redundancy. I mean avoiding copy/paste same code in all versions of function.
I think since the pattern is widely accepted and used, next generations of .NET will hide this redundant versions in some way and we just code the function with the most parameters.
The point is to avoid repeated code, as it will help you avoid this:
public Email(string workMail)
{
m_work = workMail;
m_personal = string.Empty;
}
public Email(string workMail, string personalMail)
{
m_work = workMail;
m_personal = personalMail;
}
Take in account that your constructor could do more than just assigning fields.
How it works? You can try it, debug it and learn it. I'm not sure but I think it will call first the overloaded one and then the code of your constructor. In you scenario, calling Email(string workMail) will call first Email(string workMail, string personalMail).
Check out:
http://www.c-sharpcorner.com/UploadFile/vishnuprasad2005/HowuseCSharpConstructors11302005015338AM/HowuseCSharpConstructors.aspx
http://blog.degree.no/2012/03/calling-an-overloaded-constructor-from-another-constructor-c/
http://weblogs.asp.net/scottcate/archive/2005/11/23/431412.aspx
I would say that the second constructor is provided mainly for convenience purposes, to make the usage of the class easier in cases where there is no personal mail address. The user of the class then only needs to specify the working address, and the class itself will take care of the handling of the nonexistend personal address by setting a sensible default value for that field. If that parameter was missing, the user of the class would be made resposible for filling string.Empty for missing personal mail addresses.
The constructor is implemented as a call to another constructor to avoid duplication of code. It could also be written like
public Email(string workMail)
{
m_work = workMail;
m_personal = string.Empty;
}
but the existing implementation that calls the two-parameter constructor is the cleaner solution because it follows the "Don't repeat yourself" principle.
I'm trying to find a design pattern or a best practice, or some other solution for a problem with keeping back versions of business logic within my application. Specifically, I am looking to find a way to determine which logic was used to issue an insurance policy.
I currently have code which looks like this:
public double FixedDeductibleSurchageAmount()
{
double percent = FixedDeductibleSurchargePercent();
double base_premium = CollisionPremium() + TheftPremium();
return (base_premium * percent);
}
I am needing to make a change to the business logic so that this function looks more like:
public double FixedDeductibleSurchageAmount()
{
double percent = FixedDeductibleSurchargePercent();
double base_premium = CollisionPremium() + TheftPremium() + MedicalPremium();
return (base_premium * percent);
}
Where I run into trouble is that existing policies should rate with the previous logic. Is there a design pattern for this? If not, are there any good ways to implement it?
Strategy pattern sounds most applicable. Probably you'd need a factory method or some such that takes in a date to return the appropriate strategy.
You're going to have to use additional data of some form to keep track of precisely what algorithm was used to obtain your data; you'll probably need to change your persistence representation to maintain versioning information about the algorithm used to derive your results.
BTW, you might consider making things like MedicalPremium or TheftPremium a Get-only property, rather than a parameterless function. They fit that paradigm very well.
There are any number of ways you can solve this problem. Some examples:
1) Switch to the new code and add a flag to the user data so that MedicalPremium automatically returns 0 for old users. This is particularly easy if you stored your data in XML; the old data just won't have the flag, and it won't affect your deserialization of the data because XML is flexible.
2) Make the class that contains your function MedicalPremium a base class, and make MedicalPremium virtual. Override it in the derived class, which is your new version. Newer users are the derived class. Old users are created as the base class. For the old users, it always returns 0. Properties can also be virtual just as functions can.
If you have a chance to look at Martin Fowler's Patterns of Enterprise Architecture he talks about individual instance methods, which isn't entirely the same as what you have, but is very similar. It's a great book in any case.
In the meantime, I think you might have to start considering your functions as also being data, and store in your database which function was used. You don't need (but may want) to store the function text, but you do need enough information to determine at run time which method to call. You asked about patterns, and obviously you have a strategy pattern going on here, which you could reference, but I don't know if it will be especially helpful.
Yes there is: the Decorator Pattern. You can use this to extend the behavior of a class with additional wrapper classes. In the example below I combine this with the Template Method Pattern to achieve what I believe you are looking for.
public class BaseSurchargePolicy {
protected abstract double BasePremium { get; }
protected abstract double FixedDeductibleSurchargePercent { get; }
public double FixedDeductibleSurchageAmount{
get
{
return (BasePremium * FixedDeductibleSurchargePercent);
}
}
protected ICollection<string> _ProcessorsUsed;
public IEnumerable<string> ProcessorsUsed
{
get { return ProcessorsUsed; }
}
}
public class OldSurchargePolicy : BaseSurchargePolicy
{
protected double BasePremium
{
_ProcessorsUsed.Add(GetType().Name);
return CollisionPremium + TheftPremium;
}
protected double FixedDeductibleSurchargePercent { get; set; }
public double CollisionPremium { get; set; }
public double TheftPremium { get; set; }
}
public class MedicalSurchargeDecorator: BaseSurchargePolicy
{
private BaseSurchargePolicy _wrapped;
private double _medicalPremium;
public MedicalSurchargeDecorator(BaseSurchargePolicy wrapped, double medicalPremium)
{
_wrapped = wrapped;
_medicalPremium = medicalPremium;
}
protected double BasePremium
{
get
{
_ProcessorsUsed.Add(GetType().Name);
return _wrapped.BasePremium + _medicalPremium;
}
}
protected double FixedDeductibleSurchargePercent {
get { return _wrapped.FixedDeductibleSurchargePercent }
}
}