First off, I totally apologize for the title, I don't know what the heck to put, it's such a confusing concept to really explain in a title, so bear with me.
public class fido
{
public void foo(process proc)
{
if (/* comparing by time */)
{
if (proc[parent].time < proc[child].time)
{
//do something
}
}
else if (/* comparing by priority */)
{
if (proc[parent].priority < proc[child].priority)
{
//do something
}
}
}
}
How do I go about shortening this? I was hoping it could be as simple as using a "defined" member through the parameter of foo().
For example
public class fido
{
public void foo(process proc, something mem)
{
if (/* comparing by time */)
{
if (proc[parent].mem < proc[child].mem)
{
//do something
}
}
}
}
Then I would use something like
foo(processA, time); // If I want to use time member
foo(processB, priority); // Or if I want to use priority member
I know the previous codes are 100% incorrect, but I hope you understand what I'm getting at.
I'm just trying to shorten the code because what I have is a priority queue class that uses heap and everything to prioritize values, however I need to use the class for multiple types of values, such as time and priority. I definitely do not want to create a duplicate class (totally not beneficial), I'm looking for a way I can shorten it. Does anybody know the best way?
You could pass an enum as a parameter in your method.
public class Fido
{
public void foo(Process proc, Options options)
{
if (options == Options.Time)
{
//Do time work
}
else if (options == Options.Priority)
{
//Do priority work
}
}
}
public enum Options
{
Time,
Priority
}
Note that a passing a bool instead of an enum would work here as well. It just makes things a bit less readable.
Related
I have a problem on having called a generic method, I have searched very much and do not find a solution, this one is my mistake.
And I do not have knowledge of I am doing badly,
The type arguments for method 'FormGasolineUserControl.loadList<T>(list<T>,string)' cannot be inferred from the usage. try specifying the type arguments expliciy.
this is my code:
This chunk of code where I obtain the error
private void loadDataForm()
{
try
{
DateTime dateNow = DateTime.Now;
// Call Services WPF
var QueryBD = services.LoadDataFormGasoline(1, (int)ETax.Gasoline);
if (QueryBD.Company != null)
{
day.Value = dateNow.Day.ToString();
month.Value = dateNow.Month.ToString();
year.Value = dateNow.Year.ToString();
anioGravable.Value = dateNow.Year.ToString();
peridoGravable.Value = PeriodoGravable(dateNow).ToString();
//Error call Method
loadList( QueryBD.QualityDeclarate, QualityDeclarate.Name.ToString());
loadList( QueryBD.TypeDeclarate, TypeDeclarate.Name.ToString());
}
}
catch (Exception)
{
throw;
}
}
And this one is the method:
public void loadlist<T>(List<T> lista,string nameControl)
{
try
{
switch (nameControl)
{
case "TypeDeclarate":
TypeDeclarate.Items.Add(new ListItem("Select..."));
foreach (var name in lista)
{
TypeDeclarate.Items.Add(new ListItem(name.ToString()));
}
break;
case "QualityDeclarate":
QualityDeclarate.Items.Add(new ListItem("Select..."));
foreach (var name in lista)
{
QualityDeclarate.Items.Add(new ListItem(name.ToString()));
}
break;
}
}
catch (Exception)
{
throw;
}
}
My principal aim is to be able to load the usercontrol dynamicamente by means of lists consulted in database.
help me plis...
This code could be improved in a great many ways.
It should not be generic.
It could be refactored into smaller methods that are more clear.
The naming conventions do not follow C# conventions.
It takes a list but only enumerates the elements
It really operates on sequences of strings.
The try-catch is useless.
Let's fix it.
private void AddItemsToCollection(IEnumerable<string> names, IList<ListItem> items)
{
items.Add(new ListItem("Select..."));
foreach (var name in names)
items.Add(new ListItem(name));
}
See how simple that is? Make simple methods that do one thing well. Now we use that helper to make other simple methods:
private void AddItemsToCollection(IEnumerable names, IList<ListItem> items)
{
AddItemsToCollection(names.Cast<object>().Select(n => n.ToString(), items);
}
Again, super simple. One line. Let's make more one-liners:
public void AddTypeDeclarateItems(IEnumerable names)
{
AddItemsToCollection(names, TypeDeclarate.Items);
}
SO EASY. Do it again.
public void AddQualityDeclarateItems(IEnumerable names)
{
AddItemsToCollection(names, QualityDeclarate.Items);
}
And now our method is simple:
public void AddItemsToCollection(IEnumerable names, string control)
{
switch (control)
{
case "TypeDeclarate":
AddTypeDeclarateItems(names);
break;
case "QualityDeclarate":
AddQualityDeclarateItems(names);
break;
}
}
Your code will get easier to understand, easier to make correct, easier to debug, if you simplify it so that every method does one thing.
Alternative solution: move the switch into a helper:
IList<ListItem> GetItems(string control)
{
switch (control)
{
case "TypeDeclarate":
return TypeDeclarate.Items;
case "QualityDeclarate":
return QualityDeclarate.Items;
}
throw new SomeException(...);
}
And now our method is:
public void AddItemsToCollection(IEnumerable names, string control)
{
AddItemsToCollection(names, GetItems(control));
}
Again, see what happens when you make every method do one thing? Every method gets really easy to understand, and highly likely to be correct.
This is the correct way to call this method:
...
loadlist<string>(QueryBD.myListOfStrings, "nameControl");
loadlist<int>(QueryBD.myListOfInts,"nameControl");
...
But, I guess that maybe the problem is inside the class that contains the method
void loadlist<T>(List<T> lista,string nameControl).
Aswer this question: What is T? I mean, in a class declaration we have many possibilities.
We can set T argument like a class: public MyClass<T> where T : class;
A struct: public MyClass<T> where T : struct; A class that has a public constructor public MyClass<T> where T : new(),...
See all possibilities: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
So, let's imagine that T is a class that must implements an interface and you're passing a class that doesn't implement it, so you'll not have success.
See my solution below -- search for UPDATE.
I have an extensive state machine architecture, which I'm implementing by creating a class for each state (there are multiple machines, but the states for all inherit from the same 'MachineState' class). Each state has a static property "StateName":
public class SomeState: MachineState
{
// THIS BLOCK SHOULD BE COPIED TO ALL STATE CLASSES!!
private static string _StateName;
public static string StateName
{
get {
if (_StateName == null)
{
_StateName = MethodBase
.GetCurrentMethod()
.DeclaringType
.ToString()
.Split(new char[] { '.' })
.ToList()
.Last();
}
return _StateName;
}
}
// END OF BLOCK
public SomeState(Queue<string> messages) //
: base(messages)
{
...
}
...
}
Ugh.
At least I'll call the processor-intensive stuff to get the name only once per class -- for my purposes, that's an acceptable cost. But I would really like to find some way for them to "inherit" this code -- or at least some way for them to include it something like a macro. I have an abstract property, so if it's not implemented I'll catch it at compile time; but still, there's got to be a way to avoid copying that mess into EVERY class -- and then having to CHANGE it in every class if the need ever arises.
Any ideas?
Thanks.
------------ UPDATE ---------------------------------------
Life is full of compromises; this one I can live with. #Tallek suggested this in the base class:
public static string GetStateName<T>() where T : MachineState
{
return typeof(T).Name;
}
I integrated that with my static property, like this (for class 'SomeState'):
// THIS BLOCK SHOULD BE COPIED TO ALL STATE CLASSES!!
public static string StateName { get { return GetStateName<SomeState>(); } }
It isn't perfect; I'll have to be sure to get the correct state name in the GetStateName call for each class. But it does two things I was anxious to do: it moves the logic into a single location, and it is easier to read. Keeping StateName abstract will help me catch any state that hasn't implemented StateName.
Thanks again, to all.
You have a state
Your states are classes
You want to compare that state to another
You don't want to instanciate states in order to compare
I don't see you doing it easier than:
if(state.GetType() == typeof(SomeState))
I potentially agree with CodeCaster. 20 or 30 states is not that large for an enum.
Based on your description of receiving a message and identifying the handler for that message, combined with looking at your example:
if(stateName == SomeState.StateName) { }
This implies you have stateName as a parameter. So you have an if block for every state so you can identify which one the message applies to?
if(stateName == SomeState.StateName) {
}
if(stateName == OtherState.StateName) {
}
If that is the case...
(big if given limited use case information, the rest of this answer is based on that premise so don't flame me if the rest of this doesn't apply)
You desire to have all classes automatically have this StateName property. This seems DRY, but then we see you still have to have an if block for each state, which is less DRY since there's more code to that IMO. You've traded a DRY for another DRY.
I would have enums which each have a
public enum States {
...
[Handler(typeof(SomeState))]
SomeState = 5,
...
Combined with a factory pattern, and now you throw out all the if blocks and only need a call to your factory:
MachineState newState = StateFactory.Create(stateName);
The factory uses Enum.Parse to convert the stateName into an enum, from which you access the attribute to get the type you need to instantiate. No switch/case/if/else needed.
This means every time you implement a new state class, you only need to touch one place, and that is the enum, and that has minimal code repetition.
If each if block has specific logic in it for that particular State
Move that code into a HandleMessage method defined in a MachineState or IMachineState interface, which has an implementation for each SomeState to do the stuff specific for that state. Let's assume your message indicates the stateName and maybe there's some "content" or "data" in the message that needs to be processed:
MachineState newState = StateFactory.Create(stateName);
newState.HandleMessage(messageContent);
I realize it's probably more complicated than that. You might need to seperate state from state handling into separate classes to make this work well. It's hard say. I would certainly mull this over pretty heavily though if I were in your shoes.
Its not great, but maybe worth considering...
public class MachineState
{
public static string GetStateName<T>() where T : MachineState
{
return typeof(T).Name;
}
}
Use like this:
if("MyState" == MachineState.GetStateName<MyState>()) { ... }
You could accomplish this with an extension method:
public static string GetStateName(this MachineState state) {
return state.GetType().Name;
}
Use it like this:
if(state.GetStateName() == "SomeState") { /* Do something */ }
Bake in your own caching if you want: you have access to any static structures you want here.
I have a code with next logic: If some boolean flag is true, one of two code fragments must be executed first and vice versa. But both of them must be executed always. Unfortunately, C# has not semantics instructions for that, like this:
if (condition) first
{
//Some code to execute first if condition is true
}
second
{
//Some code to execute first if condition is false
}
Now, I to do so:
if (condition)
{
//Code 1
//Code 2
}
else
{
//Code 2
//Code 1
}
Such neccesserities are numerous and this creates many code duplication. May be is there a better solution?
Put the code into seperate methods
public void MyMethod1
{
//first code goes here
}
public void MyMethod2
{
//second code goes here
}
if (condition)
{
MyMethod1();
MyMethod2();
}
else
{
MyMethod2();
MyMethod1();
}
This way you do not have to duplicate the code inside the methods.
You may consider writing a method such as:
public static void DoBoth(Action first, Action second, bool keepOrder)
{
if (keepOrder)
{
first();
second();
}
else
{
second();
first();
}
}
I'd create two methods with "Code 1" and "Code 2", then go on like your 2nd option:
if (condition)
{
Code1(); Code2();
}
else
{
Code 2(); Code1();
}
You could also polish this up via Actions or Delegates, depending on what "code 1" and "code 2" are.
I agree with #Steven Jeuris comment about preferring to know the underlying reason as it may point to a design decision requiring improvement. However, if you need to stick with what you have, I would suggest a queue of delegates since you imply that your example is very simple compared to the actual codebase. If not, then one of the other answers would be fine, but the below is possibly more maintainable as complexity grows.
Note: I'm putting this as an example - the parameters for GetQueue, and the logic inside it, could be improved depending on what your conditions actually are.
public Queue<Action> GetQueue(bool condition)
{
var toReturn = new Queue<Action>();
if (condition)
{
toReturn.Enqueue(DoWork1);
toReturn.Enqueue(DoWork2);
}
else
{
toReturn.Enqueue(DoWork2);
toReturn.Enqueue(DoWork1);
}
return toReturn;
}
public void MyExecutingMethod()
{
foreach (var action in GetQueue(true))
{
action();
}
}
public void DoWork1()
{
}
public void DoWork2()
{
}
You should try to avoid code duplication whenever you can. The basic idea in your case would be to try and extract everything that seems to be done more than once and try to "put" it somewhere where you only need to write it once.
In your case, say we have the following:
public void Bar()
{
...
if (condition)
{
//code for action 1
//code for action 2
}
else
{
//code for action 2
//code for action 1
}
...
}
public void Foo()
{
...
if (condition)
{
//code for action 1
//code for action 2
}
else
{
//code for action 2
//code for action 1
}
...
}
Now we obviously can see that you have some code duplication here. We can improve this the following way:
public void Bar()
{
...
if (condition)
{
Action1();
Action2();
}
else
{
Action2();
Action1();
}
...
}
public void Foo()
{
...
if (condition)
{
Action1();
Action2();
}
else
{
Action2();
Action1();
}
...
}
private void Action1()
{
//code for action 1
}
private void Action2()
{
//code for action 1
}
This looks a lot better (specially if Action1 code and Action2 code is lengthy). We have now managed to write the code for Action1 and Action2 only once no matter how many Foo or Bar style methods we have in our code. But we can still do more. You can see that we are still duplicating some obnoxious verbose code. So we can take it a step further and do the following:
public void Bar()
{
...
DoAction(condition);
...
}
public void Foo()
{
...
DoAction(condition);
...
}
private void Action1()
{
//code for action 1
}
private void Action2()
{
//code for action 1
}
private void DoAction(bool condition)
{
if (condition)
{
Action1();
Action2();
}
else
{
Action2();
Action1();
}
}
Now, that IMHO looks a lot better. Not only have we managed to write Action1 and Action2 specific code only once, we have now also managed to write that pesky method ordering logic only once too.
This has huge implications on readability and above all maintainability. For instance, if a bug crops up in Action1 now you only need to change it in one single place. In the original implementation you would have to check all the code and fix the bug everywhere.
Also, imagine the method ordering is business rules dependant, and your client (oh my what a surprise!) decides to change them. With the latest implementation you only need to change your code in one spot.
Rule of the thumb: Avoid code duplication whenever you can, it will drastically reduce the code you type and the headaches you or some poor soul will have in the near future.
I'm going to hazard a guess that code1 either have no side effects or act on the classes member variables, in which case they can be wrapped up in methods that return void. You could then do something along the lines of the following:
...
if (condition)
DoWork(() => Code1(), () => Code2());
else
{
DoWork(() => Code2(), () => Code1());
}
...
private void Code1()
{
// Code 1
}
private void Code2()
{
// code 2
}
private void DoWork(Action action1, Action action2)
{
action1();
action2();
}
I offer another suggestion (in pseudocode).
EDIT: It really depends on your situation which of various approaches you will want to take. Benefits of this approach are simplicity and flexibility. By flexibility, I mean that the decision on ordering is now separated from the code so you can easily do things like add a new ordering, or let the ordering be specified in some other means (e.g. what if you now want to associate different orderings with different users based on a property file)?
if(condition)
runOrder = [ "one", "two" ];
else
runOrder = [ "two", "one" ];
for(x=0; x<runOrder.length; x++)
{
codeToRun = runOrder[x];
switch(codeToRun)
{
Case "one": Code1();
Case "two": Code2();
}
}
I need to keep track of a sequential Id, this is being returned to me via a SP which is doing a max(id) across 4 tables, there is no identifer/sequence in the db which is managing the sequence. This will obviously have concurrency issues so i created a helper class to ensure unique Id's are always generated.
The helper is initialised via its repository, which initially calls the DB to find the current Id, all subsequent requests for an Id are serviced in memory via the helper. There will only ever be 1 app using the DB (mine) so i dont need to worry about someone else coming along and creating transactions & throwing the Id out of sync. I think ive got the basics of thread-saftey but im worried about a race condition when the helper is initialised, can someone please advise :)
private class TransactionIdProvider
{
private static readonly object Accesslock = new object();
private int _transactionId;
public int NextId
{
get
{
lock (Accesslock)
{
if(!Initialised) throw new Exception("Must Initialise with id first!!");
return _transactionId++;
}
}
}
public bool Initialised { get; private set; }
public void SetId(int id)
{
lock (Accesslock)
{
if (Initialised) return;
_transactionId = id;
Initialised = true;
}
}
public TransactionIdProvider()
{
Initialised = false;
}
}
The helper class is initialised in a repository:
private static readonly TransactionIdProvider IdProvider = new TransactionIdProvider();
public int GetNextTransactionId()
{
if(!IdProvider.Initialised)
{
// Ask the DB
int? id = _context.GetNextTransactionId().First();
if (!id.HasValue)
throw new Exception("No transaction Id returned");
IdProvider.SetId(id.Value);
}
return IdProvider.NextId;
}
It is thread-safe, but it's unnecessarily slow.
You don't need a lock to just increment a number; instead, you can use atomic math.
Also, you're sharing the lock across all instances (it's static), which is unnecessary. (There's nothing wrong with having two different instances run at once)
Finally, (IMHO) there is no point in having a separate uninitialized state.
I would write it like this:
class TransactionIdProvider {
private int nextId;
public TransactionIdProvider(int id) {
nextId = value;
}
public int GetId() {
return Interlocked.Increment(ref nextId);
}
}
Yes it is thread-safe; however, IMO the lock is too global - a static lock to protect instance data smacks a bit of overkill.
Also, NextId as a property is bad - it changes state, so should be a method.
You might also prefer Interlocked.Increment over a lock, although that changes most of the class.
Finally, in the SetId - if it is already initialised I would throw an exception (InvalidOperationException) rather than blindly ignore the call - that sounds like an error. Of course, that then introduces a tricky interval between checking Initialized and calling SetId - you could just hAve SetId return true if it made the change, and false if it turned out to be initialized at the point of set, but SLaks' approach is nicer.
I don't think this is a good idea, you should find another way to deal with this.
Usually when really unique ids are required and there is no a way computationally valid to check if the id is used, i would use a GUID.
However you can just use interlocked operations instead of locking, you can do it without locking at all.
Look for Interlocked.Increment, Interlocked.Exchange and Interlocked.CompareExchange
private class TransactionIdProvider
{
private volatile int _initialized;
private int _transactionId;
public int NextId
{
get
{
for (;;)
{
switch (_initialized)
{
case 0: throw new Exception("Not initialized");
case 1: return Interlocked.Increment(ref _transactionId);
default: Thread.Yield();
}
}
}
}
public void SetId(int id)
{
if (Interlocked.CompareExchange(ref _initialized, -1, 0) == 0)
{
Interlocked.Exchange(ref _transactionId, id);
Interlocked.Exchange(ref _initialized, 1);
}
}
}
This will give you a warning, but it is normal and is also reported in C# documentation as legal. So ignore that warning with a nice pragma:
// Disable warning "A reference to a volatile field will not be treated as volatile"
#pragma warning disable 0420
If you don't need to check for IsInitialized you can do it in the simplest possible way:
public int NextId()
{
return Interlocked.Increment(ref _transactionId);
}
public void Set(int value)
{
Interlocked.Exchange(ref _transactionId, value);
}
So I've got a whole bunch of options, every different page/tab can have their own local options. We'll have maybe 10-15 pages tabs open tops. I need to implement a way to show the global defaults, weather the all the tabs have consistent values. I'm working on the model/viewmodel portion of a WPF app.
I'd love to find a way that is more elegant since I'm having to cut and past roughly the same code 20+ times and just change property names. Maybe this is the problem Dynamics solve, but right now this feels both wrong and painful.
Here is an example of my current solution:
public class Foo
{
private bool fooVar1;
private bool fooVar2;
//lots of these
private decimal fooVar23;
public Foo()
{
}
public bool FooVar1
{
get;
set;
}
//you get the picture...
}
public class FooMonitor
{
private Foo defaultFoo;
private List<Foo> allFoos;
public FooMonitor(Foo DefaultFoo)
{
defaultFoo = DefaultFoo;
}
public void AddFoo(Foo newFoo)
{
allFoos.Add(newFoo);
}
public void AddFoo(Foo oldFoo)
{
allFoos.Remove(oldFoo);
}
public bool IsFooVar1Consistent
{
get
{
Foo[] tempFoos = allFoos.ToArray();
foreach (Foo tempFoo in tempFoos)
{
if (tempFoo.FooVar1 != defaultFoo.FooVar1) return false;
}
return true;
}
}
}
Or am I approaching this problem entirely incorrectly.
As I'm writing this question (After about 2000 lines of code) I'm thinking of how I read that WPF itself implements Dictionary look ups that crawl up to the parent to see if a Property is present and what the value should be.
Well, for a start you are defining both backing fields which will never be used and automatic properties. This is enough for a simple bool property:
public bool FooVar1 { get; set; }
No need for the private field. This greatly reduces the number of lines in your example.
I'd love to find a way that is more
elegant since I'm having to cut and
past roughly the same code 20+ times
and just change property names.
Code generators exist for exactly this purpose. But if you don't want to go that route, you can shorten your code to this:
return allFoos.All(foo => foo.FooVar1 == defaultFoo.FooVar1);
I'm not quite sure what the question is, but if you're looking for some way to unify the IsFoorVarXConsistent code, you could do it using reflection or by passing in an expression:
public bool IsConsistent(Func<Foo, bool> property)
{
foreach (Foo tempFoo in allFoos)
{
if (property(tempFoo) != property(defaultFoo))
return false;
}
return true;
}
Called like this:
bool is1Consistent = IsConsistent(f => f.FooVar1);
As shown this will only work for boolean properties. To extend it to other types, we can make it generic in the property type. However, in this case we cannot use != to test for inequality because not all types define a != operator. Instead we can use the .Equals method and the ! operator:
public bool IsConsistent<T>(Func<Foo, T> property)
where T : struct
{
foreach (Foo tempFoo in allFoos)
{
if (!property(tempFoo).Equals(property(defaultFoo)))
return false;
}
return true;
}
The where T : struct clause restricts this to value types like int, bool and decimal. In particular it will not work on strings. Removing the where constraint allows it to work on strings and other reference types, but creates the possibility of property(tempFoo) being null, which would cause a NullReferenceException when we called .Equals on it. So if you remove the value types constraint then you will need to add error handling for this scenario.