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.
Related
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.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a method that is exposed using interface in the business logic layer. It is as follows:
public interface IMyWorkingClass
{
IEnumerable<dynamic> GetSomeList();
}
public class MyWorkingClass : IMyWorkingClass
{
public IEnumerable<dynamic> GetSomeList()
{
dynamic foos = new List<dynamic>();
dynamic item = new ExpandoObject();
item.PropOne = (new Foo()).FooPropertyOne;
item.PropTwo = (new Bar()).BarPropertyOne;
foos.Add(item);
return foos;
}
}
public class Foo
{
public int FooId{get;set;}
public string FooPropertyOne{get;set;}
public string FooPropertyTwo{get;set;}
}
public class Bar
{
public int BarId{get;set;}
public string BarPropertyOne{get;set;}
public string BarPropertyTwo{get;set;}
}
There are a lot of different opinions/preferences out there about dynamic itself. I find them useful. One of my friends said dynamics are good but the way they are used above are not. The argument presented was that the compiler wont catch the things changed on dynamic object. I think the unit tests will be able to catch those. So I disagreed. What is your expert opinion? Thanks in advance :)
Update
Here's bit clearer (hopefully) code:
public interface IMyWorkingClass
{
IEnumerable<dynamic> GetListOfClassesForStudentDynamicReturn();
IEnumerable<StudentClassInfo> GetListOfClassesForStudentStaticReturn();
}
public class MyWorkingClass : IMyWorkingClass
{
public IEnumerable<dynamic> GetListOfClassesForStudentDynamicReturn(Student student)
{
dynamic listOfClasses = new List<dynamic>();
// repository pattern is used in DAL
var datafromDB = (StudentCollegeClassRepo.GetQueryable(x=>x.StudentId==student.StudentId)
.select(item => new {
item.CollegeClassId
,item.CollegeClass.CollegeClassName
,item.IsEnabledForStudent
}).ToList();
foreach (var item in datafromDB)
{
dynamic classWithStudent = new ExpandoObject();
classWithStudent.CollegeClassId = item.CollegeClassId;
classWithStudent.CollegeClassName = item.CollegeClassName;
classWithStudent.IsEnabledForStudent = item.IsEnabledForStudent;
listOfClasses.Add(studentWithClass);
}
return listOfClasses;
}
public IEnumerable<StudentClassInfo> GetListOfClassesForStudentStaticReturn(Student student)
{
// repository pattern is used in DAL
var datafromDB = (StudentCollegeClassRepo.GetQueryable(x=>x.StudentId==student.StudentId)
.select(item => new StudentClassInfo {
CollegeClassId = item.CollegeClassId
,CollegeClassName = item.CollegeClass.CollegeClassName
,IsEnabledForStudent = item.IsEnabledForStudent
}).ToList();
return datafromDB;
}
}
// this class is like a viewmodel
public class StudentClassInfo
{
public int CollegeClassId { get; set; }
public string CollegeClassName { get; set; }
public bool IsEnabledForStudent { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
}
public class StudentCollegeClass
{
public int StudentId { get; set; }
public int CollegeClassId { get; set; }
public bool IsEnabledForStudent { get; set; }
}
public class CollegeClass
{
public int CollegeClassId { get; set; }
public string CollegeClassName { get; set; }
}
Hopefully I made things little clearer now. So,method with dynamic return is ok or create a static type and have that returned instead? I am also learning how to ask question properly here.. Thanks for your patience and awesome replies :)
Despite what Skeet says :) I'll add some thoughts here.
If you start down the path of using Dynamics, you must shift your thinking. You don't know what your object is, you only care about what it can do.
You find yourself not needing interfaces rather quickly - and then you ask yourself "WTF am I doing anyway?". Which is always a great question to ask.
And then a shift happens as you start writing more tests to cover up the loss of a compiler check - you start writing methods a bit more clearly. You start relying on Factories and other classes to impose logic on top of these little bits of amorphous dynamic goo.
It's incredibly freeing if you consider the mental shift. For instance you have a "MyWorkingClass" that does something on top of Foo/Bar. If that was a fulfillment class called "Warehouse" that had some methods called "CheckInvetoryOf(dynamic item)" - things start to make a bit more sense.
In the real world you would send in an interface here - probably ITrackable or something - that exposes a very very small subset of what could be used. It would work, but what if you changed your approach later and wanted the Warehouse to ship digital goods - something like downloads?
Your Warehouse class was probably fashioned after a brick and mortar - and making the shift to sending out digital downloads... OH NO!
But if you use dynamics - it's easy. You could simply ask if the item has is an IDigitalGood (for instance) and handle it nicely.
So - the code you wrote is, yes, confusing. If you spend some time with Dynamic languages it will afford you the mental shift to make it not so confusing.
Oh - in terms of "Architecturally Wrong" to do what you did... who knows. If it's confusing, that's not good. If it makes testing hard - that's triple not good. If you get laughed at, you might be on the right track :)
So, you want to create an interface that expose a method that return an unknown IEnumerable? Is there a direct advantage in using the generic version of IEnumerble in this case beside saving some cast/test/overload that you would have to do anyway if you want to use those objects after the method is returned?
While I won't dispute that dynamic can be useful in some case. In my opinion, it often displays a design flaw. Every time I came to use it, I actually sat down and thought if I really needed it. And most of the time, I came to the conclusion that with some simple changes, I could eliminate it and make a cleaner design.
In this case, do you truly need to have a generic type with dynamic? My first and quick guess would be, you can probably use the non-generic IEnumerable.
Or if you want to save some casting, and you have different elements in there, you can find common ground to all element. I see that right now, all your property are string. Or if you want to return combination of elements, you can use some Tuple<>
If you truly end up returning a complete unknown types of lot of different objects, you could use IEnumerable<object>, but then I would question the reason of existence of that interface implementation. I don't remember ever creating an interface that would return object with absolutely any kind of common ground between the different implementation, or even within a single implementation. It could controls, numbers, components, entities... But they tend to share something. If it's properties, you could even pack in some PropertyInfo!
TL:DR; Unless you can present a very clear case where this design pattern would serve a very specific purpose that is unavoidable by any other means, I would recommend not using it. My IEnumerable of 2 cents.
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 thinking of using extension methods to chain a c# statement to look like jQuery in teh following:
foo foo2 =
new foo().Title(foo1.Title)
.Name(foo1.Name)
.DoSomeStuff()
.DoSomeMoreStuff();
Is this a good/bad idea?
public class foo
{
public string Title {get;set;}
public string Name {get;set;}
public int Age {get;set;}
public foo(){}
}
public static class fooExtension
{
public static foo Title(this foo source, string title)
{
source.Title = title;
return source;
}
//and other extensions
}
Upadate: More explanation as the the "why" I'm considering this.
I have 2 things going on:
I'm getting data from one object and
using it to set the properties of
another.
I need to perform some
action on these properties.
So my initial code looked more like
foo2.bars = foo1.bars;
foo2.RemoveUnderage();
foo2.NotifyPatronsBarsAreFull();
and instead, I thought that it might be more descriptive to write:
foo2.bars(foo1.bars).RemoveUnderage().NotifyPatrons();
Initializers are great, but they also bundle the properties all together and I wanted the property set to be close to the actions on which I would be taking on them.
Anything wrong with using object initializers instead?
new Foo { Title = foo1.Title, Name = foo1.Name }
.DoSomeStuff()
.DoSomeMoreStuff();
Chaining in general is fine (look at LINQ) but object initializers mean you don't need to add methods which look like properties.
I personally like this 'fluent' style of programming. Properly-named methods can look like sentences. I would change yours just a bit:
foo foo2 = new foo()
{
Title = foo1.Title,
Name = foo1.Name
}
.DoSomeStuff()
.DoSomeMoreStuff();
I think it is a bad idea in terms of readability, but that's strictly a personal thing.
Do you mean Fluent interface? In some cases the same way is used in classes in .NET Framework (i.e. StringBuilder or LINQ extension methods). However the fluent interface must be explicitly created and it is a lot of work and usage from another language than C# can be not so pretty. I don't think that creating fluent interface for every class is good way how deliver good software in short time.
I swear I have seen an example of this but have been googling for a bit and can not find it.
I have a class that has a reference to an object and need to have a GET; method for it. My problem is that I do not want anyone to be able to fiddle with it, i.e. I want them to get a read only version of it, (note I need to be able to alter it from within my class).
Thanks
No, there's no way of doing this. For instance, if you return a List<string> (and it's not immutable) then callers will be able to add entries.
The normal way round this is to return an immutable wrapper, e.g. ReadOnlyCollection<T>.
For other mutable types, you may need to clone the value before returning it.
Note that just returning an immutable interface view (e.g. returning IEnumerable<T> instead of List<T>) won't stop a caller from casting back to the mutable type and mutating.
EDIT: Note that apart from anything else, this kind of concern is one of the reasons why immutable types make it easier to reason about code :)
Return a reference to a stripped-down interface:
interface IFoo
string Bar { get; }
class ClassWithGet
public IFoo GetFoo(...);
If the object isn't too complicated/extensive then write an wrapper around it.
for example:
class A {
public string strField = 'string';
public int intField = 10;
}
class AWrapper {
private A _aObj;
public AWrapper(A aobj) {
_aObj = A;
}
public string strField {
get {
return _aObj.strField;
}
}
public int intField {
get {
return _aObj.intField;
}
}
}
So now all you do is give your client code an instance of the AWrapper class so that they may only use what you allow them to see.
this may get a bit complicated and may not scale well if your base class is not set in stone, but for most simple situation it may just do the trick. I think this is called a facade pattern(but don't quote me on that =) )
This isn't possible. Get and set accessors to reference types get and set the reference to the object. You can prevent changes to the reference by using a private (or internal) setter, but you cannot prevent changes to the object itself if it's exposed by a getter.
Your question reads like you're looking for:
public PropertyName { get; private set; }
But then, given the answers so far I'm not sure I'm interpreting your question correctly. Besides, who am I to question Jon Skeet? :)
i agree with ReadOnlyCollection
See my simple code:
private List<Device> _devices;
public readonly System.Collections.ObjectModel.ReadOnlyCollection<Device> Devices
{
get
{
return (_devices.AsReadOnly());
}
}
ReadOnlyCollection dosen't has Add method so user cant add properties to it.BUT ther is no warranty that if user can modify objects by calling their methods....
I have faced this problem in a certain way.
I have a CategoryViewModel class, which have a property Category that I want private read-only :
public CategoryViewModel
{
private Category { get; }
}
In fact, I want it to be exported as read-only to other class. However I can't do such thing.
In my case (maybe it will help some other guys), I want to add it to a repository. The only way that I've found is to have a function with the repository as param 1, and an Action as param 2 :
public void ApplyAction(ICategoryRepository repo, Action<ICategoryRepository, Category> action)
{
action(repo, Category);
}
Like that, from elsewhere, I can do such thing :
categoryViewModel.ApplyAction(_repository, (r, c) => r.MarkForInsertOrUpdate(c));
This can help other to expose there property only for certains cases and can manage them.