New answers tagged

1

In my opinion, if using if (!condition) is any less readable than if (condition == false) then you have other problems with your conditional statement which you should work to resolve. The ! negation option also cuts down on visual clutter. Extra == false comparisons in the conditional increases the number of tokens you need to visually process, especially ...


-1

Why would you refactor something that is working and correct into something else that is working and correct and roughly equivalent? Where is the customer value? How does it align with the company goals and architecture vision? It's fine to have agreed upon coding standards. They are not an imperative to apply to existing code. Don't you have real work to ...


2

This is not a question where you will get a direct answer, because both work. Most people will tell you it's a matter of taste. My personal opinion is: Don't lose sight of the end goal readability. My Favourite in a Perfect World I prefer to write code that's "small and easy"; simple statements that are rather short. I prefer to use ! in that code: if(!...


0

Another opinion - use right tool for the job - take one from both options. For true condition if (approved) { callMe } For false condition if (approved == false) { callMe } The reason for using approved == false for is false condition only because it clearly stands out in comparing with true condition if (approved). But because the way we read code ...


3

Personally, I prefer if (condition) or if (!condition) to if (condition == true) or if (condition == false), because the latter two look like someone did not fully understand how if- (and other) conditions work. Beginners often think that there must be some kind of comparison in an if-statement; however, this is not the case. What these kind of statements (...


1

Floating point numbers are simply not suitable for storing exact but arbitrary numeric values; every floating point number is just an approximation of a numeric value. Sure, some numbers can be represented exactly as a floating point value but many cannot and then you will have an error that can vary a lot, so it's better to always treat them as an ...


3

Using single precision float for money is fatal. Float has only 24 bits of precision, so if you are using dollars, then anything above 2^18 dollars has a resolution worse than one cent. So anything above $263,000 or so has big problems. Using double precision is much much less of a problem. If you have an amount of one trillion dollars in double precision, ...


3

You're right in being concerned about the use of floats for monetary amounts. Unless they are just used to calculate something which is then properly represented as a rounded scaled decimal (or an integral number of cents, which is equivalent,) they shouldn't be used to represent money. However, the damage that could possibly be caused is very dependent on ...


-3

To my gut feeling, double precision should be quite good for most practical cases. I don't risk to evaluate any numbers at the moment, but I think there is very good chance the errors would be negligible small for any decision making. What can be an issue is that there may be a few cents (or whatever your currency units) in an audited results, like ...


0

I used the ideas, especially the one proposing to centralize all the feature dependendent things, which I consider very important in a very large codebase (> 1Mio LOC), to create some sample code, which shows a possible approach. namespace Module1 { public class Input1 { public int Param1; public int Param2; } //Describes an ...


0

Assumptions: You have a sound architectural vision for moving from the monolith to micro services A lot of these micro services are processes that has a life cycle and are long running These micro services need to know when a configuration data entity/attribute is changed, but they do not change configuration data. I would suggest that the primary IPC (...


1

Calling methods in getters and setters is a dangerous practice. It can be acceptable for minor things in some cases, your example is a good one of an acceptable case. The reason it's a dangerous practice is because it exposes object state outside the object and moves the reasoning of that state outside the object as well. For extremely simple cases it can be ...


3

Turning this comment into an answer as OP accepted it as a viable answer. I'm unsure about your reasoning to avoid Thread.Sleep (as per the comments on the answer) Are you expecting to run multithreaded? If no, then your single thread will always block for a second, regardless of how you do it. If yes, then sleeping one thread will not impact the other ...


1

If I understand your question correctly, you want to filter a list based on the next item in the list instead of the item itself, i.e. in pseudocode: if(items[i] == stop && items[i + 1] == start) return items[i]; This question focuses on how to observe the previous item, but it's essentially doing the same thing and can be tailored to your ...


0

In C++, if you have a static instance of a class, and exit the application, the destructor for the class will be called, possibly while the static instance is still running other code, with possibly fatal results. I would avoid static instances especially when timers or anything multithreaded is involved.


0

I've read you mention the codebase is legacy. I came up with a workaround. Since this operation is inside of a Thread. Thread.Sleep could be another way for waiting one second, and you don't have to deal with timer. Sorry, I can't comment it for less than 50 reputation.


1

To avoid changes in many places, there are some strategies: The obvious one: Put as much of the feature specific code in one place. The other obvious one: Choose behaviour by picking the right class, not by using a switch statement. Less obvious: Have a list of features that is calculated once. Then your code shouldn’t do things for feature A, then B, ...


2

It's hard to give a concrete answer without the actual code but from experience I often found that I could make the database and the UI work transparently for both with and without the new feature. So I would prepare the database (add a table, column, view, procedure, ...) by ADDING functionality and still supporting the original functionality. (Don't ...


0

I have been running scheduled tasks in the background as part of an ASP.NET Core web app in production for a year now using FluentScheduler (https://github.com/fluentscheduler/FluentScheduler). It's handling 8-12 jobs all running on different schedules (every few minutes, every day, etc.) and haven't had too many issues. I have also heard good things about ...


0

I have heard excellent things about Hangfire, though I haven't used it for anything big myself. It can be used to run delayed and scheduled jobs. It works with SQL Server, Redis, PostgreSQL, Oracle, MySQL, Firebird, and others.


0

If you are on MS SQL Server, it comes with it's own scheduler called Agent which can run SQL scripts on a schedule. To run any program, Task Scheduler comes with Windows and is perfectly fine. You'll have to remember to deploy the task with your web application, but this is scriptable, so there should not be any insurmountable problems. I'd probably use a ...


0

I don't see why you see RabbitMQ as a broadcasting solution, RabbitMQ is a Messaging Bus. I think it's a very good solution for inter-service communication. For a configuration service, why not use Observer Pattern where your apps read the initial configuration and then be notified whenever a config change (that matters to them) occurs


2

May i suggest using gRPC. It's relatively easy to build services with it and you get a lot of benefits: you have a strong api contract and strong api governance as the api spec is put apart from the code you can generate client/server code in many languages it's well supported with current asp .net core technology One word of caution, think twice before ...


0

Before we discuss the proper way to model your problem, we need to remind ourselves that DDD is about focusing on the behavior our system is to exhibit. Unfortunately your question above takes a very data-centric perspective, and as a result makes synthesizing a solution more difficult for all parties involved. That is, it is still unclear to me what you are ...


3

I know ReadAsync creates a Task which is handled by a Scheduler on the ThreadPool and therefore is guaranteed to not block, but then I read about C# delegates and Begin/EndInvoke which allow "any synchronous method to be asynchronous" Is this true? Yes, ReadAsync will not block, and yes, it will use the thread pool. And yes delegate.BeginInvoke and ...


9

Unit tests don't care about internal state I have created a class that implements behavior which is difficult to test without some intimate knowledge of internal state. This is a contradiction. When talking about testing, behavior is specifically defined as public behavior, i.e. what is externally visible. Internal state is pretty much the exact ...


2

I'd first and foremost wager even as a starting point if this is the right way to go about it. It feels to me that you are trying to "force yourself" to unit test a flow that probably isn't directly linked to any "unit" (read, function) and thus, should not be unit tested to start with. If it'd be me, I'd find a way to re-structure the design so you can ...


1

If it's possible split ComplicatedThing into smaller Thing's which will expose these states for tests.


1

It's OK to pass things that, depending on state, might not be used. Consider for a moment a multiplication method: x.multiply(y); This method returns x * y where x is some object that was constructed with an int that it now holds. Which means this will pass: assert(new X(2).multiply(2) == 4); So far this all seems reasonable but what happens when it ...


5

Decorate your class under test with the InternalsVisibleToAttribute, citing your test assembly. Your tests will have access to the class's internal members, and you won't have to pollute your API with irrelevant details.


1

two components should only communicate with one another via an interface. Interface includes not only some methods, but both return and argument types. In ideal engineering world it could be written as public interface SomeInterface { public enum Status { Success, Failure } Status CallAPI(string s); } so enum become part of ...


2

If understand your question correctly, you have a list that needs to contain two types of objects which perform work. However, the methods for these two types differ in their arguments; one requires a single input (ul_data) while the other can do the work without any inputs at all (to wit, because it obtains the data from somewhere else). In other words, ...


0

I like the Flater's answer and Martin Maat's comment. But I think the answer should have more specific rules. So I’ll try to explain how I understand it. Let's divide properties and methods into categories: Action (imperative verb) - it allows us to say object do something. SetValue(value), GetValue(), Initialize(), Dispose(), Play(). Statement (third-...


1

Flaters answer, whilst correct for the question, does not really solve the general issue. What if you want to implement the same pattern but with a strongly typed 'message' instead of a string? E.g. IOperationResult becomes IOperationResult<T>. What if you want to project this 'message' to a different type once it's wrapped in the generic parameter? ...


0

You should expose what you need to in order to do what you want the class to do. Anything else is at best gold-plating, and at worse overwhelming the consumer with extraneous details. As an example of the later, it’s pretty unlikely that a user of your FooRepository will need to know what logger you are using, but that’s something that gets injected into a ...


1

You can write a unit test to find all implementations of an interface, and run a test against each of them. var iType= typeof(ISomeInterface); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => iType.IsAssignableFrom(p)); foreach(var t in types) { var result = t.SomeMethod("four"); Assert....


4

I'm the first one who usually jumps in to say that there isn't just one true way (TM) to organize software. The agile phrase to describe it is you have to build your Minimum Viable Product (MVP). From there you can build on what you have and refine it and adapt it to your full complete needs. Experience has taught me a few things along the way, like first ...


45

The calling code which instantiated a FooRepository object is passing an IDbConnection object and therefore has the right to access this information later on This is not true when you're dealing with things like the factory pattern, where the instantiator of the object is not the handler of the object. Factory patterns quite often exist specifically ...


1

To be more precise at the valid values: they have to have 5 or 6 digits. The first 4 can have any value between 1000 and 9999, the remaining digit(s) are either between 1 and 4 or 1 and 12 Given these requirements, one way to solve this specifically with C# is to use a struct, but to take into account that all types in .NET are zero-initialised. To work ...


9

You coworker is right. Internal state should be encapsulated by default and only exposed where there is a good reason to. So when in doubt, hide. Should I really think for each parameter if it makes sense to expose it? Or is there a design pattern I can just instinctively apply without wasting too much time? Just hide them all by default, that is the ...


6

Think about why you are creating a repository in the first place. You're trying to abstract the concept of persistence so that clients don't need to know how data is stored. You do this so that you can shield clients from future changes to the persistence mechanism. Exposing a DbConnection from your repository makes it part of your public interface. You're ...


2

In a comment, you wrote with a struct I didn't need to explicitely implement equality and I didn't have to do null checks. Therefore I'd prefer a struct. If the requirement is just to wrap an int, implementing equality in a class should be pretty trivial. And for avoiding null checks, I think your best bet is to use the new C# 8.0 feature "Nullable ...


1

It doesn't have to be complicated: public interface ISomeInterface { // Returns the amount by which the desired value *exceeds* 5. uint SomeMethodLess5(string a); }


12

var val = obj.GetValue(); var val = obj.PlayOnAwake; // From Unity It's not first-person, it's imperative. Simply put, it's a command. GetValue() Get the value! PlaySound() Play this sound! DeleteFile() Delete that file! These namings are used for methods, especially methods that perform a task (as opposed to returning a known value). var has = obj....


3

You need a requirements review. Not every integer value is valid This is a very weak requirement. There is no computer in existence for which this isn't true. Some ints are so long they'd fill up your HD. So having this requirement here doesn't help much. Consider restating what this was meant to say or removing this entirely. The valid ...


0

Intellisense Code Documentation Most languages have a form of Intellisense Code Documentation. For C#, you can find information on it here. In a nutshell, it is comment documentation the you IDE Intellisense can parse, and make available to the user when they want to use it. What your interface documentation says is the behavior of a call is the only real ...


-1

In Java if you have a custom constructor, the empty constructor doesn't apply anymore and so you can force calling the custom constructor. My understanding is that C# works the same. So you could have something like public class SecondClass { public SecondClass(//some argument){ // do your checks here and throw an exception } } public ...


0

No The argument was made however that this is a flawed approach and that my DAOs should not be structurally tied to my domain model. I am trying to understand if this is so and why. Because you cannot inherently rely on your domain and entity models to match. In a comment on a (now deleted) answer you said: Appreciate the response, but find my self ...


1

You may have validating annotations that restrict the aceptable returned values. Here is an example in Java for Spring taken from baeldung.com but in C# you have a similar feature: @NotNull @Size(min = 1) public List<@NotNull Customer> getAllCustomers() {      return null; } If you use this approach you must consider that: You need a ...


0

It's not a code smell. In fact Martin Fowler over at [refactoring.com][1] argues you should repeat a loop if it adds value because of the trivial computing cost of repeating said loop. You should make alist a function argument and make the function static (if possible in the real world)


Top 50 recent answers are included