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.
Related
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.
Let's say I have an interface called IConvertableModel and it helps me to convert some MVC models to/from DTO objects as shown below:
public class DisplayEditModel : IConvertableModel<Display>
{
[HiddenInput(DisplayValue = false)]
public int ObjectId { get; set; }
[StringLength(255)]
public string Description { get; set; }
public Display ToDto()
{
return new Display
{
Description = Description,
ObjectId = ObjectId,
};
}
public void SetFromDto(Display dto)
{
Description = dto.Description;
ObjectId = dto.ObjectId;
}
}
But there is one problem with this approach and that is it doesn't allow me do this :
var dto = _dtoRepository.GetFirstDto();
return new DisplayEditModel().SetFromDto(dto);
Instead I should do the following:
var dto = _dtoRepository.GetFirstDto();
var model = new DisplayEditModel();
model.SetFromDto(dto);
return model;
and this is adding extra two lines of code and little bit complexity in the long run.
What I am thinking is to convert SetFromDto method to something like this:
public DisplayEditModel SetFromDto(Display dto)
{
Description = dto.Description;
ObjectId = dto.ObjectId;
return this;
}
I think the benefit of this code is obvious but I also like to learn whether this harms code readability and leads to unexpected results for developers in the long run and if you think anything else, what would you recommend.
Note: Because of the interfaces reasons, I am not thinking to implement a constructor method.
A few thoughts, to begin with:
Adding lines of code is not the same as adding complexity. Having three statements, where each does a simple operation, is not necessarily harder to maintain or understand than a single statement with three operations inside of it.
When a method that begins with Set..., programmers will automatically assume that some stateful values of the target object are going to be changed by this method. It is rare for Set methods to have a return value. Property setters in C# actually "return" the original value passed into them, so you can chain setters:
int i = foo.A = 2;
So the precedent is generally against returning "this" from a set method specifically.
Chaining in general is most useful/desired when you're expecting several operations to be performed, one after the other. For example, C# provides nice initialization syntax so you can "chain" a bunch of different property setters on the same object:
var foo = new Foo { A = 1, B = 2 };
You can see how chaining is fulfilling the need to perform similar, grouped, repetitive operations that typically get performed all together. That is not the problem that you are trying to solve.
If your main gripe is that you don't like having three lines of code, why not just use a helper whose name indicates what you're trying to do?
TModel MapToModel<TModel, TDto>(TDto dto, TModel model)
where TModel : IConvertableModel<TDto>
{
model.SetFromDto(dto);
return model;
}
// usage:
var dto = _dtoRepository.GetFirstDto();
return MapToModel(dto, new DisplayEditModel());
... or even:
TModel CreateModel<TModel, TDto>(TDto dto)
where TModel : IConvertableModel<TDto>, new()
{
var model = new TModel();
return MapToModel(dto, model);
}
// usage:
var dto = _dtoRepository.GetFirstDto();
return CreateModel<DisplayEditModel>(dto);
This is simple, readable, and feasible, whereas the approach you're suggesting would break the IConvertableModel<Display> interface:
public interface IConvertableModel<TDto>
{
public TDto ToDto();
public ??? SetFromDto(TDto dto);
}
What would SetFromDto return? You would have to define another generic type on IConvertableModel.
public interface IConvertableModel<TDto, TModel> {
public TDto ToDto();
public TModel SetFromDto(TDto dto);
}
But this wouldn't really indicate that the SetFromDto method is necessarily returning itself, because it allows for a class that is not a TModel to implement IConvertableModel to convert between two other types.
Now, you could go out of your way to push the generics even farther:
public interface IConvertableModel<TDto, TModel>
where TModel : IConvertableModel<TDto, TModel>
{...}
But this still allows for some fudging, and the interface cannot guarantee that you are really returning "this" object. All in all, I'm not a big fan of that approach.
Rather than having DisplayEditModel have a get/set method for a Display object to get/set the values, just use a property that doesn't actually have a separate backing store:
public Display Display
{
get
{
return new Display
{
Description = Description,
ObjectId = ObjectId,
};
}
set
{
Description = value.Description;
ObjectId = value.ObjectId;
}
}
Now you can use an object initializer with this property when creating a model:
return new DisplayEditModel() { Display = dto };
This is a very javascript way of approaching this problem, though it has it's benefits. In the context of C#, it is a little bit strange though libraries such as LINQ do this to allow chaining together function calls.
My only worry about this, is that this has to be a class that does this consistently. Implementing a chaining function return pattern is not really a convenience as much as it is a design choice. The rule to follow in this case, would be to return this every time you mutate the object.
Chaining also may not be worth it performance wise. Something that can be done by wrapping all those operations into a single function is much faster. For instance:
MyVector.setX(1).SetY(1).SetZ(1).SetW(0)
is a lot slower than simply
MyVector.set(1, 1, 1, 0)
because now you are now doing excessive stack operations to do something fairly simple. It only becomes worth it on very large operations that take up the bulk of the computing time and make sense to chain together. For this reason, LINQ allows you to chain things together.
I wouldn't say that it necessary "harms" or is dangerous. We are in the world of a managed language, so we don't have direct access to that memory location (unlike C/C++). So I would just call it a design choice which can be fairly powerful in some cases and not so much in others.
As noted, chainable methods work fine but are not as common in C# as in some other languages. If the extra lines of code only happen in one place, I'd just leave it alone. If it's really bugging you or you do it a lot, then consider implementing a special constructor for it:
public void DisplayEditModel(Display dto)
{
this.SetFrom(dto);
}
or a static factory method:
public static DisplayEditModel CreateFrom(Display dto)
{
var model = new DisplayEditModel();
model.SetFrom(dto);
return model;
}
Either option has a clear intent, lets you create and return the object in a single line, and is idiomatic. It does require a few extra lines of code in DisplayEditModel, but I doubt it will be a serious problem.
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.
Here is some code that uses a parameter class to contain the possible parameters to the Show() method. The values in this FooOption class aren't very related. You can see this by looking at the implementation of Show() below. I know this is bad code, but are there any anti-patterns related to doing this?
class FooOptions {
public int? Id { get; set; }
public string BazContext { get; set; }
public int? BazId { get; set; }
}
class BarMgr {
public Bar Show(FooOptions options) {
if (options == null)
options = new FooOptions();
if (options.Id.HasValue)
return svc.GetBar(options.Id.Value);
if (!string.IsNullOrEmpty(options.BazContext) && options.BazId.HasValue)
return svc.GetBar(options.BazContext, options.BazId.Value);
return null;
}
}
Update:
I know that parameter objects are not an anti-pattern. In my experience, parameter object properties are related. This is the possible anti-pattern that I am trying to locate. setting all three properties makes no sense.
After your update, here my answer:
As far as I know, there is no real name for an anti-pattern like this, but there is at least one principle that this method violates:
The Single-Responsibility-Principle.
And it really is a problem of the method and not of the parameter object.
It's called the parameter object pattern, and it's not considered an antipattern -- it's a good way to deal with methods that would otherwise have too many parameters.
There might be an anti-pattern if you use options a lot we have something called feature envy and is an indication that you might want to move functionality into the actual feature being used.
I've never really questioned this before until now. I've got an input model with a number of fields, I wanted to present the string names of the properties through the input model so that my Grid can use them:
public class SomeGridRow
{
public string Code { get;set; }
public string Description { get;set; }
public const string Code = "Code";
}
Obviously, this gives the error:
The type 'SomeGridRow' already
contains a definition for 'Code'
Why can the CLR not cope with two properties of the same name which are, in my eyes, separate?
string code = gridRow.Code; // Actual member from instantiated class
string codeField = SomeGridRow.Code; // Static/Const
I'm now just using a child class called Fields within my inputs now, so I can use SomeGridRow.Fields.Code. It's a bit messy, but it works.
Because you can also access static (or, non-instance in this case) properties in the same way (inside the same class), and it would be a bit confusing, for example:
public class SomeGridRow
{
public string Code { get;set; }
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
Because both this:
public class SomeGridRow
{
public string Code { get;set; }
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
And this:
public class SomeGridRow
{
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
are valid ways to access properties, static or not. It doesn't answer the "why can't I?" question, but more of the why it's not allowed...it would be far too ambiguous IMO.
It probably could, but the designers of C# wanted to avoid ambiguities that can come from such use (abuse?) of language features.
Such code would end up being confusing and ambiguous to users (did I want the instance or the static method call?, Which one is right?).
In addition to the points already made about ambiguity, i would say that the naming needs to be relooked in such a case.
If two variables / fields having the exact same name in the same context i.e class but different values to me sounds more like a naming issue.
If they are exactly same, you dont need 2 fields.
If they are slightly different, you should have more accurate names.
In some other languages with a similar syntax, one can access a static member through an instance. So you could access both string.Empty and "abc".Empty.
C# doesn't allow this (though it does sort of from inside the class or a derived class, in that you can omit the class name for a static member and can omit this for an instance member), primarily to avoid confusion (I find it more handy than confusion tbh, but that's just me, I like switch fall-through too so what do I know).
Having introduced a stricter rule to allow for less ambiguity, it would be counterproductive to allow a new looser rule on the back of it that allowed for more. Think how many "why must I use this with property X but not property Y?" questions SO would have if it was allowed (we'd have to force this with property X to be clear we meant the instance member).