0

I have been trying to wrap my head around the finer points of this today.

Essentially I have fallen in love with this format for booleans:

Class {
public static bool myBool {set; get;}
    private static void Method()
    {
        if (!myBool)
         {
            myBool = !myBool;
            // stuff that needs to be done
         }
    }
}

Obvious things like do not use a public when a private will work and scoping properly applies. But when is this a best practice vs using a simpler:

Class {
bool myBool = true;
    private static void Method()
    {
        if (!myBool)
         {
            myBool = !myBool;
            // stuff that needs to be done
         }
    }
}

Or do I have this backwards completely?

I understand that by using the format public static bool myBool {set; get;} I doing the following:

public static bool myBool
{
   get
   {
       return myBool;   
   }
   set
   {
       myBool = valuePassedIn;
   }
}

I feel like the first method is the best approach, but I have no idea why I think this. Is there a best from these choices? Am I doing something horribly wrong, or all three methods equivalent?

  • Why do you need a static property so start with? Can you give us the context of the problem that you are trying to solve? – CodeART Nov 25 '13 at 9:38
  • @CodeART It is a general question on when which approaches are best or if there is a difference. – AthomSfere Nov 25 '13 at 12:10
5

The key here is the static keyword

By using static bool, your class is effectively non-threadsafe, its also prone to race conditions where the state of that boolean may be changed by other areas of the code that you are not expecting to have downstream dependency issues.

Personally, I'd avoid static variables unless you have a very good reason for using them. I'd also avoid using static functions that change state. Static functions should be stateless (and you need a good reason for using them too!)

As for using the inbuilt syntactic sugar for get/set. Its really just there to avoid boilerplate. Do users of the class need to access this member? If they do, then a public interface with get/set will probably be useful. It also allows you to change the internal representation of what those accessors do without breaking interfacing code. But thinking about what the interface to external users should be should drive your decisions to use the syntatical helpers and public status of your members.

  • Thanks @MattD I like the summary of "Boilerplate" vs clean and that's really what I needed to know. – AthomSfere Nov 25 '13 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.