Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. code sexiness question

code sexiness question

Scheduled Pinned Locked Moved The Lounge
questioncsharpcomalgorithmsdata-structures
33 Posts 16 Posters 20 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Super Lloyd

    The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

    private IMultipleComponentHandler SelectionHandler
    {
    get
    {
    if (m_selectionHandler == null)
    {
    var objects = SelectedObject; // <== MAIN DIFFERENCE

    				if (objects is IMultipleComponentHandler handler)
    					return m\_selectionHandler = handler;
                   
    				object\[\] collection;
    				if (objects is IEnumerable e
    					&& !objects.GetAttributes().Any())
    				{
    					collection = e as object\[\] ?? e.Cast().ToArray();
    				}
    				else if (objects != null)
    				{
    					collection = new\[\] { objects };
    				}
    				else
    				{
    					collection = Array.Empty();
    				}
    				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
    			}
    			return m\_selectionHandler;
    		}
    	}
    	private IMultipleComponentHandler m\_selectionHandler;
    

    but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

    	private IMultipleComponentHandler SelectionHandler
    	{
    		get
    		{
    			if (m\_selectionHandler == null)
    			{
    				if (SelectedObject is IMultipleComponentHandler handler)
    					return m\_selectionHandler = handler;
    
    				object\[\] collection;
    				if (SelectedObject is IEnumerable e
    					&& !SelectedObject.GetAttributes().Any())
    				{
    					collection = e as object\[\] ?? e.Cast().ToArray();
    				}
    				else if (SelectedObject != null)
    				{
    					collection = new\[\] { SelectedObject };
    				}
    				else
    				{
    					collection = Array.Empty();
    				}
    				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
    			}
    			return m\_selectionHandler;
    		}
    	}
    	private IMultipleComponentHandler m\_selectionHandler;
    

    What says you?

    For the record this is in a view model, this code is absolutely NOT performance critical.

    A new .NET Serializer
    All in one Menu-Ribbon Bar
    Taking over the world since 1371!

    H Offline
    H Offline
    honey the codewitch
    wrote on last edited by
    #11

    The "extra" variable doesn't bother me. I don't think there's much difference in the cognitive load required to understand each function. Given that the first one passed code review, it's "sexier", IMO. Edit: I have to add, is the extra time you're spending trying to decide which version is more readable adding the requisite amount of value? *hides*

    Real programmers use butterflies

    S 1 Reply Last reply
    0
    • S Super Lloyd

      The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

      private IMultipleComponentHandler SelectionHandler
      {
      get
      {
      if (m_selectionHandler == null)
      {
      var objects = SelectedObject; // <== MAIN DIFFERENCE

      				if (objects is IMultipleComponentHandler handler)
      					return m\_selectionHandler = handler;
                     
      				object\[\] collection;
      				if (objects is IEnumerable e
      					&& !objects.GetAttributes().Any())
      				{
      					collection = e as object\[\] ?? e.Cast().ToArray();
      				}
      				else if (objects != null)
      				{
      					collection = new\[\] { objects };
      				}
      				else
      				{
      					collection = Array.Empty();
      				}
      				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
      			}
      			return m\_selectionHandler;
      		}
      	}
      	private IMultipleComponentHandler m\_selectionHandler;
      

      but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

      	private IMultipleComponentHandler SelectionHandler
      	{
      		get
      		{
      			if (m\_selectionHandler == null)
      			{
      				if (SelectedObject is IMultipleComponentHandler handler)
      					return m\_selectionHandler = handler;
      
      				object\[\] collection;
      				if (SelectedObject is IEnumerable e
      					&& !SelectedObject.GetAttributes().Any())
      				{
      					collection = e as object\[\] ?? e.Cast().ToArray();
      				}
      				else if (SelectedObject != null)
      				{
      					collection = new\[\] { SelectedObject };
      				}
      				else
      				{
      					collection = Array.Empty();
      				}
      				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
      			}
      			return m\_selectionHandler;
      		}
      	}
      	private IMultipleComponentHandler m\_selectionHandler;
      

      What says you?

      For the record this is in a view model, this code is absolutely NOT performance critical.

      A new .NET Serializer
      All in one Menu-Ribbon Bar
      Taking over the world since 1371!

      D Offline
      D Offline
      Daniele Rota Nodari
      wrote on last edited by
      #12

      Storing the value of the property (SelectedObject) into a local variable (objects) is like a snapshot. It ensures that any subsequent instruction refers to the same object. This is important when you need consistency throughout the method, the method can be relatively time consuming and some other thread can concurrently change the property value. You can always rely on compiler optimizations and hope that the compiled machine code will take care of such thing, or you can do it by yourself with the local variable. Another reason could be that you know in advance that someone will add code inside the method to purposely change the object value; such change will require to put the object into a variable, like the collegue told you to do. Doing it later will require to replace any reference to the property with references to the variable: those changes would be spread along the method polluting versioning differences. It can even be of help if copy-paste is performed to some other method where the logic must be kept but the property to process has a different name. These are indeed pre-optimizations, and we can argue about their usefullness and their development cost. Additionally, the name of the property is not totally meaningful, due to the fact it is singular but it can store multiple objects (like the name of the variable unfolds): this could be an important hint for the future-you maintaining the code.

      1 Reply Last reply
      0
      • S Super Lloyd

        exactly my thoughts process too! but, those code reviews are getting to me, too many stupid comments, and style guideline I don't like, so those days I just give up and do whatever the hell they say, but that also puts me in a bad mood and makes me think.. less clearly shall we say...

        A new .NET Serializer All in one Menu-Ribbon Bar Taking over the world since 1371!

        H Offline
        H Offline
        HobbyProggy
        wrote on last edited by
        #13

        If you can't change the rules, break the rules XD Nah srsly, i tend to go on change it, love it or leave it mentality. This solves many frustration related issues for me so far.

        Rules for the FOSW ![^]

        MessageBox.Show(!string.IsNullOrWhiteSpace(_signature)
        ? "This is my signature: " + Environment.NewLine + _signature
        : "404-Signature not found");

        1 Reply Last reply
        0
        • S Super Lloyd

          The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

          private IMultipleComponentHandler SelectionHandler
          {
          get
          {
          if (m_selectionHandler == null)
          {
          var objects = SelectedObject; // <== MAIN DIFFERENCE

          				if (objects is IMultipleComponentHandler handler)
          					return m\_selectionHandler = handler;
                         
          				object\[\] collection;
          				if (objects is IEnumerable e
          					&& !objects.GetAttributes().Any())
          				{
          					collection = e as object\[\] ?? e.Cast().ToArray();
          				}
          				else if (objects != null)
          				{
          					collection = new\[\] { objects };
          				}
          				else
          				{
          					collection = Array.Empty();
          				}
          				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
          			}
          			return m\_selectionHandler;
          		}
          	}
          	private IMultipleComponentHandler m\_selectionHandler;
          

          but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

          	private IMultipleComponentHandler SelectionHandler
          	{
          		get
          		{
          			if (m\_selectionHandler == null)
          			{
          				if (SelectedObject is IMultipleComponentHandler handler)
          					return m\_selectionHandler = handler;
          
          				object\[\] collection;
          				if (SelectedObject is IEnumerable e
          					&& !SelectedObject.GetAttributes().Any())
          				{
          					collection = e as object\[\] ?? e.Cast().ToArray();
          				}
          				else if (SelectedObject != null)
          				{
          					collection = new\[\] { SelectedObject };
          				}
          				else
          				{
          					collection = Array.Empty();
          				}
          				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
          			}
          			return m\_selectionHandler;
          		}
          	}
          	private IMultipleComponentHandler m\_selectionHandler;
          

          What says you?

          For the record this is in a view model, this code is absolutely NOT performance critical.

          A new .NET Serializer
          All in one Menu-Ribbon Bar
          Taking over the world since 1371!

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #14

          Just for giggles, how about:

          private IMultipleComponentHandler SelectionHandler => m_selectionHandler ??= SelectedObject switch
          {
          null => new InspectorMultipleComponentHandler(Array.Empty<object>()),
          IMultipleComponentHandler handler => handler,
          object[] e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e,
          IEnumerable e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e.Cast<object>().ToArray(),
          var e => new InspectorMultipleComponentHandler(new[] { e }),
          };

          As with your first example, this only accesses SelectedObject once.


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          S D S 3 Replies Last reply
          0
          • Richard DeemingR Richard Deeming

            Just for giggles, how about:

            private IMultipleComponentHandler SelectionHandler => m_selectionHandler ??= SelectedObject switch
            {
            null => new InspectorMultipleComponentHandler(Array.Empty<object>()),
            IMultipleComponentHandler handler => handler,
            object[] e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e,
            IEnumerable e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e.Cast<object>().ToArray(),
            var e => new InspectorMultipleComponentHandler(new[] { e }),
            };

            As with your first example, this only accesses SelectedObject once.


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            S Offline
            S Offline
            Super Lloyd
            wrote on last edited by
            #15

            we're still stuck on .NET 4.7.2 at the moment.... :(( not for long I heard .NET 6 is coming, like the winter!

            A new .NET Serializer All in one Menu-Ribbon Bar Taking over the world since 1371!

            Richard DeemingR 1 Reply Last reply
            0
            • Richard DeemingR Richard Deeming

              Just for giggles, how about:

              private IMultipleComponentHandler SelectionHandler => m_selectionHandler ??= SelectedObject switch
              {
              null => new InspectorMultipleComponentHandler(Array.Empty<object>()),
              IMultipleComponentHandler handler => handler,
              object[] e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e,
              IEnumerable e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e.Cast<object>().ToArray(),
              var e => new InspectorMultipleComponentHandler(new[] { e }),
              };

              As with your first example, this only accesses SelectedObject once.


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              D Offline
              D Offline
              Daniel Pfeffer
              wrote on last edited by
              #16

              Whiskey. Tango. Foxtrot. :omg:

              Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.

              Richard DeemingR 1 Reply Last reply
              0
              • H honey the codewitch

                The "extra" variable doesn't bother me. I don't think there's much difference in the cognitive load required to understand each function. Given that the first one passed code review, it's "sexier", IMO. Edit: I have to add, is the extra time you're spending trying to decide which version is more readable adding the requisite amount of value? *hides*

                Real programmers use butterflies

                S Offline
                S Offline
                Super Lloyd
                wrote on last edited by
                #17

                I am just fed up with all those rubbing me wrong micro management useless comments... I try to just shrug it off... But it annoys me every time some (of those particular) guys reviews... but on the other hand getting any review at all is also hard work, so bloody annoying...

                A new .NET Serializer All in one Menu-Ribbon Bar Taking over the world since 1371!

                H 1 Reply Last reply
                0
                • S Super Lloyd

                  we're still stuck on .NET 4.7.2 at the moment.... :(( not for long I heard .NET 6 is coming, like the winter!

                  A new .NET Serializer All in one Menu-Ribbon Bar Taking over the world since 1371!

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #18

                  If you're using VS2019 or 2022, you can still use that construct in .NET 4.7.2; you just need to manually edit your project file to enable C# 9. :) If you already have a <LangVersion> element in the file, change it to <LangVersion>9.0</LangVersion>. Otherwise, add that element next to the <TargetFramework> element. Quite a few C# 8/9/10 features will work in .NET Framework projects: Using C# 9 outside .NET 5 · Discussion #47701 · dotnet/roslyn · GitHub[^]


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  S 1 Reply Last reply
                  0
                  • D Daniel Pfeffer

                    Whiskey. Tango. Foxtrot. :omg:

                    Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.

                    Richard DeemingR Offline
                    Richard DeemingR Offline
                    Richard Deeming
                    wrote on last edited by
                    #19

                    switch expression - C# reference | Microsoft Docs[^] Pattern matching overview - C# guide | Microsoft Docs[^] :)


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                    1 Reply Last reply
                    0
                    • S Super Lloyd

                      The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

                      private IMultipleComponentHandler SelectionHandler
                      {
                      get
                      {
                      if (m_selectionHandler == null)
                      {
                      var objects = SelectedObject; // <== MAIN DIFFERENCE

                      				if (objects is IMultipleComponentHandler handler)
                      					return m\_selectionHandler = handler;
                                     
                      				object\[\] collection;
                      				if (objects is IEnumerable e
                      					&& !objects.GetAttributes().Any())
                      				{
                      					collection = e as object\[\] ?? e.Cast().ToArray();
                      				}
                      				else if (objects != null)
                      				{
                      					collection = new\[\] { objects };
                      				}
                      				else
                      				{
                      					collection = Array.Empty();
                      				}
                      				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                      			}
                      			return m\_selectionHandler;
                      		}
                      	}
                      	private IMultipleComponentHandler m\_selectionHandler;
                      

                      but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

                      	private IMultipleComponentHandler SelectionHandler
                      	{
                      		get
                      		{
                      			if (m\_selectionHandler == null)
                      			{
                      				if (SelectedObject is IMultipleComponentHandler handler)
                      					return m\_selectionHandler = handler;
                      
                      				object\[\] collection;
                      				if (SelectedObject is IEnumerable e
                      					&& !SelectedObject.GetAttributes().Any())
                      				{
                      					collection = e as object\[\] ?? e.Cast().ToArray();
                      				}
                      				else if (SelectedObject != null)
                      				{
                      					collection = new\[\] { SelectedObject };
                      				}
                      				else
                      				{
                      					collection = Array.Empty();
                      				}
                      				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                      			}
                      			return m\_selectionHandler;
                      		}
                      	}
                      	private IMultipleComponentHandler m\_selectionHandler;
                      

                      What says you?

                      For the record this is in a view model, this code is absolutely NOT performance critical.

                      A new .NET Serializer
                      All in one Menu-Ribbon Bar
                      Taking over the world since 1371!

                      OriginalGriffO Offline
                      OriginalGriffO Offline
                      OriginalGriff
                      wrote on last edited by
                      #20

                      I'd use the first version - that way if SelectedObject is changed (by another thread for example) the non-null value is preserved and the app doesn't crash. It's the way I handle event raising - my standard template code is:

                          /// /// Event to indicate Description
                          /// 
                          public event EventHandler Name;
                          /// /// Called to signal to subscribers that Description
                          /// 
                          /// 
                          protected virtual void OnName(EventArgs e)
                              {
                              EventHandler eh = Name;
                              if (eh != null)
                                  {
                                  eh(this, e);
                                  }
                              }
                      

                      That way, in the (unlikely) event that the last handler is removed from the c=hain, the app doesn't crash and does something sensible.

                      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

                      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                      Richard DeemingR 1 Reply Last reply
                      0
                      • Richard DeemingR Richard Deeming

                        If you're using VS2019 or 2022, you can still use that construct in .NET 4.7.2; you just need to manually edit your project file to enable C# 9. :) If you already have a <LangVersion> element in the file, change it to <LangVersion>9.0</LangVersion>. Otherwise, add that element next to the <TargetFramework> element. Quite a few C# 8/9/10 features will work in .NET Framework projects: Using C# 9 outside .NET 5 · Discussion #47701 · dotnet/roslyn · GitHub[^]


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        S Offline
                        S Offline
                        Super Lloyd
                        wrote on last edited by
                        #21

                        Interesting... Though in our case there is some sort of build system, which is still mysterious to me, that generate the .csproj files.. so I would need to get familiar with that first! :laugh: In fact... I really ought to become more familiar with this particular system.... :sigh:

                        A new .NET Serializer All in one Menu-Ribbon Bar Taking over the world since 1371!

                        1 Reply Last reply
                        0
                        • OriginalGriffO OriginalGriff

                          I'd use the first version - that way if SelectedObject is changed (by another thread for example) the non-null value is preserved and the app doesn't crash. It's the way I handle event raising - my standard template code is:

                              /// /// Event to indicate Description
                              /// 
                              public event EventHandler Name;
                              /// /// Called to signal to subscribers that Description
                              /// 
                              /// 
                              protected virtual void OnName(EventArgs e)
                                  {
                                  EventHandler eh = Name;
                                  if (eh != null)
                                      {
                                      eh(this, e);
                                      }
                                  }
                          

                          That way, in the (unlikely) event that the last handler is removed from the c=hain, the app doesn't crash and does something sensible.

                          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

                          Richard DeemingR Offline
                          Richard DeemingR Offline
                          Richard Deeming
                          wrote on last edited by
                          #22

                          Two obvious alternatives to that:

                          public event EventHandler Name = delegate { };

                          protected virtual void OnName(EventArgs e)
                          {
                          Name(this, e); // Name can never be null
                          }

                          public event EventHandler Name;

                          protected virtual void OnName(EventArgs e)
                          {
                          Name?.Invoke(this, e);
                          }


                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                          OriginalGriffO 1 Reply Last reply
                          0
                          • S Super Lloyd

                            I am just fed up with all those rubbing me wrong micro management useless comments... I try to just shrug it off... But it annoys me every time some (of those particular) guys reviews... but on the other hand getting any review at all is also hard work, so bloody annoying...

                            A new .NET Serializer All in one Menu-Ribbon Bar Taking over the world since 1371!

                            H Offline
                            H Offline
                            honey the codewitch
                            wrote on last edited by
                            #23

                            Understandable. I can't stand code reviews myself, because I have some different philosophies about how code needs to be written than a lot of people I have worked with. However, when I am in a position where I am in charge of code reviews, I tend to go easy and stick to enforcing in-shop style guidelines more than anything. I don't care about fast for bizdev unless something is slow enough you want to get out and push. I would have accepted either version of your code. I think both are readable *enough* - and this is one of the areas where I differ with a lot of people. I don't spend as much time chasing readability as other coders. I like to look at cognitive load more than readability, because I feel like readability can be had by reading the complicated parts of a function more than once. The trick is in *understanding* what you've read. That's the part where I care, but also the part I'm not great at. One of the reasons I write here is to try to improve my skillset in terms of making my code understandable. My functions are too long, but that's due to some cognitive issues I have myself, and it's part of how I've adapted to them.

                            Real programmers use butterflies

                            1 Reply Last reply
                            0
                            • Richard DeemingR Richard Deeming

                              Two obvious alternatives to that:

                              public event EventHandler Name = delegate { };

                              protected virtual void OnName(EventArgs e)
                              {
                              Name(this, e); // Name can never be null
                              }

                              public event EventHandler Name;

                              protected virtual void OnName(EventArgs e)
                              {
                              Name?.Invoke(this, e);
                              }


                              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                              OriginalGriffO Offline
                              OriginalGriffO Offline
                              OriginalGriff
                              wrote on last edited by
                              #24

                              The first relies on the empty delegate: if someone else sees the code and removes it as it clearly does nothing then you are back to a potential failure. Unlikely, yes - but I don't like app failures. :D The second is .NET version dependant: the null conditional operator was introduced at C# 6, and some of my code predates that.

                              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

                              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                              1 Reply Last reply
                              0
                              • S Super Lloyd

                                The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

                                private IMultipleComponentHandler SelectionHandler
                                {
                                get
                                {
                                if (m_selectionHandler == null)
                                {
                                var objects = SelectedObject; // <== MAIN DIFFERENCE

                                				if (objects is IMultipleComponentHandler handler)
                                					return m\_selectionHandler = handler;
                                               
                                				object\[\] collection;
                                				if (objects is IEnumerable e
                                					&& !objects.GetAttributes().Any())
                                				{
                                					collection = e as object\[\] ?? e.Cast().ToArray();
                                				}
                                				else if (objects != null)
                                				{
                                					collection = new\[\] { objects };
                                				}
                                				else
                                				{
                                					collection = Array.Empty();
                                				}
                                				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                			}
                                			return m\_selectionHandler;
                                		}
                                	}
                                	private IMultipleComponentHandler m\_selectionHandler;
                                

                                but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

                                	private IMultipleComponentHandler SelectionHandler
                                	{
                                		get
                                		{
                                			if (m\_selectionHandler == null)
                                			{
                                				if (SelectedObject is IMultipleComponentHandler handler)
                                					return m\_selectionHandler = handler;
                                
                                				object\[\] collection;
                                				if (SelectedObject is IEnumerable e
                                					&& !SelectedObject.GetAttributes().Any())
                                				{
                                					collection = e as object\[\] ?? e.Cast().ToArray();
                                				}
                                				else if (SelectedObject != null)
                                				{
                                					collection = new\[\] { SelectedObject };
                                				}
                                				else
                                				{
                                					collection = Array.Empty();
                                				}
                                				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                			}
                                			return m\_selectionHandler;
                                		}
                                	}
                                	private IMultipleComponentHandler m\_selectionHandler;
                                

                                What says you?

                                For the record this is in a view model, this code is absolutely NOT performance critical.

                                A new .NET Serializer
                                All in one Menu-Ribbon Bar
                                Taking over the world since 1371!

                                1 Offline
                                1 Offline
                                11917640 Member
                                wrote on last edited by
                                #25

                                Very good good code review result. Absolutely meaningless and harmless change. You and code reviewer, and of course, managers, are happy. BTW, after native optimizations both versions may be absolutely identical. But don't tell about this to your manager.

                                A 1 Reply Last reply
                                0
                                • Richard DeemingR Richard Deeming

                                  Just for giggles, how about:

                                  private IMultipleComponentHandler SelectionHandler => m_selectionHandler ??= SelectedObject switch
                                  {
                                  null => new InspectorMultipleComponentHandler(Array.Empty<object>()),
                                  IMultipleComponentHandler handler => handler,
                                  object[] e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e,
                                  IEnumerable e when !e.GetAttributes<IgnoreIEnumerableAttribute>.Any() => e.Cast<object>().ToArray(),
                                  var e => new InspectorMultipleComponentHandler(new[] { e }),
                                  };

                                  As with your first example, this only accesses SelectedObject once.


                                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                  S Offline
                                  S Offline
                                  snorkie
                                  wrote on last edited by
                                  #26

                                  Are we coding in C# or Perl? I always felt like C# was a nice balance between COBOL and Perl. But the recent changes have it trending towards Perl. I hear the excuse "it saves typing" as if we aren't on a message board or slack typing all day long.

                                  Hogan

                                  1 Reply Last reply
                                  0
                                  • S Super Lloyd

                                    The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

                                    private IMultipleComponentHandler SelectionHandler
                                    {
                                    get
                                    {
                                    if (m_selectionHandler == null)
                                    {
                                    var objects = SelectedObject; // <== MAIN DIFFERENCE

                                    				if (objects is IMultipleComponentHandler handler)
                                    					return m\_selectionHandler = handler;
                                                   
                                    				object\[\] collection;
                                    				if (objects is IEnumerable e
                                    					&& !objects.GetAttributes().Any())
                                    				{
                                    					collection = e as object\[\] ?? e.Cast().ToArray();
                                    				}
                                    				else if (objects != null)
                                    				{
                                    					collection = new\[\] { objects };
                                    				}
                                    				else
                                    				{
                                    					collection = Array.Empty();
                                    				}
                                    				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                    			}
                                    			return m\_selectionHandler;
                                    		}
                                    	}
                                    	private IMultipleComponentHandler m\_selectionHandler;
                                    

                                    but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

                                    	private IMultipleComponentHandler SelectionHandler
                                    	{
                                    		get
                                    		{
                                    			if (m\_selectionHandler == null)
                                    			{
                                    				if (SelectedObject is IMultipleComponentHandler handler)
                                    					return m\_selectionHandler = handler;
                                    
                                    				object\[\] collection;
                                    				if (SelectedObject is IEnumerable e
                                    					&& !SelectedObject.GetAttributes().Any())
                                    				{
                                    					collection = e as object\[\] ?? e.Cast().ToArray();
                                    				}
                                    				else if (SelectedObject != null)
                                    				{
                                    					collection = new\[\] { SelectedObject };
                                    				}
                                    				else
                                    				{
                                    					collection = Array.Empty();
                                    				}
                                    				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                    			}
                                    			return m\_selectionHandler;
                                    		}
                                    	}
                                    	private IMultipleComponentHandler m\_selectionHandler;
                                    

                                    What says you?

                                    For the record this is in a view model, this code is absolutely NOT performance critical.

                                    A new .NET Serializer
                                    All in one Menu-Ribbon Bar
                                    Taking over the world since 1371!

                                    L Offline
                                    L Offline
                                    Lost User
                                    wrote on last edited by
                                    #27

                                    I have problems with both. "var" is a coding shortcut when you're too lazy to type, and should be replaced with the actual type when it resolves (before release); so the next guy doesn't have to "intelli-sense" it. "Object" seems more appropriate in this case. I dislike "long" if's and would have "if not null return x" instead of (if null etc.) Even though it works, I don't declare properties "after" the method that references them. The return "assign" is "different". Then there are the if's with bracketed blocks and some without. Saving keystrokes? etc.

                                    It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it. ― Confucian Analects: Rules of Confucius about his food

                                    A 1 Reply Last reply
                                    0
                                    • S Super Lloyd

                                      The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

                                      private IMultipleComponentHandler SelectionHandler
                                      {
                                      get
                                      {
                                      if (m_selectionHandler == null)
                                      {
                                      var objects = SelectedObject; // <== MAIN DIFFERENCE

                                      				if (objects is IMultipleComponentHandler handler)
                                      					return m\_selectionHandler = handler;
                                                     
                                      				object\[\] collection;
                                      				if (objects is IEnumerable e
                                      					&& !objects.GetAttributes().Any())
                                      				{
                                      					collection = e as object\[\] ?? e.Cast().ToArray();
                                      				}
                                      				else if (objects != null)
                                      				{
                                      					collection = new\[\] { objects };
                                      				}
                                      				else
                                      				{
                                      					collection = Array.Empty();
                                      				}
                                      				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                      			}
                                      			return m\_selectionHandler;
                                      		}
                                      	}
                                      	private IMultipleComponentHandler m\_selectionHandler;
                                      

                                      but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

                                      	private IMultipleComponentHandler SelectionHandler
                                      	{
                                      		get
                                      		{
                                      			if (m\_selectionHandler == null)
                                      			{
                                      				if (SelectedObject is IMultipleComponentHandler handler)
                                      					return m\_selectionHandler = handler;
                                      
                                      				object\[\] collection;
                                      				if (SelectedObject is IEnumerable e
                                      					&& !SelectedObject.GetAttributes().Any())
                                      				{
                                      					collection = e as object\[\] ?? e.Cast().ToArray();
                                      				}
                                      				else if (SelectedObject != null)
                                      				{
                                      					collection = new\[\] { SelectedObject };
                                      				}
                                      				else
                                      				{
                                      					collection = Array.Empty();
                                      				}
                                      				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                      			}
                                      			return m\_selectionHandler;
                                      		}
                                      	}
                                      	private IMultipleComponentHandler m\_selectionHandler;
                                      

                                      What says you?

                                      For the record this is in a view model, this code is absolutely NOT performance critical.

                                      A new .NET Serializer
                                      All in one Menu-Ribbon Bar
                                      Taking over the world since 1371!

                                      G Offline
                                      G Offline
                                      Gary R Wheeler
                                      wrote on last edited by
                                      #28

                                      I would have done things this way:

                                      private IMultipleComponentHandler SelectionHandler
                                      {
                                      get
                                      {
                                      if (m_selectionHandler == null)
                                      {
                                      if (SelectedObject is IMultipleComponentHandler handler)
                                      {
                                      m_selectionHandler = handler;
                                      }

                                              else
                                              {
                                                  object\[\] collection;
                                                  
                                                  if (SelectedObject is IEnumerable e
                                                      && !SelectedObject.GetAttributes().Any())
                                                  {
                                                      collection = e as object\[\] ?? e.Cast().ToArray();
                                                  }
                                                  else if (SelectedObject != null)
                                                  {
                                                      collection = new\[\] { SelectedObject };
                                                  }
                                                  else
                                                  {
                                                      collection = Array.Empty();
                                                  }
                                      
                                                  m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                              }
                                          }
                                          
                                          return m\_selectionHandler;
                                      }
                                      

                                      }
                                      private IMultipleComponentHandler m_selectionHandler;I'm an old fart who prefers single-exit :-D .

                                      Software Zen: delete this;

                                      1 Reply Last reply
                                      0
                                      • S Super Lloyd

                                        The first method below is probably 3e-9 seconds faster per call than the second method... And a code reviewer asked that I used that syntax

                                        private IMultipleComponentHandler SelectionHandler
                                        {
                                        get
                                        {
                                        if (m_selectionHandler == null)
                                        {
                                        var objects = SelectedObject; // <== MAIN DIFFERENCE

                                        				if (objects is IMultipleComponentHandler handler)
                                        					return m\_selectionHandler = handler;
                                                       
                                        				object\[\] collection;
                                        				if (objects is IEnumerable e
                                        					&& !objects.GetAttributes().Any())
                                        				{
                                        					collection = e as object\[\] ?? e.Cast().ToArray();
                                        				}
                                        				else if (objects != null)
                                        				{
                                        					collection = new\[\] { objects };
                                        				}
                                        				else
                                        				{
                                        					collection = Array.Empty();
                                        				}
                                        				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                        			}
                                        			return m\_selectionHandler;
                                        		}
                                        	}
                                        	private IMultipleComponentHandler m\_selectionHandler;
                                        

                                        but... that extra variable annoys me (var objects = SelectedObject;), I see it as increasing code complexity for little benefit. I prefer that simpler version

                                        	private IMultipleComponentHandler SelectionHandler
                                        	{
                                        		get
                                        		{
                                        			if (m\_selectionHandler == null)
                                        			{
                                        				if (SelectedObject is IMultipleComponentHandler handler)
                                        					return m\_selectionHandler = handler;
                                        
                                        				object\[\] collection;
                                        				if (SelectedObject is IEnumerable e
                                        					&& !SelectedObject.GetAttributes().Any())
                                        				{
                                        					collection = e as object\[\] ?? e.Cast().ToArray();
                                        				}
                                        				else if (SelectedObject != null)
                                        				{
                                        					collection = new\[\] { SelectedObject };
                                        				}
                                        				else
                                        				{
                                        					collection = Array.Empty();
                                        				}
                                        				return m\_selectionHandler = new InspectorMultipleComponentHandler(collection);
                                        			}
                                        			return m\_selectionHandler;
                                        		}
                                        	}
                                        	private IMultipleComponentHandler m\_selectionHandler;
                                        

                                        What says you?

                                        For the record this is in a view model, this code is absolutely NOT performance critical.

                                        A new .NET Serializer
                                        All in one Menu-Ribbon Bar
                                        Taking over the world since 1371!

                                        F Offline
                                        F Offline
                                        Fueled By Decaff
                                        wrote on last edited by
                                        #29

                                        I would be tempted to extract the contents of the if statement as a function, like this:

                                            public IMultipleComponentHandler SelectionHandler
                                            {
                                                get
                                                {
                                                    if (m\_selectionHandler == null)
                                                    {
                                                        m\_selectionHandler = InitialiseSelectionHandler(SelectedObject);
                                                    }
                                                    return m\_selectionHandler;
                                                }
                                            }
                                        
                                            private IMultipleComponentHandler InitialiseSelectionHandler(object selectedObject)
                                            {
                                                if (selectedObject is IMultipleComponentHandler handler)
                                                    return m\_selectionHandler = handler;
                                        
                                                object\[\] collection;
                                                if (selectedObject is IEnumerable e
                                                    && !selectedObject.GetAttributes().Any())
                                                {
                                                    collection = e as object\[\] ?? e.Cast().ToArray();
                                                }
                                                else if (selectedObject != null)
                                                {
                                                    collection = new\[\] { selectedObject };
                                                }
                                                else
                                                {
                                                    collection = Array.Empty();
                                                }
                                                return new InspectorMultipleComponentHandler(collection);
                                            }
                                        
                                            private IMultipleComponentHandler m\_selectionHandler;
                                        

                                        This hides the issue of using a temporary variable, snapshots the SelectedObject so the value being used can not change while updating the handler and the getter property for SelectionHandler becomes easier to read.

                                        An added bonus is if SelectedObject changes you can update the handler by calling InitialiseSelectionHandler.

                                        D 1 Reply Last reply
                                        0
                                        • F Fueled By Decaff

                                          I would be tempted to extract the contents of the if statement as a function, like this:

                                              public IMultipleComponentHandler SelectionHandler
                                              {
                                                  get
                                                  {
                                                      if (m\_selectionHandler == null)
                                                      {
                                                          m\_selectionHandler = InitialiseSelectionHandler(SelectedObject);
                                                      }
                                                      return m\_selectionHandler;
                                                  }
                                              }
                                          
                                              private IMultipleComponentHandler InitialiseSelectionHandler(object selectedObject)
                                              {
                                                  if (selectedObject is IMultipleComponentHandler handler)
                                                      return m\_selectionHandler = handler;
                                          
                                                  object\[\] collection;
                                                  if (selectedObject is IEnumerable e
                                                      && !selectedObject.GetAttributes().Any())
                                                  {
                                                      collection = e as object\[\] ?? e.Cast().ToArray();
                                                  }
                                                  else if (selectedObject != null)
                                                  {
                                                      collection = new\[\] { selectedObject };
                                                  }
                                                  else
                                                  {
                                                      collection = Array.Empty();
                                                  }
                                                  return new InspectorMultipleComponentHandler(collection);
                                              }
                                          
                                              private IMultipleComponentHandler m\_selectionHandler;
                                          

                                          This hides the issue of using a temporary variable, snapshots the SelectedObject so the value being used can not change while updating the handler and the getter property for SelectionHandler becomes easier to read.

                                          An added bonus is if SelectedObject changes you can update the handler by calling InitialiseSelectionHandler.

                                          D Offline
                                          D Offline
                                          Daniele Rota Nodari
                                          wrote on last edited by
                                          #30

                                          This is way cleaner.. It is a sort of lazy initialization.. and usually it is split exactly that way: a backing field, a property that lazily initializes the field, and a method that performs the initialization. This also highlight a possible race condition after the very first null check, that can be avoided by a double-checked locking inside the property get accessor; and the InitialiseSelectionHandler method would remain untouched. I'd just keep the backing field close to the property (I usually keep the field immediately before the property).

                                          E 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups