Naming accessors and YOU!

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 16561 Views - Last Post: 30 June 2011 - 04:33 AM

#1 cfoley   User is offline

  • Cabbage
  • member icon

Reputation: 2410
  • View blog
  • Posts: 5,050
  • Joined: 11-December 07

Naming accessors and YOU!

Post icon  Posted 26 May 2011 - 06:25 AM

How do you name your accessors? Are they in the style getName() or simply name(). Does your choice follow the convention of your language?

Background

Most of the stuff I write these days is in java, and the convention for accessors is getters: (e.g. car.getEngineSize()). The other day I was writing a parameter object class (so I could pass a group of values to methods with a single argument) and writing the getters so the methods could get at the data. It seemed to me that putting "get" everywhere was just a lot of noise so I decided to leave it out for that class. As I continued to work on my project, all the "get"s in other classes started annoying me.

I'm almost at the point of changing their names as I encounter them but am wondering if this is a good idea. What do you think?

Is This A Good Question/Topic? 2
  • +

Replies To: Naming accessors and YOU!

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6537
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Naming accessors and YOU!

Posted 26 May 2011 - 06:38 AM

There are naming conventions that should be followed.

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.
  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)
  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.

Was This Post Helpful? 1
  • +
  • -

#3 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: Naming accessors and YOU!

Posted 26 May 2011 - 06:54 AM

Java has a standard of "getters" and "setters." Much OO literature will use Java for examples, so...

C# has properties, which allow for the same thing, but feel a little cleaner. Outside of C#, I will usually preface something with a get or set, depending. If it is a boolean, I'll often use "is" or "has" instead of get. I'll use "load" if a function takes a parameter read data into it.

If saving letters was more important than clarity, all my variables would be one letter long... ;)

Seriously, there is some language bias:

Python is a fun language where privacy is only a convention and OO is more a formality. I often won't bother wrapping attributes with methods in Python like I would in most OO languages. Javascript is similar.

C isn't an OO language. My C functions will often begin with the name of the type and then the action. With a pattern of first variable being the type.
Was This Post Helpful? 3
  • +
  • -

#4 cfoley   User is offline

  • Cabbage
  • member icon

Reputation: 2410
  • View blog
  • Posts: 5,050
  • Joined: 11-December 07

Re: Naming accessors and YOU!

Posted 30 May 2011 - 04:51 PM

Hey, sorry for not following up with this topic. My fault for starting it just before a long holiday weekend.

Thanks for the replies. The reason I asked the question is because I was going against convention but the resultant code looked cleaner and more readable to me, but that could be because I wrote the code and recently too.

There are methods in the Java API that go against the getter convention. String.length(), Collection.size(), Map.values()come to mind. Though I guess there is a big difference between these methods that everyone knows and uses and a method written by a single developer.
Was This Post Helpful? 0
  • +
  • -

#5 Shane Hudson   User is offline

  • D.I.C Technophile
  • member icon

Reputation: 345
  • View blog
  • Posts: 1,286
  • Joined: 06-December 09

Re: Naming accessors and YOU!

Posted 31 May 2011 - 02:05 AM

Lately I have been coding in mainly C# so I use properties, however in any other language I stick to the getter and setter conventions.
Was This Post Helpful? 1
  • +
  • -

#6 Sergio Tapia   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Naming accessors and YOU!

Posted 31 May 2011 - 08:31 AM

I dislike the getter/setter method of naming, it feels...dirty to me. I don't know. I just don't like it.

I much prefer the cleanliness of C#'s properties. So I just name my objects like: student.Name instead of student.getName().

For booleans, I try to make it ask a question as I read it:

if (student.IsGraduted)
if (receipt.IsWithinReturnableDates)
//etc.



In Ruby I use the same rules.
Was This Post Helpful? 1
  • +
  • -

#7 Tuishimi   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 5
  • Joined: 21-March 09

Re: Naming accessors and YOU!

Posted 31 May 2011 - 08:55 AM

Use caution. I believe some java frameworks expect a "get" or "set" prefix (I could be wrong). I think there are ways to override that expectation, but they are the default.
Was This Post Helpful? 1
  • +
  • -

#8 calebjonasson   User is offline

  • Enter Title Here
  • member icon

Reputation: 209
  • View blog
  • Posts: 989
  • Joined: 28-February 09

Re: Naming accessors and YOU!

Posted 31 May 2011 - 09:20 AM

Also use caution when not starting the method with a lower case. Some coders will want to strangle you.
Was This Post Helpful? 1
  • +
  • -

#9 Sergio Tapia   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Naming accessors and YOU!

Posted 31 May 2011 - 09:36 AM

Depends on the language really. C# uses ThisTypeOfNotation() instead of thisType().

Use the standards of your language and conform to what the hivemind uses.

This post has been edited by Sergio Tapia: 31 May 2011 - 09:36 AM

Was This Post Helpful? 2
  • +
  • -

#10 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Naming accessors and YOU!

Posted 31 May 2011 - 02:37 PM

I'm with Sergio. You'll find that C# and Java naming guidelines differ from each other in many places. Properties and methods start with capitals, as well as classes/interfaces/delegates. Private and scope variables are lower case.

Anyway, coming from a C# background, you're encouraged to use Properties, which are effectively special methods. Example:

private int someValue;
public int SomeValue{
  get{
    return someValue;
  }
  set{  //you can prepend this with private/protected if need be
    someValue = value; //value is a keyword inside a mutator
  }
}


To the user, it looks and feels like a field, but it's actually a property. Assignment calls the mutator, and getting calls the accessor. It's pretty nice, actually. You get to do this:

SomeObject o = new SomeObject();
o.SomeValue = 5;


And though it looks like you've violated a rule of encapsulation, you actually haven't.

Also, they introduced a shortcut syntax for simple get/set operations.

public int SomeValue {get; set;}


Still a property, just a shortcut. And you can easily add a private variable that it fronts if you need to change things later on.
Was This Post Helpful? 1
  • +
  • -

#11 cfoley   User is offline

  • Cabbage
  • member icon

Reputation: 2410
  • View blog
  • Posts: 5,050
  • Joined: 11-December 07

Re: Naming accessors and YOU!

Posted 01 June 2011 - 01:40 AM

Interesting. Does C# allow overloading of mutators with properties? For example, in Java, I might have these two methods:

private int timeOfDay_seconds;

public void setTime(int hours, int mins, int seconds) {
  timeOfDay_seconds = (hours * 3600) + (mins * 60) + seconds;
}

public void setTime(int hours, int mins) {
  setTime(hours, mins, 0);
}


Was This Post Helpful? 0
  • +
  • -

#12 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Naming accessors and YOU!

Posted 01 June 2011 - 08:23 AM

No, there's no parameters for mutators. Or, perhaps a more accurate explanation is that there's one parameter, and it's the type that you defined the property as.

private DateTime myDate;
public DateTime MyDate{
  get{ return myDate; }
  set{ myDate = value; }
}


The mutator there is effectively the same as

public void setMyDate(DateTime value){ myDate = value; }


You do lose some flexibility like that, since you can't overload it, but you gain the ability to treat your property like a field and still not break encapsulation. It's a give and take. And there's nothing to say you can't include your own setter methods as well, on top of the mutators.

The one dangerous thing you have to remember about these things is to minimize side effects. In java, they're obviously methods, so your mind makes the connection that side effects might just be possible. In C#, they look like fields, so you really don't consider it.

I had to work through a previous co-worker's code. I saw stuff like this all over the code:

this.SomeVal = this.SomeVal;


So I tried to clean it up, only to break the program. Turns out, he had stacked lots of logic in both the accessor and the mutator, and that was his way of calling it without changing the value.

That's an example of bad programming, but it's just something to keep in mind.
Was This Post Helpful? 1
  • +
  • -

#13 cfoley   User is offline

  • Cabbage
  • member icon

Reputation: 2410
  • View blog
  • Posts: 5,050
  • Joined: 11-December 07

Re: Naming accessors and YOU!

Posted 01 June 2011 - 10:20 AM

Now, that's interesting. One of the advantages I always give for using getters and setters instead of public fields is the ability to change the implementation without affecting the interface. I usually give a time class as an example:

class Time {
	private int hours, mins, seconds;
	
	public int getHours()   {return hours;}
	public int getMins()    {return mins;}
	public int getSeconds() {return seconds;}
	
	public void rollHours(int elapsedHours) {
		hours += elapsedHours;
	}

	public void rollMins(int elapsedMins) {
		int totalMins = mins + elapsedMins;
		rollHours(totalMins / 60);
		mins = totalMins % 60;
	}

	public void rollSeconds(int elapsedSeconds) {
		int totalSeconds = seconds + elapsedSeconds;
		rollHours(totalSeconds / 60);
		seconds = totalSeconds % 60;
	}
}


With getters, setters (and rollers) I can easily remove fields as long as the methods behave the same when called. I can rewrite the class as something like this, which is arguably better if you excuse the magic numbers.

class Time {
	private int seconds;
	
	public int getHours()   {return seconds / 3600;}
	public int getMins()    {return (seconds % 3600) / 60 ;}
	public int getSeconds() {return seconds % 60;}
	
	public void rollHours(int elapsedHours) {
		rollSeconds(elapsedHours * 3600);
	}

	public void rollMins(int elapsedMins) {
		rollSeconds(elapsedMins * 60);
	}

	public void rollSeconds(int elapsedSeconds) {
		seconds += elapsedSeconds;
	}
}


Is this flexibility lost with C# parameters?
Was This Post Helpful? 0
  • +
  • -

#14 Sergio Tapia   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Naming accessors and YOU!

Posted 01 June 2011 - 10:34 AM

Using your example:

class Time
{
    private int _seconds;

    private int _hours;
    public int Hours
    {
        set { _hours = value; }
        get 
        {
            return _seconds / 3600;
        }
    }
}

//So calling Time.Hours would call:
Time time = new Time();
Console.WriteLine(time.Hours); //<-- "return _seconds / 3600;"

Was This Post Helpful? 1
  • +
  • -

#15 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Naming accessors and YOU!

Posted 01 June 2011 - 10:36 AM

Nope, it's retained in full.

Here's how I'd write that class:

public class MyTime{
  private int seconds;

  public int Hours { get { return seconds / 3600; } }
  public int Minutes { get { return (seconds % 3600) / 60; }
  public int Seconds { get { return seconds % 60; }

  public void AddSeconds(int seconds){
    this.seconds += seconds;
  }  

  public void AddMinutes(int minutes){
    AddSeconds(minutes * 60);
  }

  public void AddHours(int hours){
    AddHours(hours * 3600);
  }
  
  public MyTime(int seconds){
    this.seconds = seconds;
  }
}
....
//actual use
....

public static void Main(string[] args){
  MyTime t = new MyTime(0);
  t.AddSeconds(60);
  Console.WriteLine(t.Minutes);
  //console output: 1
}



They don't have to map to a private field at all. It's just one of the most common ways you'll see them, just like you'll commonly see getters and setters mapping directly to a private field in Java as well.

Side note: C# interfaces can include Properties in their definition. They are really just methods when compiled to CIL. (Also delegates, but that's something Java doesn't have an analog for.)

Another side note: even though for the most part you can use Properties the same way you'd use any other variable, you can't use them as out or ref method parameters, again, because they're not actually fields, they're methods.

Edit: Sergio, your implementation is a bit misleading, since it allows you to assign to Hours, but does nothing with the value.

This post has been edited by Curtis Rutland: 01 June 2011 - 10:40 AM

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2