Style-off
-
AP0LL0 schrieb:
Aber wie schreibt ihr wirklich euren Code?
Tastatur ?
/************************************************************************** # # Programname: blabla # Version: 13.37 # Datum: 01.01.1909 # Author: Vorname Nachname # Bemerkungen: I'm Batman # **************************************************************************/ #include <iostream> int blabla(); int main () { // Diese Schleife macht blabla while(1==1) { // Noch mehr blablabla } if (1000 > 1) { int x = 0; // Variable X x = 9 / 0; } return 0; } //Diese Funktion macht Bla Bla int blabla() { return 9001; }
-
pumuckl schrieb:
AP0LL0 schrieb:
Aber wie schreibt ihr wirklich euren Code? Macht ihr für euch selbst Kommentare um
Übersicht zu behalten? Macht ihr viele Absätze, viele Tabs?
Wie übersichtlich muss euer Code sein und was seht ihr als übersichtlich an?Kopiert einen Abschnitt eures derzeitigen Projekts und präsentiert ihn hier ungeschminkt.
Ich schreibe meinen Code grundsätzlich so, als ob ich ihn für jmd anderen schreibe. Weil man ja nie weiß, ob man ihn nicht doch mal aus der hand gibt. Ich gebe mir viel Mühe und verbrauche relativ viel Zeit, um meinen Code sauber zu schreiben - siehe auch das Zitat in meiner Signatur
(Das mag einer der Gründe sein warum ich mit meinen privaten Projekten meist nur sehr langsam vorankomme und sie irgendwann im Sande verlaufen. Aber das ist ein anderes Thema...)
Ich fühle mit dir. Ich habe das selbe "Problem", ich benötige manchmal Tage um 300 Zeilen zu schreiben. Jedoch nehme ich es mit der offiziellen code-style Schule nicht ganz so ernst wie andere und benutze sehr viele Tabs um es relativ tabellarisch zu halten.
#define FDRS __internal_read_stub_ typedef class __internal_read_stub_ { enum __cache_layout_enum_{ FDR_PACKET_CACHE, //255 (0-244) FDR_MASTER_NAME = 509 //255 (244-509) }; struct __packet_layout_gen_{ unsigned int _4_vers :4, _2_cmd :2, _8_len :8, _24_off :24; union __sub_prot_data_ { struct __sub_prot_query_data_ { unsigned int _2_qcmd :2, _32_qopt :32; }_34_query; struct __sub_prot_in_data_ { unsigned char _data[249]; }_1992_in; struct __sub_prot_in_msg_ { unsigned int _32_msg :32; unsigned char _name[245]; }_1992_msg; struct __sub_prot_error_ { unsigned int _32_err :32; }_32_err; }_2002_sub_data; }; typedef __packet_layout_gen_* DATA_STUB; private: __w64 unsigned long _ul_fd, //endpoint descriptor _ul_dispatch; //dispatchroutine reference void *_kp_event; //dispatch object prt char *_pc_cache; //object memory (base) ptr SOCKADDR_IN *_p_sa_host; //remote-host address-drescriptior unsigned long static __stdcall __fd_read_routine_( __in void* ); bool static __stdcall __icmp_probe_host_( __in void* ), __tcp_try_create_( __in void* ); }__INT_RS_; typedef __INT_RS_* FDRHANDLE;
-
AP0LL0 schrieb:
...
*grusel*
Da, wenn du mal etwas neueren Code aus meinem Projekt haben willst (ich hatte aber noch nicht die Güte, den für mich oder dich nochmal zu überarbeiten
):
#include <General/Utils.h> #include <Compiler/Qompiler.h> #include <limits> #include <fstream> #include <stdexcept> #include <ctime> #include <iostream> ///time double utils::ExecutionTime() { return clock() / (double)CLOCKS_PER_SEC; } ///strings //if ASCII is defined, str_t and std::string are the same and thus these functions must not be provided twice #if !defined(_ASCII) void utils::strings::Replace(str_t &in, char_t find, char_t replace) { for(size_t pos = 0; pos < in.size(); ++pos) { if(in[pos] == find) in[pos] = replace; } } void utils::strings::Replace(str_t &in, const str_t &find, const str_t &replace) { size_t find_pos = 0, pos = 0; //position in the find string while(pos < in.size()) { find_pos = 0; //check if it matches while (find_pos < find.size() && find[find_pos] == in[pos + find_pos]) ++find_pos; if(find_pos == find.size()) //the strings match { in.replace(pos, find.size(), replace); pos += replace.size(); } else { ++pos; } } } str_t utils::strings::GetReplaced(const str_t &in, char_t find, char_t replace) { str_t ret = in; utils::strings::Replace(ret, find, replace); return ret; } str_t utils::strings::GetReplaced(const str_t &in, const str_t &find, const str_t &replace) { str_t ret = in; utils::strings::Replace(ret, find, replace); return ret; } #endif // !defined(_ASCII) void utils::strings::Replace(std::string &in, char find, char replace) { for(size_t pos = 0; pos < in.size(); ++pos) { if(in[pos] == find) in[pos] = replace; } } void utils::strings::Replace(std::string &in, const std::string &find, const std::string &replace) { size_t find_pos = 0, pos = 0; //position in the find string while(pos < in.size()) { find_pos = 0; //check if it matches while (find_pos < find.size() && find[find_pos] == in[pos + find_pos]) ++find_pos; if(find_pos == find.size()) //the strings match { in.replace(pos, find.size(), replace); pos += replace.size(); } else { ++pos; } } } std::string utils::strings::GetReplaced(const std::string &in, char find, char replace) { std::string ret = in; utils::strings::Replace(ret, find, replace); return ret; } std::string utils::strings::GetReplaced(const std::string &in, const std::string &find, const std::string &replace) { std::string ret = in; utils::strings::Replace(ret, find, replace); return ret; } void utils::strings::ConvertToLower(str_t &what) { for(size_t i = 0; i < what.size(); ++i) what[i] = tolower(what[i]); } size_t utils::binary::GetLeadingOnesCount(unsigned char in) //returns the number of leading ones in binary { //optimized if((in & BIN(10000000)) == BIN(00000000)) return 0; //starting with 0 if((in & BIN(11000000)) == BIN(10000000)) return 1; //the first two bits are 10 if((in & BIN(11100000)) == BIN(11000000)) return 2; //110 if((in & BIN(11110000)) == BIN(11100000)) return 3; //1110 if((in & BIN(11111000)) == BIN(11110000)) return 4; //etc. if((in & BIN(11111100)) == BIN(11111000)) return 5; if((in & BIN(11111110)) == BIN(11111100)) return 6; if(in == BIN(11111110)) return 7; return 8; } size_t utils::binary::GetLeadingZerosCount(char_t in) { int bits = sizeof(in) * 8; int bit_count = bits - 1; //-1 for shifting (32 bits -> shift by 31 to get the first one) for(; bit_count >= 0; --bit_count) if((in & (1 << bit_count)) != 0) break; //now bit_count is at the first binary 0 return bits - bit_count - 1; } utils::numbers::NumberType utils::numbers::GetStringNumberType(str_t in) { size_t len = in.length(); if(len == 0) return utils::numbers::INVALID; //nothing inside size_t pos = 0; bool is_positive = true, is_nonzero = false, is_float = false; //check for signs, increase pos if found and reset is_positive if necessary if(in[0] == _('-')) { ++pos; is_positive = false; } else if(in[0] == _('+')) { ++pos; } //check if no digit is following if(pos == len || !utils::IsDigit(in[pos])) return utils::numbers::INVALID; for(;pos < len; ++pos) //loop over digits following { if(!utils::IsDigit(in[pos])) break; //no digit, go out of the loop if(in[pos] != _('0')) is_nonzero = true; } if(pos < len) //something is following { if(in[pos] == _('.') || in[pos] == _(',')) //a floating number { ++pos; if(pos >= len || !utils::IsDigit(in[pos])) return utils::numbers::INVALID; //no digit following after '.' or ';' //it does not necessarily have to be a floating number, //first check if the digits after the point/comma are not zeros for(;pos < len; ++pos) //loop over digits following { if(!utils::IsDigit(in[pos])) break; //no digit, break if(in[pos] != _('0')) { is_float = true; is_nonzero = true; //only relevant at 0.xx or -0.xx } } //check if something unexpected is following if(pos < len) return utils::numbers::INVALID; } else //no point or comma following, error return utils::numbers::INVALID; } //finally evaluate return value if(!is_nonzero) return utils::numbers::ZERO; //else if(is_float) { if(is_positive) return utils::numbers::FLOAT_POSITIVE; return utils::numbers::FLOAT_NEGATIVE; } if(is_positive) return utils::numbers::INTEGER_POSITIVE; return utils::numbers::INTEGER_NEGATIVE; } str_t const &utils::numbers::GetPlatformSizeTMaxString() { static str_t max_size_t_str = str_t(PLATFORM_SIZE_T_MAX_STR); return max_size_t_str; } ///utils::file str_t utils::file::Read(std::string name) //no str_t, name is ASCII { static std::ifstream in; //we can open it binary because newlines are converted by encoding::FileStringToUTF() to '\n' in.open(name.c_str(), std::ios_base::in | std::ios_base::binary); if(!in.is_open()) { std::string err = "Datei \""; //TODO: translate err += name; err += "\" konnte nicht geoeffnet werden.\n"; throw std::runtime_error(err); //PRIORITY_LOW: make a FileNotOpenedException deriving from std::Exception } std::ostringstream out; out << in.rdbuf(); in.close(); std::string tmp = out.str(); #if defined(_TEST_PRINT_OPEN_FILE_) std::cout << "File: " << name << "\nEncoding: " << encoding::GetEncoding(tmp) << "\n"; #endif //defined(_TEST_PRINT_OPEN_FILE_) return encoding::FileStringToUTF(tmp, name); } void utils::file::Write(std::string name, str_t const &s) //kein str_t, dateiname ist ANSI { static std::ofstream ostr; ostr.open(name.c_str()); if(!ostr.is_open()) { std::string err = "Datei \""; err += name; err += "\" konnte nicht geoeffnet werden.\n"; throw std::runtime_error(err); } ostr << encoding::UTF32To8(s); ostr.close(); }
-
AP0LL0 schrieb:
...
Jedoch nehme ich es mit der offiziellen code-style Schule nicht ganz so ernst wie andere und benutze sehr viele Tabs um es relativ tabellarisch zu halten.
Ist ja Furchtbar, kommen andere damit klar ?
Versuch es so wie wxSkip es gepostet hat.
-
Sheldor schrieb:
AP0LL0 schrieb:
...
Jedoch nehme ich es mit der offiziellen code-style Schule nicht ganz so ernst wie andere und benutze sehr viele Tabs um es relativ tabellarisch zu halten.
Ist ja Furchtbar, kommen andere damit klar ?
Versuch es so wie wxSkip es gepostet hat.Nein, aber muss ja auch keiner. Ich finde es immer sehr irritierend wenn Leute sich wirklich über meinen Code "beschweren" und wollen dass ich ihn ändere.
Codestyle ist für mich eher eine persönliche Angelegenheit. Das ist für mich so als würde ich sagen dass dein Haar nicht richtig aussehen würde und du mehr wie die anderen deine Haare machen solltest, weil es so normal und konventioneller ist. (In Wirklichkeit ist das ja komplett dein Ding, und deine Ästhetik, dein Haar darf dich nur nicht in deiner Leistung einschränken).Ich hatte gehofft hier auch ein paar andere "eigene" Styles zu finden und mir vielleicht etwas abzuschauen. Etwas was mir gefallen hat und dir vielleicht zu Verstehen hilft wonach ich suche. Ich suche nach eigenen Style-Charakteristiken. Ein Beispiel dafür wäre der Post von EOutOfResources, der jeden Anfang und jedes ende mit durchgängigen Kommentar-Balken versehrt und bei seinen Funktions-Deklarationen pro namespace eine Zeile lässt. Es sagt ein bisschen etwas über den Programmierer aus und gibt dem Code eine persönliche Note.
-
AP0LL0 schrieb:
...
Es gibt noch mehr "senkrecht-coder" wie Dich. Zur Zeit seid ihr in der totalen Minderzahl. Aber das betrifft ja nur Datendefinitionen und -Deklarationen.
Im Hauptcode bist Du sicherlich auch waagerecht orientiert, oder?
-
@wxSkip: Was fällt mir an Deinem Code als Fremdleser zuerst ins zweifelnde Auge?
Bitte nur beantworten, wenn Du einverstanden bist, daß der Thread abkippt in ein "Ich zeige was aus der Praxis und jemand meckert rum". Der alte "Ich zeige was aus der Praxis" ist auch schon genial. Weiß nicht, ist der nicht schon kaputt?
Man müßte nochmal zwei neue aufmachen, die streng getrennt sind.
-
Na ja, aktuell ist das zwar nicht mehr wirklich, aber da hat sich eigentlich nicht viel geändert vom Stil her
// Main loop. "HTTP-requests" until video is loaded. (Or exception occurs) int YoutubeLoader::Load(const std::string& url) { using namespace std; if (!m_callback) throw ex::exception("No callback function given!", YTLD_ERROR_CALLBACK); Callback(YTDL_START, g_info_start.length(), g_info_start.c_str()); try { ParseURL(url); while (1) { Callback(YTDL_THREADSTATUS, 0, 0); // If callback returns 0 loop shall end Socket(); SendRequest(); RecvResponse(); switch (atoi(m_http_buf.c_str() + string("HTTP/x.x ").length())) { case 200: GetFlashdata(); break; case 206: LoadVideo(); return 0; case 301: case 302: ParseRedirect(); break; default: throw ex::exception("Unknown HTTP-behavior", atoi(m_http_buf.c_str() + string("HTTP/x.x ").length())); break; } } } // Catches exception thrown by YTDL_THREADSTATUS request catch (int val) { return val; } }
Siehe auch: http://www.c-plusplus.net/forum/282269
-
AP0LL0 schrieb:
Nein, aber muss ja auch keiner. Ich finde es immer sehr irritierend wenn Leute sich wirklich über meinen Code "beschweren" und wollen dass ich ihn ändere.
Solange dir der Style gefällt und du den Code gut lesen kannst musst du ihn ja nicht ändern. (Wäre aber sehr empfehlenswert)
Falls sich die Mitarbeiter beschwerden musst du ihn ändern.Wenn du alleine Arbeitest ist es aber nicht Problematisch, erst wenn das Produkt von jemand anderem weiterentwicklet wird.
Ich hätte z.B nicht wirklich Lust mit dem Quelltext arbeiten zu müssen.
-
Ist aus einem aktuellen Projekt, unbearbeitet, bis auf
* Projektname Copyright und Original Author geändert
* bei "[ snip ]" hab ich jeweils Teile rausgeschnitten (ich kann nicht gut das ganze File hier posten, wäre auch ziemlich gross)Wobei mir gerade auffällt dass das erste Kommentar in Control::PrivateAddChild Mist ist ("do nothing" != "throw exception").
///////////////////////////////////////////////////////////////////////////// // Copyright: Blubb // Original Author: Mein Name ///////////////////////////////////////////////////////////////////////////// #include "PrecompiledHeader.h" #include <Snootch/Gui/Control.h> #include <Snootch/Gui/ChildControlCollection.h> #include <Snootch/Gui/LayoutManager.h> #include <Snootch/Gfx/GfxUtility.h> ///////////////////////////////////////////////////////////////////////////// namespace Snootch { SNOOTCH_DONT_INDENT_NAMESPACE namespace Gui { ///////////////////////////////////////////////////////////////////////////// // [ snip ] void Control::SetLayoutManager(shared_ptr<LayoutManager> const& layoutManager) { if (layoutManager != m_layoutManager) { shared_ptr<EventConnection> dataChangedEventConnection; if (layoutManager) { if (GetLifecyclePhase() == LifecyclePhase_FullyInitialized) { shared_ptr<Event> const dataChangedEvent = layoutManager->GetDataChangedEvent(); if (dataChangedEvent) { dataChangedEventConnection = dataChangedEvent->ConnectWeak( shared_from_this(), &Control::PrivateOnLayoutManagerDataChangedEvent); } } } SetLayoutDirty(); m_layoutManager = layoutManager; m_layoutManagerDataChangedEventConnection = dataChangedEventConnection; } } void Control::PrepareChildren(Gfx::RenderLock& renderLock) { // Prepare in reverse Z order (=render order) BOOST_REVERSE_FOREACH(shared_ptr<Control> const& child, GetChildren().GetVisibleOrdered()) child->PrepareImpl(renderLock); } void Control::RenderChildren(Gfx::RenderLock& renderLock, Vector2F const& offset, GFloat alpha) { // Render in reverse Z order (=overdraw) BOOST_REVERSE_FOREACH(shared_ptr<Control> const& child, GetChildren().GetVisibleOrdered()) child->RenderImpl(renderLock, offset, alpha); } Control* Control::HitTestChildren(Vector2F const& relativePosition) { // Loop through child controls, topmost first. // Stop on the first child controls that wanted the click. // Hit test in forward Z order BOOST_FOREACH(shared_ptr<Control> const& child, GetChildren().GetVisibleOrdered()) { Control* const hit = child->HitTestImpl(child->ParentSpaceToControlSpace(relativePosition)); if (hit) return hit; } return 0; } // [ snip ] void Control::PrivateUpdateParentCollection() { if (m_parentControl) m_parentControl->GetChildren().InternalUpdate(this); } void Control::PrivateSetParentCanvas(Control* parentCanvas) { SNOOTCH_ASSERT(parentCanvas == 0 || parentCanvas->m_isCanvas); if (m_parentCanvas != parentCanvas) { m_parentCanvas = parentCanvas; if (!m_isCanvas) { BOOST_FOREACH(shared_ptr<Control> const& child, GetChildren()) child->PrivateSetParentCanvas(parentCanvas); } } else { #ifdef _DEBUG PrivateCheckParentCanvasHierarchy(parentCanvas); #endif } } void Control::PrivateCheckParentCanvasHierarchy(Control const* parentCanvas) const { #ifdef _DEBUG SNOOTCH_ASSERT(parentCanvas == 0 || parentCanvas->m_isCanvas); SNOOTCH_ASSERT(m_parentCanvas == parentCanvas); if (m_isCanvas) parentCanvas = this; BOOST_FOREACH(shared_ptr<Control> const& child, GetChildren()) child->PrivateCheckParentCanvasHierarchy(parentCanvas); #endif } void Control::PrivateAddChild(shared_ptr<Control> const& child) { SNOOTCH_ASSERT(!child->m_parentControl); SNOOTCH_ASSERT(!child->m_parentCanvas); // If the control already has a parent, do nothing if (child->m_parentControl) throw std::invalid_argument(__FUNCTION__ ": Cannot add control as child that already has a parent."); // Detect loops for (Control* parent = this; parent != 0; parent = parent->m_parentControl) { if (parent == child.get()) { SNOOTCH_ASSERT(0 && "Cannot add control as child: cannot build loops."); throw std::invalid_argument(__FUNCTION__ ": Cannot add control as child: cannot build loops."); } } // Remove capture from child control (and it's children) if (child->HasCapture()) child->PrivateReleaseCapture(true); if (child->m_pathToCapture) child->PrivateStealChildCapture(); // Insert and update parent control pointer m_children->InternalAdd(child); child->m_parentControl = this; // Update parent canvas pointer if (m_isCanvas) child->PrivateSetParentCanvas(this); // This control IS a canvas else if (m_parentCanvas) child->PrivateSetParentCanvas(m_parentCanvas); // This control has a parent canvas // Set parent canvas of the CHILD control and this control's layout dirty // (The parent canvas of the child control can be this control or this control's parent canvas) child->SetParentCanvasDirty(); SetLayoutDirty(); } void Control::PrivateRemoveChild(shared_ptr<Control> const& child) { SNOOTCH_ASSERT(child->m_parentControl == this); if (child->m_parentControl != this) return; // Remove capture if this child control (or one of it's children) has it if (child->HasCapture() || child->m_pathToCapture) { SNOOTCH_ASSERT(m_pathToCapture == child.get()); if (child->HasCapture()) child->PrivateReleaseCapture(true); if (child->m_pathToCapture) child->PrivateStealChildCapture(); SNOOTCH_ASSERT(!m_pathToCapture); } // Mark parent canvas dirty so it gets redrawn child->SetParentCanvasDirty(); // Clear parent control and parent canvas pointers child->PrivateSetParentCanvas(0); child->m_parentControl = 0; // Finally remove from collection m_children->InternalRemove(child); SetLayoutDirty(); } // [ snip ] ///////////////////////////////////////////////////////////////////////////// } // namespace Gui } // namespace Snootch
-
wieso macht ihr alle
void bla(foo) { last; }
und nicht
void bla(foo){ last; }
- welchem optischen Zweck dienen die leeren {- und }-Zeilen?
-
!rr!rr__ schrieb:
last; }
Ih.
-
!rr!rr__ schrieb:
wieso macht ihr alle
void bla(foo) { last; }
und nicht
void bla(foo){ last; }
- welchem optischen Zweck dienen die leeren {- und }-Zeilen?
Ich finde so kann man den Code besser lesen.
Es gibt noch eine Möglichkeit:
int blabla(){ return 1337; }
-
@volkard: Ich weiß nicht, was du meinst, aber erzähl mal, ich sag dir dann meine Meinung dazu
.
-
{ sollte imo auf gleicher Höhe wie } sein. So erkennt man sofort den Block und muss nicht erst umständlich nach dem passenden { zum } suchen oder umgekehrt.
Es sieht einfach deutlich symmetrischer aus und das ist hier auch einfach deutlich schöner.
In Java macht man das wahrscheinlich nicht, weil man da ja Verschachtelungen von Klassen in ctors mit news anbietet, dass man für einen Aufruf sonst 30 Zeilen bräuchte.
Fast noch schöner als die ekligen:
void bla(){ blub;} // oder void bla(){ blub; }
-Konstrukte finde ich:
void bla(){ blub; }
Da sieht man wenigstens, dass die zusammen gehören. Ne Zeile zu sparen ist da total unterkompensierend.Just4fun:
void bla(){ while(true){ blub();} }
usw. ^^
-
wxSkip schrieb:
@volkard: Ich weiß nicht, was du meinst, aber erzähl mal, ich sag dir dann meine Meinung dazu
.
Der große Block in der Mitte erschlägt einen fast. Und macht mich sofort neugierig, weshalb es nicht ein asm bsr oder __builtin_clz ist.
-
Mein Code auf der Arbeit ist eine einzige Katastrophe.
Ich muss immer schnell schnell ans Ziel kommen und genauso sieht es hinterher aus.
Keine Sau interessiert sich dafür wie ich programmiere. Keine Code-Reviews, keine Absegnung des Datenbankschemas, nix. Nur das Klickibunti-Ergebnis zählt.
Wenn ich zwischendurch mal versuche mehr Wert auf guten Stil zu legen, komme ich nur zäh vorwärts. Wenn ich dagegen hacke wie ein Schwein geht alles fix, läuft stabil und jeder ist zufrieden. Vorerst zumindest. Änderungen sind entsprechend schwieriger aber andererseits habe ich genug Zeit bei der hingerotzten Erstimplementierung gespart.Nein, ich bin damit nicht glücklich.
Privat bin ich zehnmal langsamer und gebe sehr mir viel Mühe was reine Ästhetik als auch "Architektur", Objektdesign, Entwurfsmuster, Wiederverwendbarkeit und Anwendung guter OO-Prinzipien betrifft.
-
@Eisflamme: Du übersiehst da ein Problem: Wenn du die Zeile mit der schließenden Klammer änderst, musst du hinten wieder Leerzeichen hinzufügen/löschen und falls sie länger wird als die vorherige, musst du auch noch Leerzeichen in der vorigen Zeile hinzufügen.
Ich habe auch mal Code in dieser Art gesehen:
void foo() { int nLen ; char *pStrPtr ; char pStr[530] ; }
Gleiches gilt natürlich für solche Kommentare:
/************************************************* * Kommentar v1.0 * * Funktionsbeschreibung * *************************************************/
-
@volkard: Meinst du GetStringNumberType()? OK, aber ich habe auch schon Funktionen mit über 1000 Zeilen gesehen...
EDIT: Oh, ich sehe gerade, ich sollte das ostr.close() und das istr.close() in den file-Funktionen entfernen, sonst kommt noch so einer und meint "FILESTREAMS KÖNNEN RAII!!!!!!"
EDIT2: Meinst du vielleicht, ich sollte bei der Funktion einen istringstream nehmen, ein double einlesen und mit dem Ergebnis und fail() das Richtige herausfinden? Das wäre zumindest ähnlich.
-