Tag Info

New answers tagged

0

Serialization is a two part problem: Knowledge about how to instantiate a class aka structure. Knowledge about how to persist/transfer the information that is needed to instantiate a class aka mechanics. As far as possible, structure should be kept separate from the mechanics. This increases the modularity of your system. If you bury the information on ...


6

I generally avoid having the class know how to serialize itself, for a couple of reasons. First, if you want to (de)serialize to/from a different format, you now need to pollute the model with that extra logic. If the model is accessed via an interface, then you also pollute the contract. public class Image { public void toJPG(String filePath) { ... } ...


0

I'm my opinion, you should change your code so that it is Simple, Consistent and Readable. I wrote some blog posts on this topic, and trust me they are simple to understand: What is good code Simple: Just like a circuit board contains different pieces, each one with a responsibility. Code should be divided into smaller, simpler parts. Consistent: Use ...


1

Remember many rules in programming are essentially recommendations you can follow. So sometimes this is acceptable. Unit tests are called that way because they focus on testing single units of work. Generally, if you need more than one assertion per test case, you are structuring your test inappropriately. testing alternative code flows in the method, ...


1

After thinking about it overnight and looking at Nebu's answer, here are the solutions I came up with: Return only the URI, and accept one a/sync Func. While I do think it's reasonable for an API to return the URI to a video (in case the user doesn't want to download it just yet), I think it's a bit technical to ask him/her to download the source of the ...


1

But what to do with generic class, and more importantly how handle references to it? The general way in the front end of the compiler is to have two sorts of type instances, the generic type (List<T>) and a bound generic type (List<Foo>). The generic type defines what functions exist, what fields, and has generic type references wherever T ...


0

While it doesn't reduce boilerplate in the code itself, Visual Studio 2015 now comes with a refactoring option to automatically generate the boilerplate for you. To use this, first create your interface IExample and implementation Example. Then create your new class Composite and make it inherit IExample, but do not implement the interface. Add a property ...


1

Why not make FromYouTubeAsync be a pure function (e.g. which takes a String representing the HTML of the youtube video page, and which returns the URL of the mp4 video file it finds within), and then have the caller worry about how exactly to download bytes over the internet, if you think they want to have as much control over the process as you're implying? ...


2

I don't think this is possible, unless you use DirectX or OpenGL. None of existing UI frameworks is designed to support this use case. Games, on the other hand are build on the requirement that screen needs to change quickly and so their frameworks are build around that. My recommendation is to create a DirectX context and drawing area in place of that ...


2

Your first argument regarding reuse of the HttpClient makes perfect sense. As for the rest of of the requests, I think you're trying to optimize prematurely. That can lead to unnecessary complexity. Also, I'd like to warn you of using the static classes. This is usually a bad idea. It makes your code harder to test and extend. Anyways, below is a design that ...


0

Sounds like you are using domain entities for both domain operations (commands, which modify application state) and queries (which don't modify application state, but return data for the user). The problems you describe are a direct result of trying to get that single domain entity to do both jobs, which don't mix very well. My recommendation is to read on ...


0

What are those role-dependent attributes? That's strange for users to have different sets of attributes, since they can change roles in a blink. What will you do with the attributes from role A when user no longer has the role? Delete them? What if tomorrow that user will change his role back to A? So, one approach is to maintain a single overly-bloated ...


0

You are right it is a bit confusing. In the initial .net design, a Delegate was supposed to be a 'method reference' to a single target method, and a MulticastDelegate was supposed to be a container which could contain a variable number of delegates, and invoke them as a batch. However, before the release of .net 1.0 it was decided to merge the ...


2

Does Ninject provide a configuration-file based approach (like here)? I think if you did that the type would be dynamically loaded, and voila! - no dependency in your project. The drawback is that now you have potential runtime failures rather than compile-time ones, but I think that's what you would rather have in your situation.


0

So you have two set of points, a 'target' one and an 'attempt' one, and want to know how close is one to another. What I'd do: For each point in the 'attempt' image, find the closest point in the 'target' image. These distances, averaged, give you an idea how close the attempt image is to the target. Calculate the percent of attempt points where the ...


1

You've gotten some good answers here and on SO to your questions, but you're missing a non-recursive solution. Here's how I went about trying to solve the problem (Note that it is currently slightly broken!): private static IEnumerable<string> GetPaths(int maxDepth, int iterations, string root) { var depths = Enumerable.Range(0, maxDepth); var ...


3

What you encountered is called double dispatch and what you have implemented is some form of Visitor pattern. The problem you encountered is one of the limitations of Visitor pattern. You usually have to choose between inheritance and visitor. When you have one, it makes the other harder. C#'s type and method dispatch system is simply not powerful enough to ...


6

What you are looking for is commonly called mixins. Sadly, C# doesn't natively support those. There are few workarounds : one, two , three, and many more. I actually really like the last one. The idea of using automatically generated partial class to generate the boilerplate is probably closest you can get to actually good solution : [pMixins] is a ...


-1

I just realized, C# has dynamic types! interface I { int Precedence { get; } } class A : I { public int Precedence { get { return 0; } } public R Foo(A a) { return ...; } } class B : I { public int Precedence { get { return 1; } } public R Foo(A a) { return ...; } public R Foo(B b) { return ...; } } class C : I { public int ...


1

Actually this can be relatively simply resolved with the C# trick of using dynamic to do double dispatch. You simply need a method on base class I like: public R Foo(I i) { return (i as dynamic).Foo(this as dynamic); } The viewer can call this, because it knows it has an instance of I. The trick here is that when you cast to dynamic, you always pick ...


0

How should you implement it? You should adopt some convention, like the class made last, gets to implement the behavior and the other one simply forwards the call. Ideally, you can implement them as static methods so that a method and its mirror live next to one another in code. Yes, this means you have to modify the set when they're expanded. Annoying, ...


1

It sounds like your method Foo should not exist in your I subclasses. As you mentioned, with your suggested approach adding a new I subclass violates the Open/Closed principle. Instead, try moving Foo to a new class responsible for the symmetrical operation abstract class SymmetricalFoo<T,U> where T : I where U : I { public R Foo(T t, u ...


-1

What you're looking for is multiple inheritance. However, neither C# nor Java have it. You can extend B from A. This will eliminate the need for a private field for B as well as the redirecting glue. But you can only do this for one of B, C or D. Now if you can make C inherit from B, and D from C then you only have to have A extend D... ;) -- just to ...


1

Your class is doing too much, that's why you have to implement so much boilerplate. You say in the comments: it feels more sensible to write Person.Walk() as opposed to Person.WalkHelper.Walk() I disagree. The act of walking is likely to involve many rules and does not belong in the Person class - it belongs in a WalkingService class with a ...


1

You should split 'getting information' from 'assessing information' You have (at the moment) two sources of info, the USDOT result and the form. I would recomend you compile these results into a RiskInfo object which you can pass to a CalcRisk engine. CalcRisk should be a purely in memory stateless calculation so you can unit test it extensively. I would ...


5

There is a way! You can solve such problems with recursion (https://en.wikipedia.org/wiki/Recursion_%28computer_science%29). In your case it would look something like this (pseudocode): function doStuff(int depth) { if(depth > USER_DEFINED_DEPTH) return; //Do stuff doStuff(depth + 1); } doStuff(0);


2

Separating code into class libraries (ie. seperate assemblies) can improve design because you can manage dependencies clearly - eg. you can ensure the frontend have a reference to the data access layer but not the other way around. .Net allows circular dependencies between classes, but not between assemblies, and circular dependencies between layers should ...


0

.net provides SortedList class in System.Collections.Generic which keeps the list sorted. Your TKey class will need to implement IComparable, or you will need to implement an Comparer for TKey. If my class was to be sorted in the same way each time, then I would implement IComparable, but if I wanted sometimes to sort on same A then B, but other times say C ...


1

Unfortunately, exposing public List Items {get;} breaks the whole encapsulation and protection mechanisms. The using code can just do container.Items.Add and put whatever they want. (which is a problem in the other answer as well). More and more I start to prefer composition instead of inheritance, and when some form of inheritance is needed (to avoid ...


2

The direction where you are going is great. I would make a few tweaks to this design like so: public abstract class Container : Item { private float _MaxWeight; private List<Item> _Items; public List<Item> Items { get { return _Items; } } public float MaxWeight { get { return _MaxWeight; } set { _MaxWeight = value; } } ...


14

Your specific problems are relatively easily solved. Problem 1 is just a syntax issue for how to write methods with generic type parameters. In your case this would be: private List<T> SortList<T>(List<T> aList) It's the <T> after the method name which allows you to use T as a generic type parameter in the rest of the signature ...


7

This seems like one of those common "favor composition over inheritance" scenarios. A RestController serves as an endpoint for REST calls. Not something to govern Authorization. Not something to control the HttpCache. It's a violation of the Single Responsibility Principle. Instead, you should have classes (strategies if you'd prefer) to govern these two ...


1

Your concerns are valid. You're using a strongly typed language, yet venturing into a weakly-typed or untyped area. It happens, but this kind of error/constraint checking you're asking about (if nicely addressed) will increase maintainability by returning you to the benefits of being more strongly typed. What I would probably do is analyze the template to ...


1

It depends. If there is some code above this that effectively enforces that the right variables are sent in (some form for example), then this is unlikely to break frequently, so making each message its own type seems like overkill. If there is not some code above this and you're relying on your programmer's goodwill to make sure that stuff is well ...


5

As Harrison Paine and Brandin suggest, I would re-use the same object and factorize the initialization of the properties in a Reset method: public class MyClass { public MyClass() { this.Reset() } public void Reset() { this.Prop1 = whatever this.Prop2 = you name it this.Prop3 = oh yeah } public object Prop1 { get; ...


3

FooManager is a smell. Managers invariably suffer problems because a "Manager" is a catchall that pushes it towards having multiple responsibilities. I strongly encourage you to not go down that road towards God objects. Singletons are anti-patterns. Always. They force you to only ever have one object of a type, and no such thing exists. You're going to ...


0

Your best bet is probably having a custom validation component built for this purpose. It is reusable once implemented and follows the pattern of validators used for MVC4. Adding Custom Validator for MVC4 To check for the uniqueness: In C#: Get all the input values in the text boxes into a collection. Check if the length of unique values is the same as ...


2

If the intended usage pattern for a class is that a single owner will keep a reference to each instance, no other code will keep copies of the references, and it will be very common for owners to have loops which need to, many times, "fill in" a blank instance, use it temporarily, and never need it again (a common class meeting such a criterion would be ...


8

Given the very generic example, it's hard to tell. If "resetting the properties" makes semantic sense in the case of the domain, it will make more sense to the consumer of your class to call MyObject.Reset(); // Sets all necessary properties to null Than MyObject = new MyClass(); I would NEVER require making the consumer of your class call ...


12

You should definitely prefer creating a new object in the vast majority of cases. Problems with reassigning all properties: Requires public setters on all properties, which drastically limits the level of encapsulation you can provide Knowing whether you have any additional use for the old instance means you need to know everywhere that the old instance is ...


2

The fact that your class is a conversion class, the fact that it is static, and the fact that it expands an existing framework class are all irrelevant. This question is an instance of the more general question of black-box vs. white-box testing. In lack of any very good reason to perform white-box testing, all testing should be black-box testing. ...


42

Instantiating a new object is always better, then you have 1 place to initialise the properties (the constructor) and can easily update it. Imagine you add a new property to the class, you would rather update the constructor than add a new method that also re-initialises all properties. Now, there are cases where you might want to re-use an object, one ...


1

Returning a List<WorkoutHistoryViewModel> feels not as the way to go for me, even though it's done often. Your second option is better, and I think you got this quite right by intuition. You are right though that WorkhoutHistoryViewEntity is not an appropriate name. It could mean almost anything. It's hard to find a name for the Id and the name ...


2

You needn't worry about your ViewModels having more functionality than just providing data. That is, after all, their true function - to provide the data for display and any functionality required by the View. ViewModel's will normally contain properties, ICommands, at least one model and any references to services and repositories required to deal with ...


4

Imagine the following cases: interface IReadable { } interface IWriteable extends IReadable { } class MemoryStream implements IWriteable { } By looking at the signature of MemoryStream only, is it obvious that the stream can be read? Probably not: you may believe that the stream is write-only, unless you know that in that specific business logic, you ...


14

You can still write unit tests. What your question describes is a scenario in which you have some data sources that your code depends on. These data sources need to produce the same fake data across all of your tests. However, you don't want the clutter associated with setting up responses for every single test. What you need are test fakes A test fake is ...


5

The fact that: Some of the logic might make 100+ different lookups. is irrelevant in a context of unit testing. A unit tests focuses on a small part of the code, usually a method, and it is unlikely that a single method needs 100+ lookup tables (if it does, refactoring should be your top concern; testing comes after that). Unless you mean 100+ lookups ...


4

You don't have to test .NET Framework's code in your specific case, because: You can't inherit from Convert class, since this class is static; even if you could do that, for example if Convert class weren't static: The Convert class has no virtual methods, There are no instance methods, There are no abstract methods, You cannot override static methods in a ...


3

This depends on how your conversion class looks like. If it looks like this: class MyConvert { public static Foo1 ToFoo1(Bar1 bar){...} public static Foo2 ToFoo2(Bar1 bar){...} public static Foo3 ToFoo3(Bar1 bar){...} // ... public static Foo1 ToFoo1(Bar2 bar){...} public static Foo2 ToFoo2(Bar2 bar){...} ...


-1

Using both childId and Child property seems to be the worst option because of potential mistakes / inconsistencies. Having only the Navigation property seems best option for several reasons: If the relationship is optional you have a clear indication that there is no child by setting the property to null. In case you have only childId, you need to set it ...



Top 50 recent answers are included