New answers tagged

0

I believe the answer lies in MarioVW's StackOverFlow response to: Practical Example Where Tuple can be used in .Net 4-0? With tuples you could easily implement a two-dimensional dictionary (or n-dimensional for that matter). For example, you could use such a dictionary to implement a currency exchange mapping: var forex = new ...


1

I don't see this as a question of technical pros and cons. It depends on the lifecycle of a HouseCleaner, what it is semantically, and how it relates semantically to a House. Suppose you were dealing with a Car and a Wheel. It wouldn't make a lick of sense of re-inject Car into Wheel into each other every time the Car needed to move. The Car simply has four ...


2

There are arguments for both. The choice as it is said "depends". The first approach can be scaled, because you can create many instances of service (i.e. multithreaded service) - but the service must be lightweight. The second approach on the other hand is better suited for "fat" services that take time to instantiate. It is better to share them. As for the ...


3

This has nothing to do with ObservableCollection and everything to do with WPF. WPF requires all changes to be done on the UI thread. But WPF doesn't dispatch the changes onto UI thread when collection changes, unlike with property change. You can work around it either by dispatching the collection change onto UI thread using WPF's Dispatcher. Or you can ...


1

Covariance and contravariance are not allowed in any class. As abstract classes can have concrete implementation, this applies to them too. The short answers for why is that (a) the CLR doesn't support it and (b) it doesn't support it, because (for covariance): [a class C<T>] cannot have any method that takes a T, any property of type T with a ...


0

Please let me know what the best practice in such a situation is. I don't know about "the best practice", but it sure sounds like the state design pattern. Quote from the link: Intent Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. An object-oriented state machine wrapper + ...


5

Besides the fact that in your current state the code would not work, because dum would be null, you cannot mock a private attribute of a class unless you have an access to it using some public method. How to do it? 1. You need to change the Class1 class signature so that the IDummyInterface1 is passed as a parameter, be it in a constructor or a method ...


0

Assuming that you're deserializing from the xml response and serializing from the objects themselves here is a model that may work for you. public abstract class FooMessage { [XmlIgnore] string A { get; set; } [XmlIgnore] string B { get; set; } [XmlIgnore] string C { get; set; } } public class UpdateFooRequest : ...


1

TLDR It depends on how configurable and extendable you want to have the reusable library (project), without touching it. In the end you either have factories in the library itself, or the library does not have them and the client (the user) of the library is responsible for creating them and instantiating the library himself. Longer answer No matter ...


4

Regular expressions work on strings, not on a "string list" and not multiple string lists. Wherever you need to process more than one string, you will typically need some environmental code to do the processing. For your example, this code has to apply the regex to every element of the first list, then collect the results and use this results to process the ...


2

When an API uses an abstract base class, the (only) way to provide a version of that API is to subclass the abstract base class. Because in C# and Java we can only have one super class, it is, in some sense, a scarce resource. Requiring that each API implementer subclass from that abstract base class means they cannot subclass from a class of their choice. ...


2

Besides not being able to use multiple inheritance, as Robert Harvey has pointed out, when using an abstract class, you usually do so to group common behaviour of children of this supertype together, respecting the DRY principle. But by doing so, you are sometimes introducing more data to the class than the single interface would probably need for it to ...


6

You can't use multiple inheritance with abstract classes.


3

Both approaches are reasonably common. They even have names: This is a client-server architecture. Sometimes called "thick client" because the application's business logic is in the client. This is a three-tier or application-server architecture. The business logic is in the application server. If I were designing it myself, I would use an ...


3

It is a clever hack, but still a hack in that is abuses a feature for something which it is not the intended purpose. Hacks have a cost in maintainability, so it is not enough you can't find any other drawbacks, it also need to have significant benefits compared to the more idiomatic way to solve the same problem. The idiomatic way would be to create ...


6

It's a great idea to create type for every identifier kind, mainly for the reasons you stated. I wouldn't do that by implementing the type as enum because making it a proper struct or class gives you more options: You can add implicit conversion to int. When you think about it, it's the other direction, int -> CustomerId, that is the problematic one that ...


4

As long as the new Logger class does not contain more code, the example seems to be contrived. But imagine that class gets some more methods, with code which is independent from the concrete IMessageLogger, for example: public class Logger { // ... public void LogFormatted(string formatString, string[] parameters ) { string message = ...


1

You need Dependency Injection - having the IDbConnection injected to your classes. Here are some quick benefits come to my mind: You only specify the connection parameters at one place - when the IDbConnection gets registered. You have the option to replace IDbConnection with SqlConnection, SqlCeConnection and etc. You have better control over transaction ...


1

The way I normally structure applications is to have all the database access in one DLL (module for other languages). All the data access methods take a connection string as a parameter (in the case of EF its a bit different but still gets passed in based on the connection string in the app.config or web.config of the primary application). This way the DAL ...


0

Usually the database connection information is in the .config file for the project, and your database accessing classes will read it into a local variable. Use the .NET System.Configuration settings to read the information from the .config file using nice, Microsoft-built libraries. Depending on how centralized and how you access your database classes, this ...


4

Which one is efficient? depends on your definition of efficient and on your data: Which kind of efficient do you mean: "less processing time", "less memory consumption", "less hours needed to implement or maintain"? I assume you mean "less processing time". The answer depends: if database contain 1 million rows and XML contain only two rows the first ...


1

In my opinion gathering(i.e. getIp) and processing (i.e. setEmail) should be handled in different classes the ip gethering belongs to a log-service that has knowledge about runtime, environment, context, session.... the processing of the log-infos belongs to a different logging-persistence class that has a similar interface as a write a only repository and ...


-1

The "factory" class with lots of static CreateXXX() methods is misguided. There are cases where some (OTHER) form of factory is useful. For instance I use factories to enable mocking object instantiation for unit testing.


4

Your coworker is incorrect. When working with UI logic in MVVM, it's common to have properties for binding that are derived from other data. In these cases, you don't want to create another private member - that just adds a point of failure with no benefit. Side note: If you're using C# 6 then instead of hardcoded strings you can do ...


3

Getters like your colleague expects, are a code smell. They're only there for language niggles anyway. What they're doing is exposing a private variable. To be honest, you might as well just access the private variable directly if that's all you're using getters for and cut out a layer of middleman. Originally OO languages supported the use of accessor ...


1

From my POV, the idea is good. The intention to give different types to unrelated classes of identifiers, and otherwise express semantics via types and let the compiler check it, is a good one. I don't know how it works in .NET performance-wise, e.g. are the enum values necessarily boxed. OTOH code that works with a database is likely I/O-bound anyway and ...


-1

You cannot do this, enums must be predefined. So unless you are willing to pre-define the entire spectrum of possible values of customer ids, your type will be useless. If you cast, you would be defying your primary objective of preventing to accidently assign a type A id to a type B id. So enums are not helpful to your purpose. This does bring up the ...


0

You are not forbidden to inherit from concrete classes, and certainly shouldn't make all classes sealed, doing so would likely lead to violations of the Open-Close Principle (OCP) down the road when you realize you need to inherit from a class. As long as your concrete inheritance hierarchy does not violate the Liskov Substitution Principle (LSP), and that ...


0

In Dependency Inversion Principle you should seperate interface (for consumer) from concrete implementation. So your implementation of FontList : ObservableCollection<string> is perfectly ok. (it is just an implementation detail) On the other side the consumer of your class should only need to know (or depend on) an interface (i.e. ...


0

Application of DIP should be selective. That means you pick which dependencies you want inverted. Applying DIP increases complexity. So you should employ your software design expertise to choose where this increase in complexity pays off and where not. Also, the book from these rules come from itself says those are not hard rules and they can be violated : ...


4

There are some reasons which can make this design the better alternative: GenericHelperClass ghc = new GenericHelperClass(); // ... // using `ghc` here for other purposes //... ProjectSpecificClass psc = new ProjectSpecificClass(ghc); if the construction of ghc is slow or needs lots of resources, it might be better to construct the object only once if ...


1

My own thought on these sorts of helpers are in effect filling in lacuna in the standard library. They should therefore be held to the same sort of rigorous standards that the standard library is held to. Particularly if this helper class(es) is being used in multiple project, it is essential to validate it with extensive testing. Just as the presumed high ...


0

Interfaces that only carry properties should be avoided since : it obfuscates the intent : you solely need a data container it encourages inheritance : probability that someone will mix concerns in the future it prevents serialization Here you are mixing two concerns : summary as a data summary as a contract A summary is made of two strings : an id ...


0

I would consider using an interface for Vote instead of genetics. That way if you had something like: interface IVote { // your interface requirements } And then on your class definitions implement the IVote Interface: class PolicyVote : IVote {// class def. } class FundingVote : IVote { //class def } //etc. You could then avoid casting to ...


3

In C# you can use ReaderWriteLock class to allow a single write operation in your file (and multiple readers, if this is needed). Also, to maximize performance you can have asynchronous operations using Asynchronous File I/O (you can have some processing while the I/O operations are being done). However, before diving into these concepts, some things must ...


0

The described scenario is actually a really good fit for doing exception handling correctly -- to stop a process and recover from exceptional errors. Exceptions should bubble up, to the first place where you can continue intelligently, taking a new direction in light of the error. Don't be afraid to let that be all the way out of the application. You can ...


1

You're looking for AutoMapper. Lose the inheritance though and duplicate the properties in the ViewModel. Inheritance, especially in this case, will bring pain. Use AutoMapper to handle the assignments automatically, that's what it's been designed for.


1

This is the preferred method of extending the EF data classes. You can add almost anything. I had a situation where I needed to use different annotations (replacements for the validation, as the defaults weren't sufficient for my needs). Microsoft provides plenty of examples to do this.


2

Working on a C# Server with SQL Server and PetaPoco, this is the approach we took to clean-up data in Unit Tests. A typical unit test would have Setup and Teardown as follows: [TestFixture] internal class PlatformDataObjectTests { private IDatabaseConfiguration _dbConfig; private Database _pocoDatabase; private PlatformDataObject _platformDto; ...


0

The most simple solution is to have a loop that goes in granulity of 1 second and checks if there is some profile to update, by checking time of it's last update ( should be set in .update() method of profile ) and it's interval. Example pseudocode: while(shouldRun()) { var startTime = currentTimeMiliseconds(); for( var u : Users ) { if( ...


1

I recommend you look at quartz.net which will help you with the scheduling part of the app. I tried my own scheduling and came unstuck very quickly. You can then focus your efforts on the logic of the app itself.


6

Besides the fact that this is an integration test as opposed to a unit test, the operations you describe typically go in Setup and/or Teardown methods. Frameworks like nUnit allow one to decorate class methods with these attributes to indicate whether the method is a setup method or teardown method. Then your tests should become cleaner and smaller as the ...


0

Assuming you are using .NET, mentioning C#, I would look into data binding features first. Most UI toolkit Microsoft has made offer some form of data binding either to objects, object lists or ADO.NET datasets. Mixing your data retrieval with your UI controls is never a good idea, I would try and keep this external to your user interface.


4

The big problem with databases and (unit-)tests is that databases are so darn good at persisting stuff. The usual solution is to not use an actual database in your unit-tests, but instead mock the database or use an in-memory database that can easily be wiped completely in-between tests. Only when testing the code that directly interacts with the database, ...


7

The point that you should be aiming for with such tests is that as many of them as possible should be interacting with a mock of the database, rather than the database itself. The standard way to achieve this is to inject a DB access layer into the logic you are testing here, using interfaces. That way, the test code can create in-memory data sets prior to ...


4

Do they load all the program code into the memory on application startup? NO You can have as many Assemblies in your project as you need. Assemblies are referenced via the using keyword. Unused assemblies are filtered out at the build time itself. For example, you can have two referenced asssemblies as: using System.Windows.Forms; using ...


2

Primary Constructors would have helped, but they were pulled from C# 6. You could use certain IOC container black magic to make it look neater. But neither remove the underlying problem: your class is awkward because it has a bunch of dependencies. If it has a bunch of dependencies, it's probably trying to do too much, since few problems require 4 ...


2

I think you listed the differences very well in your answer, however I'll add my some of my opinions on how I view the two approaches. AAA is very useful for me when I'm testing my own code. If I'm working on a project or a library for myself, AAA is the way that I go. It lets me set up whatever I need to execute my test and then just test it. It's ...


1

Interfaces are required in good quality implementations of MVP for the same reason they are required in all good "OO" designs: They help reduce coupling They discourage inheritance (which further reduces coupling) Arguably most importantly, they simplify unit test writing



Top 50 recent answers are included