New answers tagged

1

The name of that particular anti-pattern is procedural design. In short, you are separating data from behavior, which arguably disqualifies this kind of design from being called object-oriented at all. More importantly it pushes the responsibility to handle these data things right to the caller, which is exactly your problem. The way to fix this, is to hide ...


2

The general relationship you have between your classes (0..1 User to 0..1 Thing) is a perfectly valid kind of relationship. It's less common, but valid in the right situation, which this seems to be. However, you need to be very careful here. Your current setup creates a lot of room for contradiction. Part of this is because you store this information twice. ...


1

One way to ensure consistency of circular references such as this is to implement idempotent set/unset operations which call each other recursively unless the target condition is already satisfied. I don't speak C#, so please accept pseudocode: class User { public Thing curThing; function setThing(Thing aThing) { if (this.curThing == ...


6

Whenever you have tightly coupled objects with circular dependencies, you have one of three cases (in an order of likelihood that I just pulled out of thin air, but sounds plausible): You are missing an object, and the two objects are actually three objects. The two objects are actually one object. The business domain you are modeling is indeed circular, ...


1

Whenever I modify one of them, I often need to call a corresponding function in the other class. If I am not careful about which functions call methods in the other class, I can end up with a stack over flow. When reading this, my first thought was that User and Thing really should have been one class, but that then doesn't match with moving a Thing ...


1

Language Integrated Query (LINQ) What is a query and what does it do? A query is a set of instructions that describes what data to retrieve from a given data source (or sources) and what shape and organization the returned data should have. A query is distinct from the results that it produces. LINQ is the answer to my question. LINQ allows developers to ...


0

async + await don't just make an asynchronous call and wait for the result to be delivered, that would indeed be synchronous. That would happen if you created a semaphore, launched a new pthread for example that signals the semaphore when it is finished, and then wait on the semaphore. But async + await as part of the language is different. What it does is ...


-1

Divide and Conquor Split the first set up into batches. { 1: [5,4] //<batch 1 2: [4] //<batch 2 3: [10] //<batch 2 } Use an appropriate parallelisation technique (tasks, thread pool, etc...). Each of the batches have the same sub problem. Apply a standard double for loop and construct the index. // batch 1 { 4: [1] 5: [1] } ...


0

The expected result is not a good candidate for a class since the data is static and there can be no valid objects made out of it( It cannot be seen as a valid blue print). This is actually a limitation of C#. Everything must exist in a class, struct or enum. If all members are static, then make the class static. The class is needed simply because you ...


1

Your points One thing you may have glossed over, which can change your outlook on things, is that const values are inherently static. While they each serve a different purpose, there is some similarity in why you can justify the use of static to list some fixed values, effectively using it in the same way you'd use a const (but with less restriction on its ...


2

What I've often done for large objects like this (which should be avoided if possible, but can't always be avoided) is to dump the object into a JSON file (you could of course use any handy/useful serialization format, but text-based is preferable as you can read the diffs in source control). The test method wouldn't look much different other than a call out ...


0

I'm thinking Method 3 - Store the location in a cookie: Although I do think the connection information is within the domain of your server I agree that network configuration and DNS is a separate domain from both client and server side of your web app. And as Ewan points out, tying your functionality to this my not be a good idea. What if you tried to deploy ...


5

Naming ILogin is an abstract interface for different login strategies, so better call it accordingly public interface ILoginStrategy { Task Login(); } Inheritance By better naming, the correct usage of inheritance becomes clearer: a Site has a login strategy, but it is not a login strategy by itself. So don't derive Site from ILoginStrategy,...


1

One possibility is to create a third class: class SiteLogin { } class LoginStrategyA : ILogin { public LoginStrategyA(SiteLogin siteLogin); } class Site { public Site(SiteLogin siteLogin, ILogin login); } Everything that LoginStrategyA needs to access should be extracted to SiteLogin. That way both Site and LoginStrategyA can access it without ...


2

If the device has GPS and the browser supports the geolocation api you can use that. If not I would use a cookie and have the site ask the user to select the location, either from a dropdown of known locations or enter a postcode etc. Have javascript check the cookie and prompt for location if its missing. Prevent the user from using functionality without ...


6

Note that Microsoft uses [Pure] exclusively in the context of Code Contracts (as opposed to, say, optimizing code during compilation or runtime). In this context, if the method doesn't make visible state changes, the method is pure. As simple as that. When Code Contracts were introduced, the [Pure] attribute was added sporadically and sometimes ...


2

At What Level? The perennial question. What is the lowest level with reasonable access to all that information? What is the highest level where such an implementation isn't too detailed? Generally that would be the repository as it stores all that information, and is usually defined in terms of relational logic. So it should fit right in. Personally that ...


9

Things declared const are true compile-time constants, and thus may occur in constant-expressions. This means you can use them in the following contexts, where static readonly variables may not appear[1]: Values of other constants: const int OTHER = N; Explicit values of enum members: enum Foo { Bar = N } Default arguments: void Fn(int i = N) case labels: ...


0

This is a matter of preference. I do not like auto properties much, it leads to unnecessarily obscure code. I do use them sometimes but only for the most basic DTO-type of classes. My problem with them is that the data members of a class are no longer guaranteed to be listed first. If you apply StyleCop you can be sure all data members will be the first ...


0

If you are trying to keep your code as clean and abstract as possible, you will find that, most of the time, when you have a setter, you will want to define your own backing field (or you will wish you had, at some point). Do you need to validate something in your setter? The only way you could do that is by having your own backing field, to make sure you ...


5

property with a { get .... ; } and a backing field a property with a { get .. ; private set .. ; } Note that your bullet points aren't quite correct. If you're using an auto property (i.e. not having an explicitly defined backing field), then the second bullet point's getter and setter should not have a body. Once you explicitly define the body of the ...


3

In general, you should only explicitly declare the backing field if there is some reason you need to. Things like playing nice with some existing base class, or working with reflection code that expects a field, or if you want readonly (set on initialization) behavior but don’t want to implement that by hand, or your setter is nontrivial. The language didn’t ...


1

In this specific case, it sounds like you just need a post-processing hook. In its simplest form, it could look like this: class BaseClass { protected virtual void PostProcess() { //No code, do nothing } public void Run() { //Do Task 1 //Do Task 2 PostProcess(); } } class A : BaseClass { ...


0

If there should be separate methods for adding postcards, books and so on depends on the business context of your application. Go back to the business requirements and see if: Adding media items is a primary or a side activity/requirement for the users Media of different types are explicitly distinguished- for example is there a business requirement stating ...


2

is it architecturally correct to "merge" the client and server API's into a single assembly? I wouldn't do that. Having interfaces and necessary information in common (by which I'm assuming communication protocol and data transfer objects) does not mean that clients and server are strongly coupled, unless they share the code that does the logic or ...


1

You can achieve very easily the feature to register types from a configuration file: modulesettings.json: { "Dependencies": { "A.Namespace.IServiceType1, A.Dll": "Another.Namespace.ImplementationType1, Another.Dll", "Still.Different.Namespace.IServiceType2, Still.Different.Dll": "Namespace....


2

In .NET option 2 is the way to go. Option 3, although creative, only adds complexity in my eyes. The only reason to do something like that would be if setting up an instance of MessageSender would be expensive in some way. But then the less astonishing option would be to externalize the setup and pass an object that has the expensive stuff in it to ...


1

Lets say i have a zoo class, with a bunch of collections. That's it, you're already on for a wild ride if you go that route. Do you have any good reason to model your repository (or the abstraction thereof, at least) as an in-memory abstraction? Have you considered Query Objects (see also here)? Edit: I don't like the just make an animal collection ...


4

You want the Template Method Pattern. Basically you have run() calling another method (called say stopService()) which implement task3-behavior. Instead of overriding run() in the subclass B you just override the stopService() method to implement task4-behavior instead.


2

To elaborate on Frits's answer: only consider inheritance if it makes sense to say "A is a B" or "B is an A" or "A and B are both C's". If none of this is the case but you still see repetition that can be generalized, create a new class named ServiceUtils or something like that and move your shared code in there.


3

There is a lot of misunderstanding about 'DRY' and 'reusability'. When a developer sees some code that seems to do the same thing, or is a duplicate, the first thought is often: "that has to be refactored". But that is not always a good idea. This code is a good example of that: there are some methods in two different classes which are the same, ...


2

The trouble is your animals are modeled with polymorphism but your stores are not. If an animal would get a reference to its store at construction time, the animal could have a Delete method that calls this.Store.Delete(this.id);. If you do not want animals to delete themselves or have that reference, you can have your animal manager call Delete on the ...


1

My approach here would be to maintain a single collection of IAnimal and a single Zoo.Remove() method. Then when you need just the elephants, have Zoo.getElephants().


6

The comments by Rik D and amon already point out two possible solutions that come to mind: If all items are instances of subclasses with a common superclass or interface, why keep them in separate collections? You might put them into just one and use predicates such as isTiger() to filter when you want to handle the tigers only. If these are fundamentally ...


2

Enums are generally okay, they serve a meaningful purpose to represent a data type that can only take a limited number of concrete, possible values. The two major problems with enums are: They are often used in situations where polymorphism would make a lot more sense, would be easier to extend and would lead to more stable and easier to maintain code. If ...


2

This pattern is fine as a repository, because the whole point is that the datalayer is separated, so you can use EF or whatever you like internally. However, In order to keep EF attributes out of your business class you'll have to write a mapping layer for any complexities of your objects, such as keys and relationships that don't follow the default. Once ...


1

Repositories and EF This is a topic that a lot can be said about, but I want to keep it short here because I want to focus on better solutions. The short answer is that the repository pattern doesn't mesh well with Entity Framework, because EF itself is already an implementation of the repository pattern. The DbContext is a unit of work. The DbSet<T> ...


Top 50 recent answers are included