programing tip

대소 문자 만 다른 변수 이름을 사용하는 것이 부도덕한가요?

itbloger 2020. 8. 26. 07:38
반응형

대소 문자 만 다른 변수 이름을 사용하는 것이 부도덕한가요?


예를 들어, 다음 코드를 사용하십시오.

var person = new Person();

또는 Pythonistas :

person = Person()

나는 이것이 얼마나 나쁜지 끊임없이 말하지만,이 두 줄의 코드가 부도덕 한 예를 아직 보지 못했다. 나에게 사람은 사람이고 다른 이름을 붙이는 것은 시간 낭비입니다. 구문 강조가 나타나기 며칠 전에는 이것이 큰 일이었을 것이라고 생각합니다. 그러나 요즘에는 변수 이름과는 별개로 유형 이름을 구별하는 것이 매우 쉽습니다. 도대체 여기에서 차이점을 쉽게 알 수 있습니다.

아니면 내가 놓친 것이 있습니까? 그렇다면 문제를 일으키는 코드의 예를 제공하면 도움이 될 것입니다.


이것이 나쁘다고 말하는 사람들의 이유는 무엇입니까? 나는 항상 이것을한다. 유형의 단일 변수에 이름을 지정하는 가장 간단하고 표현적인 방법입니다. 두 개의 Person객체가 필요하면 다음 person과 같은 의미있는 형용사를 접두사 로 붙일 수 있습니다.

fastPerson
slowPerson

그렇지 않으면 그냥

person

나도 괜찮아.


이 패턴을 메서드 서명에서 많이 사용합니다. IMHO를 설명하는 대체 이름을 제공 할 수 없다면 이것에 문제가 없습니다.

사람과 사람의 두 가지 유형이 있다면 그것은 매우 잘못된 것입니다.


나는 임시 객체 참조를 위해 항상 그것을 사용합니다. 원시 데이터 유형에 대한 전염병처럼 피할 것입니다.

Person person = new Person(); // okay

int Int = 42; // pure evil

누군가 그것이 악하다고 말하면 이것이 더 나은지 물어보십시오.

var abc = new Person();

그 사람이 문맥 상 일반적인 사람이라면 "사람"은 정말 좋은 이름입니다. 물론 Person이 코드에서 특정 역할을 가지고 있다면 역할을 사용하여 그녀의 이름을 지정하는 것이 좋습니다.


나는 그렇게 말한 것에 대해 비추천을받을 것이라고 생각하지만 ...

장대 한 살인과 탐욕을 목격 한 지 한 세기가 지난 지금, 우리가 할 수있는 가장 부도덕 한 일이 변수에 이름을 붙이는 것이라면 우리 프로그래머들은 진정으로 축복을 받았습니다.


나는 그것이 반드시 "나쁘다"고 생각하지는 않지만, 어떤 종류의 사람인지 (아마도 많은 가능한 사람 중 한 명만 다루고 있음)과 같이 더 많은 맥락을 제공하도록 자격을 부여 할 수 있다면 다른 사람이 그것을 선택합니다. 위로 더 잘 이해할 수 있습니다.


Jason-이것이 나쁘다고 누가 말했는지 잘 모르겠습니다. 많은 저자가 이것을 클래스 (대문자) 인스턴스 (소문자)를 표현하는 표준 방법으로 사용합니다 .

나는 소문자 변수가 실제로 이것이 인스턴스 일뿐만 아니라 클래스의 이름임을 나에게 전달한다는 것을 알기 때문에 이것을 자주 사용합니다.

누군가가 그 반대에 대해 확고한 주장을하지 않는 한, 나는 확실히 이것을 계속할 것입니다.


그것이 나쁜 것으로 간주되는 이유는 미래에 2 명의 사람이 필요하다면 다음과 같은 코드로 끝날 수 있기 때문입니다.

Person person = new Person ();

Person person2 = new Person ();

그러면 "Bad"에 접하게됩니다. 그러나이 경우 두 사람을 구별하기 위해 원래 사람을 리팩토링해야합니다.

예를 들어 변수 이름 "person"은 개체 "Person"을 완벽하게 설명하는 이름입니다. 그러므로 그것에 전혀 문제가 없습니다.


나는 그것이 무엇인지에 대한 이름을 말합니다 : 변수가 2 마리의 개를 가진 사람을 나타내면 그것을라고 부릅니다 personWith2Dogs. 변수의 범위가 짧으면 (루프 var처럼) 사람이 괜찮습니다.


나는 그것을 내 코드에서 많이 사용하고 그것에 문제가 없다고 생각합니다. 즉, 나는 (아마도) 한 화면보다 긴 메서드에서 사용하지 않을 것이며 Person 클래스의 인스턴스가 여러 개있는 경우 사용하지 않을 것입니다. 이름을 person1, person2, person3으로 지정하지 마세요. 대신 person_to_del, person_to_ban, person_to_update 등과 같이 좀 더 설명적인 것을 사용하세요.


부도덕하지,하지만 글로벌 검색 모두를 찾을 수 Personperson당신이 활성화 대소 문자 구분을하지 않을 경우. 나는 글로벌 검색 / 교체를 쉽게하기 위해 접두사를 선호하지만 절대적으로 헝가리어 나 길거나 복잡한 것은 아닙니다. 그래서 저는 ...

Person클래스 변수 의 인스턴스 변수에 대한 메소드 매개 aPerson변수의 로컬 변수에 thePerson대한 클래스 / 유형myPersonourPerson

드문 경우 p지만 많은 참조가있는 로컬 컨텍스트에서 사용할 수 있지만 일반적으로 루프 인덱스 등에 적용됩니다.


때에 따라 다르지.

If you have a strict capitalization style, so variables begin lowercase (and use either under_scores or camelCase for word breaks), and Classes begin with Capital Letters, then it's obvious that person is a variable and Person is a class, and when somebody understand this, they won't seem to be in overlapping namespaces. (Similarly, people almost never get confused between the verb or noun "polish" and the adjective "Polish".)

If you don't have such a style, then you've got two names that can easily be confused, and differ only in case. That's bad.


What are the exact arguments those people use?

If they don't allow you to use person as a variable name, you might consider to add the 'a' prefix.

aPerson = Person()

I think what you are doing is fine. I think in general it's important to have agreed coding standards.

For instance I use lowerCamelCase for instances, variables and UpperCamelCase for classes e.t.c.

Coding standards should remove this problem.

When I look at succesful open source programs they often have coding standards

http://drupal.org/coding-standards

http://help.joomla.org/content/view/826/125/

http://wiki.rubyonrails.org/rails/pages/CodingStandards

http://lxr.linux.no/linux/Documentation/CodingStyle

Agreeing the coding standards should be the last battle you have over this.

In fact look at the wikipedia entry (from http://en.wikipedia.org/wiki/CamelCase)

Programming and coding style

Internal capitalization is sometimes recommended to indicate word boundaries by the coding style guidelines for writing source code (e.g., the Mesa programming language and the Java programming language). The recommendations contained in some of these guidelines are supported by static analysis tools that check source code for adherence.

These recommendations often distinguish between UpperCamelCase and lowerCamelCase, typically specifying which variety should be used for specific kinds of entities: variables, record fields, methods, procedures, types, etc.

One widely used Java coding style dictates that UpperCamelCase be used for classes, and lowerCamelCase be used for instances and methods.[19] Recognising this usage, some IDEs, such as Eclipse, implement shortcuts based on CamelCase. For instance, in Eclipse's Content assist feature, typing just the upper-case letters of a CamelCase word will suggest any matching class or method name (for example, typing "NPE" and activating content assist could suggest "NullPointerException").

The original Hungarian notation for programming specifies that a lowercase abbreviation for the "usage type" (not data type) should prefix all variable names, with the remainder of the name in UpperCamelCase; as such it is a form of lowerCamelCase. CamelCase is the official convention for file names in Java and for the Amiga personal computer.

Microsoft .NET recommends lowerCamelCase for parameters and non-public fields and UpperCamelCase (aka "Pascal Style") for other types of identifiers.[20]

Python recommends UpperCamelCase for class names.[21]

The NIEM registry requires that XML Data Elements use UpperCamelCase and XML Attributes use lowerCamelCase.

There is no single convention for the inclusion of upper case abbreviations (mainly acronyms and initialisms) within CamelCase names. Approaches include leaving the whole abbreviation in upper case (such as in "useHTTPConnection") and leaving only the first letter in upper case (such as in "useHttpConnection").

Camel case is by no means universal in computing. Users of several modern programming languages, notably those in the Lisp and Forth families, nearly always use hyphens. Among the reasons sometimes given are that doing so does not require shifting on most keyboards, that the words are more readable when they are separated, and that camel case may simply not be reliably preserved in case-insensitive or case-folding languages (such as Common Lisp, that, while technically a case-sensitive language, canonicalizes (folds) identifiers to uppercase by default).


It's possible to make a stronger argument that method names of that kind are not only harmless but can be an indicator of good quality code.

  • An indicator of good code granularity: If your methods are short, single-purpose, and descriptively named, you don't need a lot of information in variable names. If you have long methods that do a lot of things and need to keep track of a lot of context and state, then your variable names need to be more descriptive.

  • An indicator of general-purpose calculations being pushed down into general-purpose methods: if you do an intermediate manipulation of data structures in a business method, for example an array of users has to be deduplicated, you'll have to have variables in scope with names like users[] and deduplicatedUsers[]. If you move the deduplication to a utility method, you can call the method Utils.dedup(array), and you can call the deduplicated array deduplicatedArray or just result.

  • Java decompilers often use a scheme like that for naming local variables (instance and class variables are normally available in the bytecode, but local variables aren't), and the results are more readable than you might expect, in fact often more readable than the original source.

  • See Larry Wall's principle of "Local Ambiguity is OK" - http://www.wall.org/~larry/natural.html .


I'd say that you probably have some specific use in mind whenever you create an object. The type alone very rarely reflects that use.

So if you want to create a new contact in your address book application, you might want to call the variable newContact.

And if you're unit testing your code to check the behaviour of Person objects with no names set, you might want to call them unnamedPerson or something similar.

Calling it simply person forgoes a big chance to make your code self-documenting.


Only if you're programming in VB6. In that case, what you're doing is illegal, but not immoral.


I do it as well, and neither do I understand why it should be 'immoral'. Though I can understand that it 'might' sometimes be confusing, but today we have IDE's with intellisense and syntax highlighting which will make sure that (if you make a mistake and reference your variable instead of your class, and vice versa) you'll see your error quite fast. And we also have the compiler. :)


I also don't see any problem with this practice. As long as there is only one variable of that class, it is easy to write and easy read. Imo, that even applies in a basic text editor. I personally can't recall anyone calling this bad or even immoral. Just continue doing this :)


I think the 'rule' you may be thinking of is intended more for primitive types, and classes where the class name makes a poor variable name.

For example, if you were dealing with calculating the cost of a particular item in an online store, the following code would not be good form:

Decimal _decimal = item.BaseCost + item.Tax;

Instead, a more descriptive name would be advised, such as '_total' , or '_cost'.


The only issue with this sort of thing I've found is if you want the same name for a private member and also a public property.

If these differ only in case, it'll work fine in case-sensitive languages such as C#, but not in VB.NET.

So, for instance, in VB, I'd write

Private _name As String

but

Public Property Name() As String
    Get
        Return _name
    End Get
    Set(ByVal Value As String)
        _name = Value
    End Set
End Property

I'd do the same in C#, so that translation from one to the other is painless. It also makes it a bit less error-prone, since it's very easy to mis-read, or indeed mis-type words that differ only by case.


Not immoral, but if your best name for your variable is the name of the type, something wrong or you just making a proof of concept or something like that. For me a variable name must refer to the meaning in the business context and not to the programming language. It will be more difficult to understand the code.


I often use Person person = new Person() myself. Commonly used in Java/C#.

Although I ended up wondering yesterday why

private enum DataType {NEW, OLD}

doesn't work in C#...

Especially seeing how you can use String, string, Double, double,... at will in C#.


Person person = new Person()

is fine in my book.

Wheh it becomes horrible is when you have:

string Person;
string person;

Very easy to mix up the 2.


What has been expressed to me, other then not meeting our Coding Standards, is avoiding adding confusion when someone else is reading my code. I, personally, see no problem with it, as long as the meaning is clear.

As for CLR types (int,string, etc.) you can use either String or string (etc.) to declare the type, so I would avoid using something like

int Int = 0;
string String = "hi there";

Making capitalization the only difference is dangerous...keep doing this for a big project and I guarantee you'll run into bizarre errors you can't seem to locate.

fastPerson/slowPerson like above are fine...they're descriptive and differentiated from the variable type name...but come on man, calling an int "Int" would be plain lazy.


I would say its never immoral - it really just your base line variable name. If you can't think of a better name, naming it after it's type is a good default.(For complex types only - for built in types its evil) And lots of time there really isn't a better name cause you don't know anything else about the variable. Like with this method

void SaveToDatabase(Person person) {...}

About the only thing else you could reasonably call person is person_to_save or something like that which seems redundant.

However in a lot of cases you can improve on the readability of your code by replacing person with a more descriptive name. For example this is less descriptive

void AddToAccount(Account account, Person person)  {...}

than this

void AddToAccount(Account account, Person dependent)  {...}

However please, please - pretty please don't put an 'a' or 't' in front of the type name. I.E. aPerson for 'a person' or tPerson for 'the person'. Its overly complicated and doesn't add much if any value. Plus you starts to pollute you scope with a bunch of variables that start with a or t which can minimize the value of intelli-sense.


I wouldn't say it's horrible. I usually prefix the name of the variable with 'a' in this sort of thing to show that it's a single instance of the type, so I would do

Person aPerson = new Person();

It makes the code read more naturally I think.


Absolutely nothing wrong with it subject to caveats pointed out by others (summarizing here for convenience): not doing it with primitive types, refactoring the original instance if another instance is added later, not using char-case to differentiate class names, etc.

My rule of thumb? Statements in code should read like simple English sentences.

Person person = new Person();

Employee employee = person.getRole(EMPLOYEE);

Parent parent = person.getRole(PARENT);

person.getFullName();

employee.getSalary();

parent.getChildren();

parent.getFullName(); // assuming decorator pattern at play

if (person.hasRole(EMPLOYEE)) {

  ...

}

And so forth.

If the variable's scope is limited (the encapsulating method is 10-15 lines, for instance) I might even use 'p' instead of 'person'. Shorter variable names are less of a distraction when trying to hold context in your head. Avoid gratuitous prefixes such as 'a' or (shudder) Hungarian notation and offshoots thereof. (Mind you, I have nothing against such prefixes when used in the appropriate context - C++ / COM / ATL / Win32 API code etc., where it helps to keep assignments / typecasting straight).

My two(!) bits :-)

참고URL : https://stackoverflow.com/questions/461231/am-i-immoral-for-using-a-variable-name-that-differs-from-its-type-only-by-case

반응형