New answers tagged

1

I agree that it is totally okay if a class has only one method, but recently I have read many blogs saying this is bad OOP and rather procedural coding. If a class has only one method, it's usually Execute(), or something equivalent. The question you have to ask yourself is, what are you encapsulating by using a class, if you only have one method? That's ...


2

You are touching upon the difference between an External DSL (a separate language with its own syntax and semantics) and an Internal DSL (a way to creatively design an API in such a way that using it feels like a different language, even though it is actually still bound by the syntax and semantics of the "host" language). You will also sometimes hear the ...


2

This isn't a DSL, it's simply an API. An API provides a set of building blocks for use within the language the application programmer is using. If it's a set of building blocks for use within another programming language that another programmer will be using, it's a set of bindings. A domain-specific language is a newly invented language, usually one that ...


1

First, remove the duplication by moving PrintResult() below your switch. You call it every time (nearly, you'll need to make it a touch more robust I imagine). Then, change your method to return a result instead. This method calculates and prints. It shouldn't, that break SRP. Now, you could create a dictionary of functions to be invoked. var operations =...


-3

You could use http://ncalc.codeplex.com/ Expression e = new Expression(num1 operator num2); result = e.Evaluate()


0

Short answer for your questions: Yes State+Behavior leads to those problems, but this is true for all of OO. The real culprit is the coupling of ViewModels which is a kind of SRP violation. Statically typed, probably. But you should reduce/eliminate your need for instantiating ViewModels from other ViewModels. Not that I'm aware off. No, but having ...


-1

An hour of commenting your code saves a week for those trying to add a feature to an existing code. I haven't seen overly-documented code aside from textbook examples. The thing is I don't know if I should document my overloaded operators, I mean, it is kind of obvious, isn't it? It can be obvious. To the author. For a year. But think about newcomers ...


1

I have a stream parsing method in C# that reads portions of a protocol frame from the STOMP protocol... Can anyone give some examples of processing in a functional manner? You're thinking about this at the wrong level. The interesting question is not "how would I implement this low-level byte-buffer code in a functional style?" The private ...


4

The thing is I don't know if I should document my overloaded operators, I mean, it is kind of obvious, isn't it? Simple answer: Then it won't take you very long to document it, will it? Just do it! Complicated answer: You're writing this documentation for someone to use, not for its own sake. Who are you writing it for? How are they going to use it? ...


3

It's largely a matter of personal preference, although some places may make it a formal coding standard. C itself doesn't care. For my part, if I'm defining multiple functions in a single source file, I will define the called functions before the caller: void foo( void ) { ... } void bar( void ) { ... foo(); ... } int main( void ) { ... ...


1

The best place is somewhere that people can find it. In the middle of a very large file is bad. At the top is good, but others might prefer right at the bottom. Forward declaring main() doesn't help, and is often pointless anyway - because it's very unusual to explicitly call main() from within your code.


2

I think using the switch statement with strings is a terrible idea for the following reasons: Your commands can't take an actual parameter because you've used the CommandParameter to identify the command itself. Your Execute and CanExecute methods become large blobs where it's impossible to tell if you are actually handling all of your commands since you ...


1

The whole idea behind a Command is that it's not specific to a view. You may want to execute the same command from a button on your view, or a menu option, or from a right click context menu, or from a myriad of other UI elements. By creating specific command classes, you gain Single Responsibility and reusability. I wouldn't recommend having your view model'...


1

I think the key thing to consider here is the View im absence of the ViewModel. Ie. In your view you will have bindings for the various buttons etc and you need to distinguish these. Your choices will be bettween NamedCommand(parameter) GenericCommand(name, parameters) I think its fairly obvious where a parameter becomes a command name rather than a ...


2

There is an additional case which wasn't mentioned in the previous answers: mocks for unit tests. A mock can need to implement only a small part of an interface, but to compile, it should declare all of them. The not implemented exception makes then a very clear difference between methods which are actually required by the test, but return nothing or a ...


8

It allows the code to compile for your method stub (regardless of the method's return type), while you get around to putting in an implementation. It also reminds you to put in the implementation, because it will throw the first time you try to MouseDown on that textbox. A thrown exception that says "This method is not implemented" is much better than ...


2

For your specific piece of code, it's very low level, reading bytes from an input and writing them to an output. In C#, this code is not going to be functional. But you can add a wrapper so that you can pass a fake "state of the world" to your non-functional methods and make them return the "altered" state of the world along with your result. The ...


0

When you add a new column to a database table, you will usually either give the column a default or update the current rows in the same script. You're sort of doing the same thing here, just with the extra indirection of having a serialized string instead of a table, it's a little trickier. Many SQL implementations have tools for parsing and writing XML, so ...


0

Actually, the "right" way is to NOT use a factory at all unless there is absolutely no other choice (as in unit testing and certain mocks - for production code you do NOT use a factory)! Doing so is actually an anti-pattern and should be avoided at all costs. The whole point behind a DI container is to allow the gadget to do the work for you. As was stated ...


0

There is no "right way", but there are a few simple principles to follow: Create the composition root on application's startup After the composition root has been created, throw the reference to the DI container / kernel away (or at least encapsulate it so it is not directly accessible from your application) Do not create instances via "new" Pass all ...


1

First I want to mention that you are making this significantly harder on yourself by refactoring an existing project rather than starting a new project. You said it is a large application, so pick a small component to start with. Preferably a 'leaf-node' component that is not used by anything else. I don't know what the state of the automated testing is on ...


0

You say you want to use it but don't state why. DI is nothing more than providing a mechanism for generating concretions from interfaces. This in itself comes from the DIP. If your code is already written in this style and you have a single place where concretions are generated, DI brings nothing more to the party. Adding DI framework code here would ...


8

There are two parts to your question - how to implement DI properly, and how to refactor a large application to use DI. The first part is answered well by @Miyamoto Akira (especially the recommendation to read Mark Seemann's "dependency injection in .net" book. Marks blog is also a good free resource. The second part is a good deal more complicated. A ...


5

.net already uses connection pooling, so when you create/dispose a connection, you are not actually opening and closing a database connection, just fetching and returning a connection to the pool. So you don't really get any benefit by changing to Open/Close, and the using construct guarantees that the connection is returned to the pool correctly even in ...


24

Don't think yet about the tool that you are going to use. You can do DI without an IoC Container. First point: Mark Seemann has a very good book about DI in .Net Second: composition root. Make sure that the whole set up is done on the entry point of the project. Rest of your code should know about injections, not about any tool that is being used. Third:...


-3

is it bad to only be using 1 connection for a small personal program that accesses 1 database (and 2 tables) You should not limit program to 1 connection. Sooner you will end up situations you require more than one simultaneous connections, Built in connection pooling, is reusing connections and will only return connections to pool when you close it (...


0

Correct approach is to use constructor injection, if you use What I'm thinking about is that I can create a few specific factories which will contain logic of creating objects for a few specific class types. Basically a static class with a method invoking Ninject Get() method of a static kernel instance in this class. then you end up with ...


-6

You should use Microsoft Script Control 1.0. It's a COM library. private double MathParser(string problem) { MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl(); sc.Language = "VBScript"; object result = sc.Eval(input); if (result.ToString() == "True") { return 1; } else if (result.ToString() == "False") ...


1

If you're talking about that page, the content is outdated because it deals with Enterprise Library 5, which was superseded with Enterprise Library 6 three years ago. If you read the paragraph just below the one you quoted, it directly answers your question about the alternative: The latest Enterprise Library information can be found at the Enterprise ...


3

Should I just dispense with the binding source and work with the DataTable object directly That at least will basically solve your whole problem. Use your UI labels for displaying things only, not for providing input values for further calculations. What would you do, for example, if you get a requirement to change the formatting of the cost label, to, ...


1

OK, I think I got it but it's a little bit different then the origial builder pattern. If the builder is nested inside the immutable object it then can still access its properties and set them even if they remain private to the actual object: class Foo { public Foo() {} public string Bar { get; private set; } public string Qux { get; } ...


2

Assumed your class is not "too large" (which you should check first), instead of having a huge constructor argument list in FooRepo, you can pass the values in by utilizing a mutable DTO object as a form of "helper object". This might be a class FooRepoDTO, or when you follow the builder pattern, it could be the FooRepoBuilder itself (which must provide ...


6

You pass them in via the constructor. If that means your constructor is too large, then maybe your giant class shouldn't be so giant. There are very few things in the world that have 5+ independent, but cohesive elements.


2

Eric Lippert actually has a piece about this: https://blogs.msdn.microsoft.com/ericlippert/2011/06/30/following-the-pattern/ Eric's explanation: What is required is that the type of the collection must have a public method called GetEnumerator, and that must return some type that has a public property getter called Current and a public method MoveNext ...


3

Edited clarification: while the implementation of the interface is not required, it IS in fact implemented in your example, since you're iterating over an array, and arrays implement IEnumerable in C#. It isn't required. The foreach keyword basically just "rewrites" your code so it becomes a while loop calling MoveNext() and looking at Current, but the ...


5

The official documentation looks straightforward to me: The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface. Note that kai's answer, backed by the C# Language Specification, shows ...


1

There's a UI right there. You can see it has both text and image elements. Though, in the end it's all image. The searchable, selectable, and copyable text you see me typing right now ends up being an image on your screen, though unlike the image above it's sent to your computer as text. Your computer converts it from text to an image to put it on your ...


1

Database enums are for situations where something is necessarily hard coded. The enum creates a binding between the database data and something that is hard coded into the source code. Don't think of that as meaning that they are never useful, since there are situations where this is acceptable and necessary. Rather, don't use an enum unless you have this ...


0

In a functional language like F#, you could take advantage of partial application. That is, FuncLevel1 only has one function parameter, FuncLevel2 and it already contains FuncLevel3 inside it: let funcLevel1 (funcLevel2 : int -> int) (param1 : int) (param2 : int) : int = let result = funcLevel2 param1 + param2; result let funcLevel2 (funcLevel3 :...


0

There are quite a few reasons to selectively disable compiler warnings, even for projects which strive for best practices. Different Compilers (or different versions of the same compilers):Compilers handle warnings in subtlety different ways. Giving false-positive warnings that don't impact other compilers. In this case it might make sense to disable the ...


-1

You can have the best of both worlds by overriding the behavior HtmlEncode. This is accomplished by overriding the HttpEncoder class like so: using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Util; using System.Text; using System.IO; /// <summary> ...


1

For the most part rule Preconditions is validation. With the approach of keeping validation outside of Rule action and execution flow you will get: You will be able to reuse Preconditions. - In most cases it's a useless flexibility. Moreover usually you will have rules only with one precondition and one rule action. There will be a problem of sharing data ...


5

An example in C that I encounter variants of regularly: int doSomething(int argument1) { #ifdef HARDWARE_TYPE_A performAction(argument1); #else displayNotSupportedMessage(); #endif } The argument is only relevant on some platforms, but on the ones where it's not relevant my compiler will complain, and since I have warnings converted to errors it ...


0

The best advice is to not use HttpUtility.HtmlEncode. The problem is that this returns a string, which means that the type system cannot catch encoding mismatches. The best solution is to have an HTML struct that represents strictly and only HTML, and then use instances of this to represent HTML, rather than strings. Then the compiler can assure you that ...


2

Assuming you will call HttpUtility.HtmlEncoded() from your extension method (otherwise it's a no-no) and also that you will use a meaningful name to your method (otherwise you will just make code less clear). Given: string someText = "This is some text"; Let's compare: string htmlEncoded1 = someText.ToHtmlEncodedString(); string htmlEncoded2 = ...


5

Polymorphism with no shared interface will ONLY let you store objects in the same (strongly typed) container, not actually DO anything. You can't disptach method calls or anything like that. In your specific example, I think composition would be more appropriate, no? You already have an abstraction for a specific point in 2d space, so why woudn't you reuse ...


2

The two subclasses does not have any interface in common, so why you do you want to have them inherit from a common class in the first place? The Location class does not provide you any benefit as far as I can tell. To me it would seem to more logical to have the Line contain two Point's.


6

To expand on my comment I will give you my opinion on your code : Generics : I believe there is thin line between cases where generics are useful and cases where they are abused and only bring more problems. Yours is way past into the problems area. Just looking at the big generic definition rings an alarm for me. This is augmented by fact that you have ...


4

You could probably have a look at Rules Design Pattern. There is a good video also at Pluralsight, see Rules Pattern (you will need to sign in).


0

If class Foo has a private member, such as public class Foo { private int _bar; } Then _bar is accessible from within any instance of Foo. public class Foo { private int _bar; public bool MatchesOtherFoo(Foo other) { return _bar == other._bar; } } You couldn't access _bar from another class, but you can access it from other ...



Top 50 recent answers are included