C # 안티 패턴
간단히 말해서 Java 반 패턴 이 없어서는 안될 자원이라는 것을 알았습니다 . 전문가는 물론 초보자에게도 적합합니다. 아직 C #에서 이와 같은 것을 찾지 못했습니다. 그래서 저는이 질문을 커뮤니티 위키로 열고 모든 사람들이 이것에 대한 지식을 공유하도록 초대 할 것입니다. 나는 C #을 처음 접했기 때문에 이것에 매우 관심이 있지만 일부 안티 패턴으로 시작할 수는 없습니다.
다음은 다른 언어가 아닌 C #에 대해 특히 사실이라고 생각하는 답변입니다.
그냥 복사 / 붙여 넣기를 했어요! 이것들에 대한 댓글도 살펴보세요.
던지기 NullReferenceException
잘못된 예외 발생 :
if (FooLicenceKeyHolder == null)
throw new NullReferenceException();
속성 대 공용 변수
클래스의 공용 변수 (대신 속성 사용).
하지 않는 클래스 간단한 데이터 전송 개체입니다.
bool이 단순한 규칙이 아니라 실제 유형이라는 것을 이해하지 못함
if (myBooleanVariable == true)
{
...
}
또는 더 나은
if (myBooleanVariable != false)
{
...
}
이와 같은 구문은 부울 값의 개념이 관례 일 뿐인 개발자 C
와 C++
개발자 가 자주 사용합니다 (0 == false, 다른 것은 true 임). C # 또는 실제 부울이있는 다른 언어에서는 필요하지 않거나 바람직하지 않습니다.
사용 using()
using
적절한 경우 사용하지 않음 :
object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close. Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away. 2. C# is GC so this doesn't do what was intended anyway.
예외를 잘못 다시 던집니다. 예외를 다시 발생 시키려면 다음을 수행하십시오.
try
{
// do some stuff here
}
catch (Exception ex)
{
throw ex; // INCORRECT
throw; // CORRECT
throw new Exception("There was an error"); // INCORRECT
throw new Exception("There was an error", ex); // CORRECT
}
GC.Collect()
가비지 수집기를 신뢰하는 대신 수집합니다.
나는 이것이 자바와 C # 모두에서 너무 많이 보인다.
if(something == true){
somethingelse = true;
}
보너스 포인트가있는 경우
else{
somethingelse = false;
}
using Microsoft.SharePoint;
'그런가 말했다
다음 코드를 많이 봅니다.
if (i==3)
return true;
else
return false;
해야한다:
return (i==3);
데메테르의 법칙 모욕 :
a.PropertyA.PropertyC.PropertyB.PropertyE.PropertyA =
b.PropertyC.PropertyE.PropertyA;
던지기 NullReferenceException
:
if (FooLicenceKeyHolder == null)
throw new NullReferenceException();
내 눈으로 본 것은 사실이다.
public object GetNull()
{
return null;
}
실제로 앱에서 사용되었으며 null을 반환하는 sp_GetNull과 함께 사용할 저장 프로시 저도있었습니다 ....
내 하루를 만들었습니다.
나는 sp가 고전적인 ASP 사이트에 사용되었다고 생각합니다. .. 결과 집합과 관련이 있습니다. .net은 코드를 .net으로 "변환"하려는 누군가의 아이디어였습니다.
int foo = 100;
int bar = int.Parse(foo.ToString());
또는 더 일반적인 경우 :
object foo = 100;
int bar = int.Parse(foo.ToString());
나는 우리 프로젝트에서 이것을 발견했고 거의 의자를 부러 뜨렸다 ...
DateTime date = new DateTime(DateTime.Today.Year,
DateTime.Today.Month,
DateTime.Today.Day);
나는 종종 이런 종류의 var-abuse를 우연히 발견합니다.
var ok = Bar();
또는 더 나은 :
var i = AnyThing();
그런 식으로 var를 사용하는 것은 의미가 없으며 아무것도 얻지 못합니다. 코드를 따르기 어렵게 만듭니다.
- 대리자 호출 전에 null 테스트가 없습니다 .
- null 검사로 'as'를 사용하는 경우와 try / catch로 캐스트를 사용하는 방법을 알지 못합니다.
- catch 블록 내 'throw exception'대 'throw'.
- StringBuilder를 사용하는 대신 많은 수의 문자열을 인스턴스화합니다.
- 블록 사용의 깊은 중첩 .
bool이 단순한 규칙이 아니라 실제 유형이라는 것을 이해하지 못함
if (myBooleanVariable == true)
{
...
}
또는 더 나은
if (myBooleanVariable != false)
{
...
}
이와 같은 구문은 부울 값의 개념이 관례 일 뿐인 개발자 C
와 C++
개발자 가 자주 사용합니다 (0 == false, 다른 것은 true 임). C # 또는 실제 부울이있는 다른 언어에서는 필요하지 않거나 바람직하지 않습니다.
업데이트 됨 : 명확성을 높이기 위해 마지막 단락을 변경했습니다.
클래스의 공용 변수 (대신 속성 사용).
하지 않는 클래스 간단한 데이터 전송 개체입니다.
토론 및 설명은 아래 주석을 참조하십시오.
나는 이것을 실제로 보았다.
bool isAvailable = CheckIfAvailable();
if (isAvailable.Equals(true))
{
//Do Something
}
isAvailable == true
안티 패턴 손을 아래로 친다 !
이것을 슈퍼 안티 패턴으로 만듭니다!
object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close. Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away. 2. C# is GC so this doesn't do what was intended anyway.
비공개 자동 구현 속성 :
private Boolean MenuExtended { get; set; }
각 메서드의 맨 위에있는 모든 지역 변수를 선언하고 초기화하는 것은 매우 추합니다!
void Foo()
{
string message;
int i, j, x, y;
DateTime date;
// Code
}
두 개의 문자열 안티 패턴
안티 패턴 # 1
문자열에서 null 또는 비어 있는지 확인
//Bad
if( myString == null || myString == "" )
OR
if( myString == null || myString.Length == 0 )
//Good
string.IsNullOrEmpty(myString)
Anti-Pattern # 2 (.NET 4.0에만 해당)
문자열에서 null 또는 공백 또는 공백 확인
//Bad
if( myString == null || myString == "" || myString.Trim() == "")
//Good
string.IsNullOrWhiteSpace(myString)
불필요한 캐스팅 (컴파일러를 신뢰하십시오) :
foreach (UserControl view in workspace.SmartParts)
{
UserControl userControl = (UserControl)view;
views.Add(userControl);
}
if(data != null)
{
variable = data;
}
else
{
variable = new Data();
}
더 잘 쓸 수 있습니다.
variable = (data != null) ? data : new Data();
그리고 더 나은
variable = data ?? new Data();
마지막 코드 목록은 .NET 2.0 이상에서 작동합니다.
억양으로 말하는 것은 항상 나를 잡았습니다.
C ++ 프로그래머 :
if (1 == variable) { }
C #에서는를 입력하면 컴파일러 오류가 발생 if (1 = variable)
하여 발에 총을 쏘는 것에 대해 걱정하는 대신 의도 한대로 코드를 작성할 수 있습니다.
삼항을 사용하지 않는 것은 가끔 C #으로 변환하는 것입니다.
당신은 본다 :
private string foo = string.Empty;
if(someCondition)
foo = "fapfapfap";
else
foo = "squishsquishsquish";
대신에:
private string foo = someCondition ? "fapfapfap" : "squishsquishsquish";
foreach (string list in lists)
{
Button btn = new Button();
btn.Click += new EventHandler(delegate { MessageBox.Show(list); });
}
(설명 및 수정은 링크 참조)
For concating arbitrary number of strings using string concatenation instead of string builder
Exampls
foreach (string anItem in list)
message = message + anItem;
is this considered general ?
public static main(string [] args)
{
quit = false;
do
{
try
{
// application runs here ..
quit = true;
}catch { }
}while(quit == false);
}
I dont know how to explain it, but its like someone catching an exception and retrying the code over and over hoping it works later. Like if a IOException occurs, they just try over and over until it works..
The project I'm on had fifty classes, all inheriting from the same class, that all defined:
public void FormatZipCode(String zipCode) { ... }
Either put it in the parent class, or a utility class off to the side. Argh.
Have you considered browsing through The Daily WTF?
Massively over-complicated 'Page_Load' methods, which want to do everything.
Using properties for anything other than to simply retrieve a value or possibly an inexpensive calculation. If you are accessing a database from your property, you should change it to a method call. Developers expect that method calls might be costly, they don't expect this from properties.
Found this a few times in a system I inherited...
if(condition){
some=code;
}
else
{
//do nothing
}
and vice versa
if(condition){
//do nothing
}
else
{
some=code;
}
ReferenceURL : https://stackoverflow.com/questions/1529604/c-sharp-antipatterns
'your programing' 카테고리의 다른 글
문자열의 문자 수를 제한하고 나머지는 잘라 내기 (0) | 2020.12.31 |
---|---|
Google지도 v3에서 다각형의 중심을 얻는 방법은 무엇입니까? (0) | 2020.12.31 |
점이 선의 오른쪽인지 왼쪽인지 확인하는 방법 (0) | 2020.12.31 |
PHP에서 HTML / XML을 어떻게 구문 분석하고 처리합니까? (0) | 2020.12.31 |
인라인 메서드 본문에서 invokevirtual에 대한 예상치 못한 지침 및 매개 변수 (0) | 2020.12.31 |