How do you break down your code?

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

39 Replies - 1021 Views - Last Post: 07 February 2019 - 02:34 PM

#1 fearfulsc2   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 226
  • Joined: 25-May 16

How do you break down your code?

Posted 05 February 2019 - 11:00 AM

Hi everyone,

I am looking at code I wrote recently for a project and it's really painful to read and debug and is many lines of code.

I managed to take some of it out and make that piece of code into its own helper class but there is still a lot of work to be done.

Some of the code is repeated due to object not set to a reference of an object error, so I worked with that in a rush and I want to find a way to reduce the redundancy there.

For example I have something like
if(objectA == null || objectA.Count == 0 || objectB == null || objectB.count == 0)
{
 if(objectA != null && (objectB == null || objectB.Count == 0))
 {
  // do something
 }
 else if((objectA == null || objectA.Count == 0) && objectB != null)
 {
  // do something
 }
 else
 {
  // do something;
 }
}
// both objects are not null or do not have a size of 0
else
{
 // do something
}



And essentially there is some redundancy in each of those statements with some uniqueness.

Is there a better way for me to check for if something is null or empty and for me to remove some of those if/else statements?

This post has been edited by fearfulsc2: 05 February 2019 - 11:01 AM


Is This A Good Question/Topic? 0
  • +

Replies To: How do you break down your code?

#2 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 195
  • View blog
  • Posts: 1,089
  • Joined: 05-December 13

Re: How do you break down your code?

Posted 05 February 2019 - 11:09 AM

Do you know what these || do in a statement of evaluation when you have conditions on the left as well as the right to evaluate with || between them? What happens to the statement?

There is a link in my signature under C# spoiler, expand it and look for Conditional Operators.

Read these https://www.tutorial...p_operators.htm and https://docs.microso...ence/operators/
Was This Post Helpful? 0
  • +
  • -

#3 fearfulsc2   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 226
  • Joined: 25-May 16

Re: How do you break down your code?

Posted 05 February 2019 - 11:13 AM

I'm not sure I follow what you are saying.

The || symbol is a logical or and it's usually a statement that returns true if one or the other logical comparisons are true.

If you put them in a parentheses and have && before that, such as
 if(a && (b || c))



then you have a must be true with either b or c having to be true. So I'm not sure what you are trying to convey.
Was This Post Helpful? 0
  • +
  • -

#4 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 195
  • View blog
  • Posts: 1,089
  • Joined: 05-December 13

Re: How do you break down your code?

Posted 05 February 2019 - 12:38 PM

I'm eluding to the point that its simple logic and I am not really sure how you think it can be made better by anyone here. Only you know what terms the conditions should be met under, and only you know what it will be used for. What is it doing that you don't want it to do, vice versa?

What are the object and where do they derive from? Are they being made instances of some other objects, if so where and what are they?

Its your code, you tell us what it does or doesn't do that is should or shouldn't. and provide the relevant code behind it.

Note you are already checking if objectA is null
01
if(objectA == null || objectA.Count == 0 || objectB == null || objectB.count == 0)
then on line 3, you are checking if its not null. Maybe you should explain what you're trying to do, instead of going around the houses with making this better?
Was This Post Helpful? 0
  • +
  • -

#5 fearfulsc2   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 226
  • Joined: 25-May 16

Re: How do you break down your code?

Posted 05 February 2019 - 01:10 PM

Okay, I think I follow now.

I am given 2 objects that I have to compare. The objects can both be a list of objects.

However, I do not know at the time if the objects given to me are empty or null.

When I go to compare them, they work fine if they both are not null and both have at least 1 item in the list.

The issue happened when One or both objects had a null value or empty list.

When it came down to comparing them, I would get an error saying, Object not set to an instance of an object whenever I did something like
CompareFunction(objectA[i], objectB[i])



The issue with this is that I did not know which object was the null or empty object.

That is why I have the if/else statements checking for all cases.

Inside those if/else statements, the code is very similar(sometimes the same) except that I need to specify in the parameter which object is not/empty.

so it would look something like this
// if objectB is null or empty
compare(objectA[i], null)

// if objectA is null or empty
compare(null, objectB[i])


Was This Post Helpful? 0
  • +
  • -

#6 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 195
  • View blog
  • Posts: 1,089
  • Joined: 05-December 13

Re: How do you break down your code?

Posted 05 February 2019 - 04:54 PM

So you want to check if an object item is not null, as it makes no sense to check for something that is not good to you, such as null values. Or does it? Why not just work with the object that is not null and then compare it?

Maybe you might find this more useful :: https://docs.microso...numerable___0__

I wouldn't bother checking for the count in the condition, but upon non null values, count how many there are instead? Pseudo code example
        public List<object> ListA = new List<object> { null };
        public List<object> ListB = new List<object> { null };
        public int CountListA, CountListB;

        private void Start()
        {
            ListA.Add("MyItemA1"); ListA.Add("MyItemA2");
            ListA.ForEach(delegate(object Item)
            {
                if (Item != null)
                    {  CountListA++;
                 Console.WriteLine(Item); }
            });
            ListB.Add("MyItemA1"); ListB.Add("MyItemB2"); ListB.Add("MyItemB3");
            ListB.ForEach(delegate(object Item)
                {
                    if (Item != null)
                        {   CountListB++;
                     Console.WriteLine(Item); }
                });
        }

You can use linq Except if you want to return them to a new list like this ::
            var CompList = ListA.Except(ListB).Union(ListB.Except(ListA)).ToList();
            CompList.ForEach(delegate(object Item) { Console.WriteLine(Item); });

https://docs.microso...framework-4.7.2

This post has been edited by Sheepings: 05 February 2019 - 05:21 PM

Was This Post Helpful? 0
  • +
  • -

#7 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6717
  • View blog
  • Posts: 22,931
  • Joined: 05-May 12

Re: How do you break down your code?

Posted 05 February 2019 - 07:40 PM

In general, I would take advantage of the null conditonal operator in code that looks like this:
for(int i = 0; i < max; i++)
    compareFunction(objectA?[i], objectB?[i]);


That is because obj?[i] is just syntatic sugar for the more verbose:
obj == null ? null : obj[i]



So that brings up the question of how to determine the value of max. One way would be to take advantage of the null conditional operator again, as well as the null coalescing operator:
int aCount = objectA?.Count ?? 0;
int bCount = objectB?.Count ?? 0;
int max = Math.Max(aCount, bCount);


The obj ?? x is again syntactic sugar for:
obj == null ? x : obj



Unfortunately, all of that is pointless because what I've presented above will only call the compare function if there is at least one element in objectA or objectB. It looks like you also want to do other stuff when either object is not null, but contains zero elements. I don't really understand if you wanted to do a comparison in those cases, or if there was something else you wanted to do. Can you explain further?
Was This Post Helpful? 3
  • +
  • -

#8 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7378
  • View blog
  • Posts: 15,309
  • Joined: 16-October 07

Re: How do you break down your code?

Posted 06 February 2019 - 07:19 AM

You know you only have four cases, so that should be your checking goal.

One way:
var va = objectA == null ? 0 : objectA.Count;
var vb = objectB == null ? 0 : objectB.Count;
if (va == 0 && vb == 0) {
    // both objects are null or have a size of 0
} else if (vb == 0) {
    // we know object A must have a value, because of first check
} else if (va == 0) {
    // we know object B must have a value, because of above check
} else { 
    // both objects are not null or do not have a size of 0
}



A slightly silly way, but makes sense if you are ancient enough to think in binary:
switch ((objectA == null || objectA.Count == 0 ? 0 : 1) + (objectB == null || objectB.Count == 0 ? 0 : 2)) {
    case 0:
        // both objects are null or have a size of 0
        break;
    case 1:
        // we know object A && !B must have a value
        break;
    case 2:
        // we know object B && !A must have a value
        break;
    case 3:
        // we know object A && B must have a value
        break;
}


This post has been edited by baavgai: 06 February 2019 - 07:21 AM

Was This Post Helpful? 0
  • +
  • -

#9 fearfulsc2   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 226
  • Joined: 25-May 16

Re: How do you break down your code?

Posted 06 February 2019 - 07:31 AM

Sure, I'll elaborate more for post #7.

I am given 2 list objects and they have to be dynamically compared so that if I get an object call Human and another object called AlmostHuman.

I can also compare objects like Shape1 and Shape2.

So I can pass in an object list of any type and see the similarities.

So I can have something like this
public sealed class Human
{
 public string EyeColor { get; set; }
 public string HairColor { get; set; }

}

public sealed class AlmostHuman 
{
 public string EyeColor { get; set; }
 public string HairColor { get; set; }
}

public sealed class Shape
{
 public string TypeOfShape { get; set; {
 public bool IsRound { get; set; }
}

public sealed class Shape2
{
 public string TypeOfShape { get; set; }
 public bool IsRound { get; set; }
}



Now, I want to be able to compare the "similar object types" to one another.

Compare(IList<T> object1, IList<S> object2)
{
 // the rest of the logic for seeing if object is null or empty
}



So when I call an API to get these objects, the API can either return NoContent, the list of objects, or an empty list.

When I pass those objects into the parameters of that function, I want to compare them. That is when I ran into the if/else or switch cases where I had to modify the logic a bit to compare if both objects had values or if one had values or if none of the had values(in this case return null).

I hope that makes sense.

This post has been edited by fearfulsc2: 06 February 2019 - 07:32 AM

Was This Post Helpful? 0
  • +
  • -

#10 andrewsw   User is offline

  • awks lol ffs
  • member icon

Reputation: 6693
  • View blog
  • Posts: 27,471
  • Joined: 12-December 12

Re: How do you break down your code?

Posted 06 February 2019 - 07:42 AM

I think a broader description of the overall aims would help break this down. Edit: the post just above appeared after my posting.

Is your compare function attempting to do too much? Does it really need to return an indicator of which list is null, empty?

Personally, I would be tempted to avoid trying to compare two objects if either is null; then a compare function would determine whether they both have the same length (which could perhaps be 0) and contain the same objects, possibly in the same order(?).

The compare function could then just confirm 'yes or no', the two objects/list have the same length and the same object references.

You might also consider diving into something like a generic list extension, for example, to create more of a model/abstraction.
Was This Post Helpful? 0
  • +
  • -

#11 andrewsw   User is offline

  • awks lol ffs
  • member icon

Reputation: 6693
  • View blog
  • Posts: 27,471
  • Joined: 12-December 12

Re: How do you break down your code?

Posted 06 February 2019 - 07:47 AM

Commenting on the OP's most recent post, are interfaces, or inheritance, not involved for Human and AlmostHuman? and shapes?

A generic list extension is only likely to be useful to check if two lists contain the same object references. If you are looking to discover "similar" objects, based on some ad hoc comparison of a handful of properties, you are not likely to create anything useful generically with such distinct types as humans and shapes.

[Unless you consider humans to be, generally, of rectangular-like shape.]
Was This Post Helpful? 0
  • +
  • -

#12 fearfulsc2   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 226
  • Joined: 25-May 16

Re: How do you break down your code?

Posted 06 February 2019 - 08:00 AM

Yes, the compare function is doing a lot of work.

The function is getting a list of two objects and then compares the values inside the properties to see if the values are the same.

If Human and AlmostHuman both have brown hair and brown eyes, they are in essence the same in this case. If One has brown hair and the other has blue hair, they are different.

If one has a value and the other is null, they are different and I must reflect that and say that the object has values but its partner it is being compared to has no values.

I have all of that taken care of. Now, it's just a matter of cleaning it all up to make it more readable and efficient since it's worst run time complexity will be O(n2)

int higherCount = 0;
int lowerCount = 0;

if(objectA == null || objectB == null || objectA.Count == 0 || objectB.Count == 0)
{
 if(objectA != null && (objectB == null || objectB.Count == 0))
 {
  higherCount = objectA.Count();
  for(int i = 0; i < higherCount; i++)
  {
   var someVariable = await this.Compare(objectA[i], null);
  }
 }
 else if((objectA == null || objectA.Count == 0) && objectB != null)
 {
  higherCount = objectB.Count();
  for(int i = 0; i < higherCount; i++)
  {
   var someVariable = await this.Compare(null, objectB[i]);
  }
 }
 else
 {
  return null; // not really the case but for demo purposes here
 }
}
// if both are not null, compare both
else
{
 bool isObjectA higher = false;
 if(objectA.Count >= objectB.Count)
 {
  higherCount = objectA.Count;
  lowerCount = objectB.Count;
  isObjectAHigher = true;
 }
 else
 {
  higherCount = objectB.Count;
  lowerCount = objectA.count;
 }

 for(int i = 0; i < higherCount; i++)
 {
  bool result = false;

  if(lowerCount == 0)
  {
   if(objectA.Count == 0)
   {
    objectA = null;
   }
   if(objectB.Count == 0)
   {
    objectB = null;
   }
   var somevariable = await this.Calculate(objectA, objectB); // this is a recursive call and the logic above is all called again

   break;
  }
  for (int j = 0; j < lowerCount; j++)
  {
   // a lot of logic to compare the objects and then decrease the size of the list by 1 and then recursively call the function again and do the comparisons again and repeats until the size of both hit 0 or null
  }
 }

}



Was This Post Helpful? 0
  • +
  • -

#13 fearfulsc2   User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 226
  • Joined: 25-May 16

Re: How do you break down your code?

Posted 06 February 2019 - 08:15 AM

View Postandrewsw, on 06 February 2019 - 07:47 AM, said:

Commenting on the OP's most recent post, are interfaces, or inheritance, not involved for Human and AlmostHuman? and shapes?

A generic list extension is only likely to be useful to check if two lists contain the same object references. If you are looking to discover "similar" objects, based on some ad hoc comparison of a handful of properties, you are not likely to create anything useful generically with such distinct types as humans and shapes.

[Unless you consider humans to be, generally, of rectangular-like shape.]



And that is where exceptions will be thrown because if Human and Shape were to be compared, it would go crazy because the properties in the object are not the same name.

I get a list of property names I want to compare for a certain type/subtype of object.
So if I get from the db that I want to compare Human, AlmostHuman will also be given to me as well. Since they both have the same same property names, the comparison can go through. However, if the property names are different, exceptions will be thrown.
Was This Post Helpful? 0
  • +
  • -

#14 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2730
  • View blog
  • Posts: 10,898
  • Joined: 03-December 12

Re: How do you break down your code?

Posted 06 February 2019 - 08:26 AM

I think you would benefit from this book: Adaptive Code
Was This Post Helpful? 1
  • +
  • -

#15 andrewsw   User is offline

  • awks lol ffs
  • member icon

Reputation: 6693
  • View blog
  • Posts: 27,471
  • Joined: 12-December 12

Re: How do you break down your code?

Posted 06 February 2019 - 08:37 AM

Quote

I get a list of property names I want to compare for a certain type/subtype of object.

If they shared a common parent or interface then you wouldn't need a list of properties, just an equality/comparison method within the hierarchy.

Yes, as with astonecipher, it doesn't sound to be very adaptive going forward. More to do with concretions.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3