So I'm currently writing an API, but I've hit a road block in construction. The issue is a series of values will constantly be called throughout, which requires a lot of parameters to be constantly pushed into series of classes and methods throughout the API.
Which is not very elegant nor practical. As it will induce a large amount of extra code.
My thought was originally was this:
public class CustomerProfile
{
public string ParentSite { get; private set; }
public string DynamicSite { get; private set; }
public string SiteDb { get; private set; }
public CustomerProfile(string parentSite, string dynamicSite, string siteDb)
{
if (string.IsEmptyOrNull(parentSite) &&
string.IsEmptyOrNull(dynamicSite) &&
string.IsEmptyOrNull(siteDb))
{
throw new Exception("Error Message: + "\n"
+ "Null value exception...");
}
else
{
ParentSite = parentSite;
DynamicSite = dynamicSite;
SiteDb = siteDb;
}
}
}
So my thought was to have a nice class that will set the properties, will act like a container for these repeatable values.
However, my issue seems to come from the next class.
public class Configuration
{
public CustomerProfile profile;
public Configuration(string parentSite, string dynamicSite, string siteDb)
{
CustomerProfile profile = new CustomerProfile(parentSite, dynamicSIte, siteDb);
}
}
This now works throughout the class I would just use profile.SiteDb or another property that resides within it.
But is this really the best approach?
I could use simple inheritance, but I'm not really sure that is cleaner or more efficient. Any thoughts on the matter would be terrific?
Is this approach the more ideal to pass property values from one class to another, as it will be used throughout several and several methods as well. I was looking for the cleanest way to invoke.
So my question is:
Out of all the ways to pass properties, what way is the best and why?
I thought this approach would be best but as I begin to use it
throughout it seems like it may not be the most ideal.
Thank you.
Related
I have an application that will run once every minute. After completing, the app will write to a log table before it exits. This object closely maps that log table:
class SendResult
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public TimeSpan ExecutionTime { get
{
return EndTime - StartTime;
}
public bool RequestChecked{ get; set; }
public int RequestID { get; set; }
public bool RequestRequiresFileSend { get; set; }
public bool FilesRead { get; set; }
public bool FilesSent { get; set; }
public SendResult() { }
}
Each property will be updated at a different point in the app. I have achieved this by declaring the object once and making it static:
class Program
{
public static SendResult Result;
public Program()
{
Result = new SendResult();
Result.StartTime = DateTime.Now;
// do stuff...
Result.EndTime = DateTime.Now;
LogUtility.Log(Result);
}
}
..and everywhere throughout the app I just call:
Program.Result.FilesRead = ...
I know an alternative is to construct the app around SendResult, like this:
SendResult result = new SendResult();
result.StartTime = DateTime.Now;
var request = new RequestHandler().CheckRequest();
result.RequestChecked = request.Checked;
result.RequestID = request.RequestID;
result.RequestRequiresFileSend = request.FileSendRequired;
var sendResult = new FileSender(request.ResuestID).Send();
result.FilesRead = sendResult.FilesRead;
// ...and so on
But in a case where you have to insert this result tracking after all your code has been written, is there a better way than the global var method I have used?
The parts of the code summarized as "do stuff" should take in the SendResult instance as a dependency that is either explicitly pushed into them, or possibly resolved in some way other than directly depending on accessing a static field in Program. You can pass the reference directly using constructor arguments, object properties, or method parameters. Indirect ways to do that could be implemented using an IoC/DI container. The idea is to reduce coupling, which is most of the time a good idea.
Potentially, your application could benefit from using the Pipes and Filters Architectural Pattern, but only if you have scaleability and flexibility requirements. Otherwise, the introduced complexities would be counterproductive for your particular case.
Static variables are usually not a good idea, there is almost no uses of them in the modern application with Dependency Injection. It's use adds a state and increase coupling, making it much more complicated to e.g. unit test all your components in isolation.
So the simplest approach would be to just create the required object and send it to all the methods that require editing. It's a bit hard to say generally though, it might be better that all your methods do return their own objects that are later composed into the resulting one that is saved to the database.
But while there can be different strategies to achieve what you want, using static variable is most likely not the best of them.
I've deserialized JSON into a c# object, but with an incomplete JSON such that some properties are missing. At the time of deserializing the object, I don't have access to the full JSON. I can get the full JSON by making another API call, but I don't want to make that call if I don't have to.
I would like my property getters to work such that they return the property if it's not null. If it is null, it should make the call to the API to get the full JSON and update all of the JsonProperties in the class, and then return the property I've asked for.
public class Car
{
private string _make;
private string _model;
[JsonProperty("make")]
public string Make
{
get
{
if (_make != null)
{
return _make;
}
else
{
UpdateProperties();
return _make;
}
}
}
[JsonProperty("model")]
public string Model
{
get
{
if (_model != null)
{
return _model;
}
else
{
UpdateProperties();
return _model;
}
}
}
[JsonProperty("self")]
public Uri Self { get; set; }
public void UpdateProperties()
{
}
}
In the UpdateProperties() method above, I can make it use the Self property to get and deserialize a new instance of a Car class, but I want it to refresh the properties of the current Car class instance instead. I can do this manually by setting each property individually again, but since I need to do this for many classes, I would appreciate a better way. Is this possible?
Or am I going about this all wrong?
EDIT:
Here is an example of the JSON the API would return. Lets say I make a call to get information about the vehicle fleet. It would return:
{
"details" : "something"
"car": {
"make": "Ford",
"self": "https://..."
}
"truck": {
"age": 30,
"self": "https://..."
}
}
where when you access the url provided by car.self, it would return the following JSON:
{
"make" : "Toyota",
"model" : "Camry",
"self" : "https://..."
}
So, let me offer a different perspective. The problem description seems straightforward enough- I have two API calls, one which returns a partial object, and one which returns a complete object. I don't want to make two calls if I don't have to. So, I'll just make the second call and "fill in the details" if I need to, right?
Wrong.
The proposed approach is not a good idea.
This goes off the rails from the beginning with the design of the API. The objects returned by the API should not be so complicated so as to require multiple calls to return the "full" object as described in the code. But, let's assume I have no control over the design of the API - what should I do?
Programmers are frequently faced with the task of confronting a badly-designed API. These create leaky abstractions like the one described in this problem, where there is a strong desire to "paper over" the bad API design. The problem is that not all bad designs can be papered over. This is one.
What is proposed here is to introduce a painful side-effect of a get accessor. This is arguably the worst way to solve the problem of a bad API design. A typical get method returns with a negligible amount of time - it's a simple memory access. This proposed get accessor could potentially take seconds to return, it could fail, it could throw an exception. Worse yet, there is no indication to the caller that this is, in fact, access to an external interface. At the end of the day, the state of your object is not deterministic, which is the arguably the worst thing you can have in a program.
If that wasn't bad enough, get accessors have no provision for asynchronous operations, which are common when dealing with remote APIs. User experience will suffer. By taking this approach, I will have actually taken one problem and made a new problem everywhere this class is used.
A better approach:
The API has two separate functions, so really, this implies two separate result types. I would create one type for the partial class and a second type for the full class. After all, I'm writing code - and unless the code is in the habit of re-writing itself, I should know at the time of writing whether I need the full or the partial representation of the object.
To get the full representation, I'll provide a separate access to the API, with appropriate methods to allow for asynchronous execution (e.g. observables). This will have the added benefit of allowing me to examine (via the "where used" function) where in the program these different API calls are used. This might build a case for me to return to the API designer and suggest a change to the design, based on how I'm using it.
The only way with your current setup to reset all of the properties manually.
You're right to want to have this be automatic, since that's a lot of boilerplate code. This is a common problem and the most common solution to it is to use the DTO or Data Transfer Object pattern.
You would introduce a new class called a CarDto and instead of Car exposing private fields, it would expose the properties on the CarDto.
See Below:
public class Car {
private CarDto _dto = null;
public Car(CarDto dto = null) {
//If we pass in a dto, use it, otherwise create a new one
_dto = dto ?? new CarDto();
}
[JsonProperty("make")]
public string Make {
get {
if (_dto.Make == null) {
UpdateProperties();
}
return _dto.Make;
}
}
[JsonProperty("model")]
public string Model {
get {
if (_dto.Model == null) {
UpdateProperties();
}
return _dto.Model;
}
}
[JsonProperty("self")]
public Uri Self { get; set; }
public void UpdateProperties() {
//The API would return a CarDto.
CarDto newDto = APICall(); //Mock code
_dto = newDto;
}
}
public class CarDto {
public string Make { get;set; }
public string Model { get;set; }
}
So now, if you ever have a null property, you will make a call to UpdateProperties. This will then return a new CarDto that you use as your private _dto field.
This is a SUPER useful and common pattern, and one that makes things a lot easier so it's great to implement and get practice using! Let me know if anything is unclear.
Consider the following code:
public interface IIdentifiable<T>
{
T Id { get; set; }
}
public interface IViewModel
{
}
public class MyViewModel1 : IViewModel, IIdentifiable<int>
{
public string MyProperty { get; set; }
public int Id { get; set; }
}
public class MyViewModel2 : IViewModel, IIdentifiable<string>
{
public string MyProperty { get; set; }
public string Id { get; set; }
}
I also have class that operates with ViewModels:
public class Loader<T> where T: IViewModel
{
public void LoadData()
{
/*some important stuff here*/
if (typeof(IIdentifiable<??>).IsAssignableFrom(typeof(T)))
{ // ^- here's the first problem
data = data.Where(d => _dataSource.All(ds => ((IIdentifiable<??>) ds).Id != ((IIdentifiable<??>) d).Id)).ToList();
} // ^---- and there the second ----^
/*some important stuff here too*/
}
}
Now, as you can see, viewmodels that I have might implement the IIdentifiable<> interface. I want to check that, and if it's true,
I want to make sure my data list does not contains any entry that are already present in my _dataSourse list.
So I have 2 questions:
I don't know what IIdentifiable<> has in its generic parentheses, it might be int, string or even GUID.
I tried typeof(IIdentifiable<>).IsAssignableFrom(typeof(T)) which is the correct syntax, yet it always returns false.
Is there a way to check whether T is IIdentifiable<> without knowing the exact generic type?
If there is an answer for the first question, I would also like to know how can I compare the Id fields without knowing their type.
I found this answer quite useful, yet it doesn't cover my
specific case.
I know that I probably can solve that problem if I make my Loader<T> class a generic for two types Loader<T,K>, where K would be the
type in IIdentifiable<>, yet I would like to know if there are other solutions.
P.S. In addition to my first question: I'm also curious why one can write something like this typeof(IIdentifiable<>).IsAssignableFrom(typeof(T)) if it returns false when the generic type of IIdentifiable<> is not specified?
Edit: I guess, in hindsight, I understand why I can't write the code this bluntly - because there's might be the collection ICollection<IViewModel> where the entries implement different types of IIdentifiable<> (or don't implement it at all), and the check like that would fail awkwardly. Yet maybe there is a way to do something like that with some restrictions, but without creating second generic parameter to my Loader?
Try add two methods to your Loader<T>:
public bool CanCast<TId>()
{
var identifiableT = typeof(IIdentifiable<>).MakeGenericType(typeof(TId));
return identifiableT.IsAssignableFrom(typeof(T));
}
public IEnumerable<IIdentifiable<TId>> Filter<TId>(IEnumerable<T> data)
{
return data.Where(d => _dataSource.All(
ds => !((IIdentifiable<TId>) ds).Id.Equals(((IIdentifiable<TId>) d).Id)));
}
Then in LoadData
if (CanCast<int>())
data = Filter<int>(data);
else if (CanCast<Guid>())
data = Filter<Guid>(data);
// and so om
Well, I would suggest you to always use a string for identification. You can convert int and guid to a string. And if you want to ensure proper type is used then you can prefix the string with type information.
However, I do think that the performance of you algorithm would be very poor as you wouls essentially loop 2 containers so it would be O(n * m).
Thus it would be best to either do appropriate SQL query if both sources are from the database or use a dictionary if you do it in code. Alternatively if data is properly sorted, you could find duplicates more efficiently.
By the way generics are quite limited in C#. Sometime using ˋFunc<>ˋ could help but even then you have to provide extra information to the algorithm.
We should address your question in two steps (because there really are two problems to solve here).
First, make following change to your interface IIdentifiable<T>
public interface IIdentifiable<T>
where T : IEquatable<T>
{
T Id { get; set; }
}
This will ensure that you can compare Id properties correctly.
Secondly, in your LoadData() method, change the if statement to
if (T is IIdentifiable<T>)
{ // ^- here's the first problem
data = data.Where(d => _dataSource.All(ds => ((IIdentifiable<T) ds).Id != ((IIdentifiable<T) d).Id)).ToList();
}
I have a summary objects, who's responsibilities actually to combine a lot of things together and create a summary report, who later going to be serialized into the XML.
In this objects I have a lot of structures like this:
public class SummaryVisit : Visit, IMappable
{
public int SummaryId { get; set; }
public int PatientId { get; set; }
public int LocationId { get; set; }
public IMappable Patient
{
get
{
return new SummaryPatient(PatientBusinessService.FindPatient(this.PatientId));
}
}
public IMappable Location
{
get
{
return new SummaryLocation(LocationBusinessService.FindLocation(this.LocationId));
}
}
public IEnumerable<IMappable> Comments
{
get
{
return new SummaryComments(CommentBusinessService.FindComments(this.SummaryId, Location));
}
}
// ... can be a lot of these structures
// ... using different business services and summary objects
public IEnumerable<IMappable> Tasks
{
get
{
return new SummaryTasks(TaskBusinessService.FindTasks(this));
}
}
}
PatientBusinessService, LocationBusinessService etc. are statics.
And each of these SummaryPatient, SummaryLocation etc. have the same type of structure inside.
What is the best approach to refactor and unit test this?
Tried to replace static calls with calls via the interfaced proxies (or refactor statics to non-static classes & interfaces), but this class just got a lot of these interfaces as the constructor injection stuff and start to be super greedy. In addition, these interfaces have a one used method inside (if I going to create it just to this summary needs).
And as soon as this is a summary object, commonly this static services used just once for the whole structure to get appropriate properties for output.
You could change your tests to be more integrational (test more than one class at the time). You could try to modify your services to be more universal and be able to take data from different sources (like TestDataProvider and your current data provider).
Better solution I think is to modify classes you want to test:
Use strong typing for properties and gain all benefits. I think you should return more specific types instead of IMappable
It looks like some of your data is stored inside class (ids) some data is not (IMappable object references). I would refactor this to hold references to objects inside class:
private SummaryPatient _patient;
public SummaryPatient Patient
{
get
{
if (_patient == null)
_patient = new SummaryPatient(PatientBusinessService.FindPatient(this.PatientId));
return _patient;
}
}
Then you can assign your tests data in constructor or create static method CreateDummy(...) just for unit tests. This method then should use CreateDummy for child objects. You can use it in your unit tests.
Bit of an odd one this...
Lets say I have the following class:
public class Wibble
{
public string Foo {get;set;}
public string Bar {get;set;}
}
This class is used a process where the values of Foo and Bar are updated/changed. However after a certain point in the process I want to "lock" the instance to prevent any changes from being made. So the question is how best to do this?
A solution of sorts would be something like this:
public class Wibble
{
private string _foo;
private string _bar;
public bool Locked {get; set;}
public string Foo
{
get
{
return this._foo
}
set
{
if (this.Locked)
{
throw new ObjectIsLockedException()
}
this._foo = value;
}
}
public string Bar
{
get
{
return this._bar
}
set
{
if (this.Locked)
{
throw new ObjectIsLockedException()
}
this._bar = value;
}
}
}
However this seems a little inelegant.
The reason for wanting to do this is that I have an application framework that uses externally developed plugins that use the class. The Wibble class is passed into the plugins however some of them should never change the contents, some of them can. The intention behind this is to catch development integration issues rather than runtime production issues. Having the object "locked" allows is to quickly identify plugins that are not coded as specified.
I've implemented something similar to your locked pattern, but also with a read-only interface implemented by a private sub-class containing the actual class data, so that you could pass out what is clearly a read-only view of the data and which can't be up-casted to the original 'mutable version'. The locking was purely to prevent the data provider from making further changes after it had provided an immutable view.
It worked reasonably well, but was a bit awkward, as you've noted. I think it's actually cleaner to have mutable 'Builder' objects which can then generate immutable snapshots. Think StringBuilder and String. This means you duplicate some property code and have to write the routines to do the copying, but it's less awkward, in my opinion, than having a write-lock on every property. It's also evident at compile-time that the snapshot is supposed to be read-only and the user of the Builder cannot modify the snapshots that it created earlier.
I would recommend this:
An immutable base class:
public class Wibble
{
public string Foo { get; private set; }
public string Bar { get; private set; }
public Wibble(string foo, string bar)
{
this.Foo = foo;
this.Bar = bar
}
}
Then a mutable class which you can change, and then create an immutable copy when the time comes.
public class MutableWibble
{
public string Foo { get; set; }
public string Bar { get; set; }
public Wibble CreateImmutableWibble()
{
return new Wibble(this.Foo, this.Bar);
}
}
I can't remember the C# syntax exactly, but you get the idea.
Further reading: http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=vs.71%29.aspx
You cannot make an object immutable!
You can follow this post:
How do I create an immutable Class?
But I think you can always change property values by reflection!
update
"...Actually, string objects are not that
immutable and as far as I know there are at least 2 ways to break string
immutability. With pointers as shown by this code example and with some advanced System.Reflection usage...."
http://codebetter.com/patricksmacchia/2008/01/13/immutable-types-understand-them-and-use-them/
The other option you have is use the BinaryFormatter to create a memberwise clone of the object to be "locked". Though you're not locking the object you're creating a snapshot which can be discarded while the original remains unchanged.