cod naspa

Acest forum este dedicat intrebarilor de programare care nu-si au locul in unul din celelalte forumuri
Post Reply
User avatar
Marius Bancila
Fondator
Fondator
Posts: 2343
Joined: 11 Jul 2007, 11:45
Judet: Timiş
Location: Timisoara
Contact:

cod naspa

Post by Marius Bancila » 19 Aug 2008, 18:47

Azi am dat peste o functie care arata asa (am modificat doar numele, cu exceptia lui fRet si fReturn ;) ):

Code: Select all

BOOL DoSomething(INT option)
{
  BOOL fRet;
  BOOL fReturn;;

  switch(option)
  {
    case OPTION_1:
      fRet = TRUE;
      break;
    case OPTION_2;
      fRet = FALSE;
      break;
    case OPTION_3:
      if(...)
      {
        fReturn = CallSomeMethod();
        if(fReturn == TRUE)
        {
          fReturn = CallSomeOtherMethod();
        }
        return fReturn;
      }
      return TRUE;
  }
  return fRet;
}
Va provoc sa-mi aratati aberatii la fel de mari (stiu ca se poate :( ). ;)


Marius Bancila
Fondator Codexpert, Microsoft MVP VC++
Site personal | Blog

User avatar
Silviu Ardelean
Senior
Senior
Posts: 1175
Joined: 12 Jul 2007, 09:22
Judet: Timiş
Location: Timisoara
Contact:

Re: cod naspa

Post by Silviu Ardelean » 19 Aug 2008, 18:53

Foarte tare! :thumbsup:
Mi-a placut in special return-urile - peste tot si pretudindeni. ;) Logica de la case-ul 3 e "brilianta"!

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 20 Aug 2008, 11:03

O initiativa foarte buna!... :)
Am si eu in tolba o multime de cod nashpa.
Unele exemple le-am postat deja prin alte forumuri dar dred ca ar fi bine sa le punem si aici... la colectie.

Iata un hal de destructor:

Code: Select all

CFoo::~CFoo()
{
// ...
    switch(cleaning_option)
    {
    case CLEANING_OPTION_0:
        // perform cleaning for cleaning option 0
        break;
    case CLEANING_OPTION_1:
        // perform cleaning for cleaning option 1
        break;
    // ...
    // ... a lot of cases here
    // ...
    case CLEANING_OPTION_ALL_OTHERS:
        // perform cleaning for all others cleaning options 
        break;
    default:
        // perform the default cleaning
        break;
    }
// ...
}

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 20 Aug 2008, 11:08

Una cu exceptii

Code: Select all

    for(int i = 0; i < n; i++)
    {
        try
        {
            // ...
        }
        catch(...)
        {
            --i; // try again!
        }
    }
// comentariul din blocul catch e cel original. :)

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 20 Aug 2008, 11:37

_ASSERTE everywhere:

Code: Select all

    HRESULT hr = S_OK;

    hr = Function1();
    _ASSERTE(SUCCEEDED(hr));
// ...
    hr = Function2();
    _ASSERTE(SUCCEEDED(hr));
// ...
    hr = Function3();
    _ASSERTE(SUCCEEDED(hr));
// ... s.a.m.d.

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 20 Aug 2008, 12:03

C++ pentru programatorii Java :) (din seria "pointerii is nashpa, referintele sunt cool").

We have a third-party library function which returns a pointer...

Code: Select all

FOO* ThirdPartyLibraryFunction()
{
    // ... on some condition ...
    return NULL;
}
...but further, we are using only references because, unlike pointers, they are all valid.

Code: Select all

// ...
    FOO* pFoo = ThirdPartyLibraryFunction();
    MySafeFunction(*pFoo);
// ...

void MySafeFunction(FOO& rFoo)
{
    rFoo.i = 0; // Bang!
    //...
}

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 20 Aug 2008, 12:31

"GetVector", o functie utila care nu trebuie sa lipseasca din implementarea nici unei clase

Code: Select all

class CFoo
{
// ...
// Implementation
private:
    std::vector<std::string> m_v0;
    std::vector<std::string> m_v1;
    // ...
    std::vector<std::string> m_v9;
    std::vector<std::string>& GetVector(int index);
};

Code: Select all

std::vector<std::string>& CFoo::GetVector(int index)
{
    static std::vector<std::string> dummy_vector;
    if(index == 0)
        return m_v0;
    else if(index == 1)
        return m_v1;
    // ...
    else if(index == 9)
        return m_v9;
    else
        return dummy_vector; // TO AVOID ANNOYING WARNING
}
:)
// in codul original era vorba despre oaresce array-uri MFC (tot pe-acolo ;)).

User avatar
Marius Bancila
Fondator
Fondator
Posts: 2343
Joined: 11 Jul 2007, 11:45
Judet: Timiş
Location: Timisoara
Contact:

Re: cod naspa

Post by Marius Bancila » 20 Aug 2008, 13:24

Ovidiu, mai putine odata te rog, ca nu rezist la atatea lovituri odata. :o Aia cu referintele e dura, dar am vazut-o si eu de destule ori. :?

Inca una, mai degraba distractiva, decat de smuls parul din cap...
http://www.reddit.com/comments/6wx6a/as ... ever_read/
Marius Bancila
Fondator Codexpert, Microsoft MVP VC++
Site personal | Blog

User avatar
Sanda X
Membru
Membru
Posts: 101
Joined: 14 Jul 2007, 21:50

Re: cod naspa

Post by Sanda X » 20 Aug 2008, 14:15

Hmmm... multe de acolo par mai degraba inventate decat culese din programe reale.
Mi-a placut totusi aia cu

Code: Select all

#define sizeof(x) rand()
Curat murdar! :biggrin:
Sanda X

User avatar
cristitm
Membru
Membru
Posts: 68
Joined: 11 Jul 2007, 21:56

Re: cod naspa

Post by cristitm » 20 Aug 2008, 15:35

Of... vai, vai ce exemple. Te miri de ce toate softurile au buguri.
Errare human est!

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 20 Aug 2008, 16:20

cristitm wrote:Of... vai, vai ce exemple. Te miri de ce toate softurile au buguri.
Bug-urile sunt "siguranta zilei de maine" pentru programmeri. ;)

Inca una scurta si "subtila" cu MFC:

Code: Select all

    if(some_error_condition)
    {
        CString strError;
        AfxMessageBox(strError.LoadString(IDS_ERROR_MESSAGE));
    }

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 20 Aug 2008, 16:52

Un exemplu si mai subtil de cod tip "lasa-ma sa te las!". :)

Code: Select all

HRESULT CFoo::AFunction()
{
    HRESULT hr = S_OK;
    try
    {
        // ...
    }
    catch(...)
    {
        hr = E_FAIL;
    }
    return hr;
}
urmat de un exemplu magistral de tratare a "erorii" intoarse de functia de mai sus:

Code: Select all

    HRESULT hr = AFunction();
    if(FAILED(hr))
    {
        CString strError;
        strError.Format(_T("ERROR: %08X"), hr);
        AfxMessageBox(strError);
    }

Dark
Banned
Banned
Posts: 75
Joined: 21 Nov 2007, 19:29
Judet: Bucureşti

Re: cod naspa

Post by Dark » 22 Aug 2008, 17:19

Intr-o vreme am tinut un jurnal cu ce gaseam prin codul unui anume proiect (al carui nume nu-l voi da, caci nu sint badaran).

Incapatinare:

Code: Select all

    while((hIdxFile = CreateFile(pzDbx, GENERIC_READ, 0, NULL, OPEN_ALWAYS, 0, NULL)) == INVALID_HANDLE_VALUE)
    ;
Incapatinare limitata, de data asta cu abuzul creativ al instructiunii for (a se observa unde se face incrementarea):

Code: Select all

        for( int x = 0; (hIdxFile = CreateFile(pzDbx, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL)) == INVALID_HANDLE_VALUE; ) {
            if( ++x == 200 ) {
	            Close();
	            return -1;
            }
        }
Redundanta la putere:

Code: Select all

    std::map<uint,identitylist_t>::iterator iT = m_cStatic.m_cTemplate.find(Type);
    identitylist_t& TypeList = iT == m_cStatic.m_cTemplate.end() ? m_cStatic.m_cTemplate[Type] : iT->second;

    // Operatorul ala adauga cheia daca nu exista, deci gunoiul era echivalent cu:
    // identitylist_t& TypeList = m_cStatic.m_cTemplate[Type];
A treia expresie a instructiunii for e pentru prosti:

Code: Select all

    for( nFold = 0; nFold++ < nFolders; ) 
Rectific: a treia expresie din for e pentru prosti, insa operatorul virgula e pentru doctori docenti:

Code: Select all

    for( int x = 0; s[x++] = c, Data>>c, !Data.eof() && x < 100; ) ;
Regula #1 a obfuscarii: da nume subversive functiilor. In cazul de fata, memcpy() numit erase():

Code: Select all

    void erase(int*l, int*r) { int*e=end(); for( m_nSize-=r-l; r<e; *l++=*r++ ); }
Cine are nevoie de acolade cind avem operatorul virgula? De asemenea, toata lumea stie regulile de precedenta ale operatorilor, deci sa nu punem paranteze ce ar putea incurca Maestrii:

Code: Select all

	while( x < m_cGrid.GetCols() && nXoff + (nW=m_cGrid[x].Width()) < nCx-3 )
		nXoff += nW,
		iB++,
		x++;
La asta mi-a placut comentariul:

Code: Select all

      // It was hard to write, it should be hard to read :)
      NamedArray_s& sArray = (*m_cNameMap.insert( NameMap_t::value_type( cName, NamedArray_s( (DataType_e) nType ) ) ).first).second;
Un exemplu mai complicat care arata mai multe tehnici: folosirea identificatorilor rezervati de standard, alternarea intre exceptii si goto pentru error handling etc.:

Code: Select all

  try{
    if ( pcTex == NULL || pcTex->GetErrorCode() != LBitmap_t::e_BitmapOK )
        goto _Error; // underscore la inceput si litera mare, identificator rezervat. Dar ce conteaza?
    if ( pcAlpha == NULL || pcAlpha->GetErrorCode() != LBitmap_t::e_BitmapOK ) {
      DEFAULT_TRACE << "Can't open alpha file '" << cAlphaPath << "'\n";
      goto _Error;
    }
    if( pcAlpha->GetNumBits() != 8 ) {
      DEFAULT_TRACE << "Alpha file '" << cAlphaPath << "' is not 8bit grey.. dont know how to handle it\n";
      goto _Error;
    }
    if( pcAlpha->GetCLUT() ) {
      DEFAULT_TRACE << "Alpha file '" << cAlphaPath << "' has a color-lookup-table.. dont know how to handle it\n";
      throw;  // aici face throw in loc de goto, ca sa nu ne plictisim
    }
  }
  catch( ... ) {
      goto _Error; // surpriza!
  }

  if( 0 ) { // si lovitura de gratie
_Error:
    DEFAULT_TRACE << "Failed to create composite texture '" << cTexturePath << "'\n";
    cTmpFile = cTexturePath;
  }
Ce ne facem daca ne-am bagat tot codul de initializare intr-un constructor si vrem sa-l apelam dintr-o alta functie (care intimplator e tot un constructor)? Is it a bird? Is it a plane? No, it's inplace new!

Code: Select all

Blob_c::Blob_c(const void*p, uint nSize) 
{ 
    new (this) Blob_c(nSize); 
    memcpy( &m_pData[2], p, nSize );
}
Elementele care se scot singure din containere se pot abuza in moduri nebanuite:

Code: Select all

while( m_pcChild ) {
    delete m_pcChild; // Tema suplimentara: are sau nu voie compilatorul sa faca o bucla infinita, mutind evaluarea conditiei in afara buclei?
}
Un nou concept: crash to preserve data (Acme Data Preserver a luat locul numelui softului):

Code: Select all

  CString cS;
  cS.Format("Error in reading Directory <>,\nDatabase may be corrupt.\Acme Data Preserver will now crash to preserve data.", GetName() );
  AfxMessageBox( cS );
  throw;
Ce faci daca ai vrut sa prinzi o exceptie si te razgindesti?

Code: Select all

try {
    char *pB;
    uint nL;
    Get(nType, nInst, nL, &pB);
    cType.push_back( nType );
    cInst.push_back( nInst );
    cMem .push_back( pB );
    cLen .push_back( nL );
    dbPAssert( nL != 0, ("Unexpected deleted chunk.") );
}
catch(...) {
    throw;
}
Asta da design OOP, cum sa ne facem prieteni cu forta:

Code: Select all

class StackTimer_c : private Timer_c
{
    friend class TimerCount_c;
};
Optimizare la singe, combinata cu o mica diversiune in domeniul numirii functiilor:

Code: Select all

// In clasa TreeNode:
  enum Equal2Head_e { e_NotEq, e_Eq, e_NotPresent };
  Equal2Head_e  m_eIsEqual;
  int IsEqual2Head() const { return int(m_eIsEqual); }

// Mai incolo:
int HandlerView::GetNodeIcon( TreeNode* pcNode ) const {
  return "\5\2\7"[pcNode->IsEqual2Head()];
}
A... ce sa apas? Si chiar daca ar exista OK, de ce mi se da optiunea sa crap programul? A, stiu, "to preserve data".

Code: Select all

  if ( MessageBox( NULL, "Error in AppendToMapping\nTo avoid crash press OK - it'll not export proper mesh", "Prepare for crash", MB_YESNO | MB_ICONERROR ) == IDOK )
    return;
Pointerii din ziua de azi nu mai sint asa de hotariti ca aia de odinioara:

Code: Select all

  if (m_pcSurface)
  {
    return m_pcSurface;
  }
  else
  {
    // Bun, deci surface e 0. Sigur?
    if (m_pcSurface == 0) {
        Identity_t cResourceID((TypeID_e)(GETINSTANCE(e_PlatformKDTree)), m_nSurfaceInstanceID);
        // Ba, sigur-sigur?
        if (m_pcSurface == 0){
          m_pcSurface = ceva irelevant;
        }
    }

    return m_pcSurface;
  }
Instructiunea switch are doua probleme majore: 1. produce cod optim cu orice compilator din era noastra; 2. nu e din STL. Ambele neajunsuri sint rezolvate prompt in felul urmator:

Code: Select all

  std::map<QuestType_e, fCreateQuestFunction> cFunctions;
  cFunctions[e_EscortItem]            = &QuestGenerator_t::CreateEscortItem;
  cFunctions[e_EscortCharacter]       = &QuestGenerator_t::CreateEscortCharacter;
  cFunctions[e_GuardArea]             = &QuestGenerator_t::CreateGuardArea;
  // inca vreo 20 de insertii
  cFunctions[e_GiveItemToCharacter]   = &QuestGenerator_t::CreateGiveItemToCharacter;
  cFunctions[e_TalkToCharacter]       = &QuestGenerator_t::CreateTalkToCharacter;
  fCreateQuestFunction fFunction = cFunctions[eQuestType];
  if(fFunction){
    if(!((this->*fFunction)(cSession))){
      return 0;
    }
  }
  // Functia iese dupa citeva linii, fara a mai folosi cFunctions vreodata
Si sa incheiem in forta. Cistigatorul probei olimpice de inghesuit cit mai multi operatori intr-o expresie este:

Code: Select all

for( uchar*p = m_pData; !++*--p; );

User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi

Re: cod naspa

Post by Ovidiu Cucu » 23 Aug 2008, 15:10

Faina colectie, Dark!

Hai sa mai pun si eu inca una din folclor:

Code: Select all

   if(nAdminsCount == 1) // last administrator
   {
      nRet = AfxMessageBox(_T("You are going to delete the last admin.\n")
                           _T("Further, nobody will be able to administrate users!\n\n")
                           _T("Are you sure?"),
                           MB_YESNO);
   }
   if(nUsersCount == 1) // last user
   {
      nRet = AfxMessageBox(_T("You are going to delete the last user.\n")
                           _T("Nobody will be able to run this application again!\n\n")
                           _T("Are you sure?"),
                           MB_YESNO);
   }
   if(nRet == IDYES)
   {
       // DELETE USER!
   }

User avatar
Popa Alin
Membru
Membru
Posts: 52
Joined: 30 May 2008, 11:00
Judet: Timiş
Location: Timisoara

Re: cod naspa

Post by Popa Alin » 03 Sep 2008, 12:02

for( uchar*p = m_pData; !++*--p; );
Dumnezeule.... nu as vrea sa vad un intreg proiect facut de acest "programator" :)
Great minds disscuss ideas, average minds disscuss events, small minds disscuss people.

Post Reply