<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
    <channel>
        <title>نوشته های Majid</title>
        <link>https://virgool.io/feed/@Majid_karimpanah</link>
        <description>توسعه دهنده نرم افزار</description>
        <language>fa</language>
        <pubDate>2026-07-03 14:31:35</pubDate>
        <image>
            <url>https://files.virgool.io/upload/users/216513/avatar/TTC1z0.png?height=120&amp;width=120</url>
            <title>Majid</title>
            <link>https://virgool.io/@Majid_karimpanah</link>
        </image>

                    <item>
                <title>Top 25 Docker Interview Questions and Answers for 2024</title>
                <link>https://virgool.io/@Majid_karimpanah/top-25-docker-interview-questions-and-answers-for-2024-o0futor1pgqo</link>
                <description>hi guys welcome to this video on dockerinterview questions and answersdocker is a popular devops tool used toautomate the deployment of applicationsin lightweight containers so thatapplications can work efficiently indifferent environmentsdocker was initially released in 2013and since then has become the go tosolution for containerizationin this video we have compiled the mostimportant docker interview questionsthat you might face in a docker ordevops interviewso without further ado let&#x27;s get startedso let&#x27;s go through and you&#x27;re going tobe asked to explain what thearchitecture of docker is and dockerreally is the most popularcontainerization environment so dockeruses a client server architecture andthe docker client is a service whichruns in a command line and then thedocker daemon which is run as a rest apiand within the command line will acceptthe requests and interacts with theoperating system in order to build thedocker images and run the dockercontainers and then the docker image isa template of instructions which is usedto create containers the dockercontainer is an executable package ofapplications and its dependenciestogether and then finally the dockerregistry is a service to host anddistribute docker images among otherusers so you&#x27;ll also be asked to providewhat are the advantages of docker overvirtual machine and and this issomething that comes up veryconsistently in fact um you may want toeven extend it as having what are thedifferences between having a dedicatedmachine a virtual machine and a dockeror docker-like environment and reallythe the arguments for docker are justabsolutely fantastic you know first ofall docker does contain and occupydocket containers occupy significantlyless space than a virtual machine or adedicated machine the boot up time ondocker is significantly faster than a vmcontainers have a much betterperformance as they are hosted in asingle docker image docker is highlyefficient and very easy to scaleparticularly when you start working withkubernetes easily portable acrossmultiple platforms and then finally forspace allocation uh docker data volumescan be shared and reused among multiplecontainers the argument against virtualmachines is significant and particularlyif you&#x27;re going into an olderenvironment where a company is stillusing actual dedicated hardware andhaven&#x27;t moved to a cloud or cloud-likeenvironment your arguments for dockerare going to be very very persuasive bevery clear on what the advantages arefor docker over a virtual machinebecause you want to be able tosuccinctly share them with your team andthis is something that&#x27;s important whenyou&#x27;re going through the interviewprocess but also equally importantparticularly if you&#x27;re working with acompany that&#x27;s transitioning or goingthrough a digital transformation wherethey aren&#x27;t used to working with thetools like docker you need to be able toeffectively share with that team whatthe benefits are so how do we sharedocker containers with different nodesand in this instance what you want to beable to do is leverage the power ofdocker swarm so docker swarm is a toolwhich allows the i.t administrators anddevelopers to create and manage clustersof swarm nodes within the dockerplatform and there are two elements tothe node there&#x27;s the manager node andthen there&#x27;s the the worker node themanager node as you&#x27;d assume manages theentire infrastructure and the workingnode is actually the work of the agentas it gets executed so what are thecommands to create a docker swarm and sohere we have an example of what amanager node would look like and onceyou&#x27;ve created a swarm on your managernode you can now add worker nodes tothat swarm and again when you&#x27;restepping through this process be veryprecise in the execution part that needsto be taken to be able to effectivelycreate a swarm so start with the managernode and then you create a worker nodeand then finally when a node isinitialized as a manager node it canimmediately create a token and thattoken is used for the worker nodes andassociating the ip address with theworker nodes question 17 how to runmultiple containers using a singleservice it is possible to run multiplecontainers a single service by usingdocker compose and docker compose willactually run each of the services inisolation so that they can interact witheach other the language used to writeout the composed files that allow you torun the service is called yaml and yamosstands for yet another markup languageso what is the use of a docker file so adocker file actually is used forcreating docker images using the buildcommand so let&#x27;s go through and show onthe screen what that would look like andthis would be an opportunity where ifyou&#x27;re actually in a technical interviewyou could potentially even ask hey can idraw on a whiteboard and show you whatthe architecture for using the buildcommand would look like and what theprocess would look like um again whenyou&#x27;re going through an interviewprocess as someone who interviews a lotof people one of the things i reallylike is when an interview candidate doessomething that&#x27;s slightly different andin this instance this is a great exampleof where you can stand up to thewhiteboard and actually show what canactually be done through actuallycreating images on the whiteboard veryquickly little square boxes where youcan actually show the flow for creatinga build environment as an architect thisshould be something that you&#x27;recomfortable doing and by doing it in theinterview and certainly you want to askpermission before you actually do it butdoing this in the interview really helpsdemonstrate your comfortable feelings ofworking with these kind of architecturedrawings so back to the question ofcreating a docker file so we go throughand we have a docker file that actuallythen goes ahead and creates the dockerimage which then in turns creates thedocker container and then we are able topush that out up to a docker hub andthen share that docker hub witheverybody else as part of the dockerregistry with the whole network so whatare the differences between docker imageand docker containers so let&#x27;s gothrough the docker image so the dockerimages are templates of a dockercontainer an image is built using adocker file and it stores that dockerfile in a docker repository or a dockerhub and you can use docker hub as anexample and the image layer is a readonly file system the docker container isa collection of the runtime instances ofa docker image and the containers arecreated using docker images and they arestored in the docker daemon and everycontainer is a layer is a read writefile system so you can&#x27;t replace theinformation you can only append to itso while you can actually use yamo orwriting your so a question you can beasked is instead of yammer what can bean alternate file to build dockercompose so yaml is the one that is thedefault but you can also use json so ifyou are comfortable working with jasonand my that is something that you shouldget comfortable with is you want to beable to use that to name your files andas a frame reference json is a logicalway of being able to do value pairedmatching using a javascript like syntaxso you&#x27;re going to be asked to how tocreate a docker container so let&#x27;s gothrough what that would look and we&#x27;llbreak it down task by task so the taskis going to be create a mysql dockercontainer so to do that you want to beable to build a docker image or pullfrom an existing docker image from adocker repository or hub and then youwant to be able to then use docker tocreate a new container which has mysequel from the existing docker imagesimultaneouslythe layer of read write file system isalso created on top of that image andbelow at the bottom of the screen wehave what the commands lines look forthat so what is the difference between aregistry and a repository so let&#x27;s gothrough that so for the docker registryand repository for the registry we havea docker registry is an open sourceserver-side service used for hosting anddistributing docker images whereas incontrast for repositories a collectionof multiple versions of a docker imagein a registry a user can distinguishbetween docker images with their tagnames and then finally on the registrydocker also has its own default retreatcalled docker hub for the repository itis a collection of multiple versions ofdocker images it is stored in a dockerregistry and it has two types of publicand private registry so you can actuallycreate your own enterprise registry soyou&#x27;re gonna be asked you know what arethe cloud platforms that support dockerreally you know lists them all and wehave listed here amazon web servicesmicrosoft azure google cloud rackspacebut you could add in their ibm bluemixcould put in red hat really any of thecloud service providers out there todaydo support docker it&#x27;s just become anindustry standard so what is the purposeof expose and publish commands in dockerso if we go through expose is aninstruction used in docker file whereaspublish is used in docker run commandfor expose it is used to expose portswithin a docker network whereas withpublish it can be used outside of adocker environment for expose it is adocumenting instruction used at the timeof building an image and running acontainer whereas with published is usedas to map a host port to a runningcontainer port for expose is the commandused in docker whereas for publish weuse the command-p for when we&#x27;re doingour command line used in docker andexamples of these are expose 8080 orwith docker we would put in or forpublish we&#x27;d do the example docker rund dash p and then 0.0.0.80a colon 80 as our command line with thatwe have reached the end of this dockerinterview questions videoi hope you enjoyed this video do likeand share it thank you for watching andstay tuned for more from simply learnhi there if you like this videosubscribe to the simply learn youtubechannel and click here to watch similarvideos to nerd up and get certifiedclick here</description>
                <category>Majid</category>
                <author>Majid</author>
                <pubDate>Wed, 15 Nov 2023 09:16:14 +0330</pubDate>
            </item>
                    <item>
                <title>Chapter Two - Meaningful Names (clean code)</title>
                <link>https://virgool.io/@Majid_karimpanah/chapter-two-meaningful-names-clean-code-zc7yvdhiq3ec</link>
                <description>IntroductionNames are everywhere in software. We name our variables, our functions, our arguments,classes, and packages. We name our source files and the directories that contain them. Wename our jar files and war files and ear files. We name and name and name. Because we doso much of it, we’d better do it well. What follows are some simple rules for creatinggood names.Use Intention-Revealing NamesIt is easy to say that names should reveal intent. What we want to impress upon you is thatwe are serious about this. Choosing good names takes time but saves more than it takes.So take care with your names and change them when you find better ones. Everyone whoreads your code (including you) will be happier if you do.The name of a variable, function, or class, should answer all the big questions. Itshould tell you why it exists, what it does, and how it is used. If a name requires a comment,then the name does not reveal its intent https://virgool.io/p/zc7yvdhiq3ec/intd;//elapsedtimeindays The name d reveals nothing. It does not evoke a sense of elapsed time, nor of days. Weshould choose a name that specifies what is being measured and the unit of that measurement: https://virgool.io/p/zc7yvdhiq3ec/intelapsedTimeInDays;  https://virgool.io/p/zc7yvdhiq3ec/intdaysSinceCreation;  https://virgool.io/p/zc7yvdhiq3ec/intdaysSinceModification;  https://virgool.io/p/zc7yvdhiq3ec/intfileAgeInDays; Choosing names that reveal intent can make it much easier to understand and changecode. What is the purpose of this code?getThem(){&amp;amp;quot;&amp;amp;gt; publicListgetThem(){ list1=newArrayList();&amp;amp;quot;&amp;amp;gt; Listlist1=newArrayList();  https://virgool.io/p/zc7yvdhiq3ec/for(int[]x:theList)  https://virgool.io/p/zc7yvdhiq3ec/if(x[0]==4)  https://virgool.io/p/zc7yvdhiq3ec/list1.add(x);  https://virgool.io/p/zc7yvdhiq3ec/returnlist1;  https://virgool.io/p/zc7yvdhiq3ec/%7D Why is it hard to tell what this code is doing? There are no complex expressions.Spacing and indentation are reasonable. There are only three variables and two constantsmentioned. There aren’t even any fancy classes or polymorphic methods, just a list ofarrays (or so it seems).The problem isn’t the simplicity of the code but the implicity of the code (to coin aphrase): the degree to which the context is not explicit in the code itself. The code implicitlyrequires that we know the answers to questions such as:1. What kinds of things are in theList?2. What is the significance of the zeroth subscript of an item in theList?3. What is the significance of the value 4?4. How would I use the list being returned?Avoid DisinformationThe answers to these questions are not present in the code sample, but they could havebeen. Say that we’re working in a mine sweeper game. We find that the board is a list ofcells called theList. Let’s rename that to gameBoard.Each cell on the board is represented by a simple array. We further find that the zerothsubscript is the location of a status value and that a status value of 4 means “flagged.” Justby giving these concepts names we can improve the code considerably:getFlaggedCells(){&amp;amp;quot;&amp;amp;gt; publicListgetFlaggedCells(){ flaggedCells=newArrayList();&amp;amp;quot;&amp;amp;gt; ListflaggedCells=newArrayList();  https://virgool.io/p/zc7yvdhiq3ec/for(int[]cell:gameBoard)  https://virgool.io/p/zc7yvdhiq3ec/if(cell[STATUS_VALUE]==FLAGGED)  https://virgool.io/p/zc7yvdhiq3ec/flaggedCells.add(cell);  https://virgool.io/p/zc7yvdhiq3ec/returnflaggedCells;  https://virgool.io/p/zc7yvdhiq3ec/%7D Notice that the simplicity of the code has not changed. It still has exactly the same numberof operators and constants, with exactly the same number of nesting levels. But the codehas become much more explicit.We can go further and write a simple class for cells instead of using an array of ints.It can include an intention-revealing function (call it isFlagged) to hide the magic numbers.It results in a new version of the function:getFlaggedCells(){&amp;amp;quot;&amp;amp;gt; publicListgetFlaggedCells(){ flaggedCells=newArrayList();&amp;amp;quot;&amp;amp;gt; ListflaggedCells=newArrayList();  https://virgool.io/p/zc7yvdhiq3ec/for(Cellcell:gameBoard)  https://virgool.io/p/zc7yvdhiq3ec/if(cell.isFlagged())  https://virgool.io/p/zc7yvdhiq3ec/flaggedCells.add(cell);  https://virgool.io/p/zc7yvdhiq3ec/returnflaggedCells;  https://virgool.io/p/zc7yvdhiq3ec/%7D With these simple name changes, it’s not difficult to understand what’s going on. This isthe power of choosing good namesAvoid DisinformationProgrammers must avoid leaving false clues that obscure the meaning of code. We shouldavoid words whose entrenched meanings vary from our intended meaning. For example,hp, aix, and sco would be poor variable names because they are the names of Unix platformsor variants. Even if you are coding a hypotenuse and hp looks like a good abbreviation,it could be disinformative.Do not refer to a grouping of accounts as an accountList unless it’s actually a List.The word list means something specific to programmers. If the container holding theaccounts is not actually a List, it may lead to false conclusions.1 So accountGroup orbunchOfAccounts or just plain accounts would be better.Beware of using names which vary in small ways. How long does it take to spot thesubtle difference between a XYZControllerForEfficientHandlingOfStrings in one moduleand, somewhere a little more distant, XYZControllerForEfficientStorageOfStrings? Thewords have frightfully similar shapes.Spelling similar concepts similarly is information. Using inconsistent spellings is disinformation.With modern Java environments we enjoy automatic code completion. Wewrite a few characters of a name and press some hotkey combination (if that) and arerewarded with a list of possible completions for that name. It is very helpful if names forvery similar things sort together alphabetically and if the differences are very obvious,because the developer is likely to pick an object by name without seeing your copiouscomments or even the list of methods supplied by that class.A truly awful example of disinformative names would be the use of lower-case L oruppercase O as variable names, especially in combination. The problem, of course, is thatthey look almost entirely like the constants one and zero, respectively https://virgool.io/p/zc7yvdhiq3ec/inta=l;  https://virgool.io/p/zc7yvdhiq3ec/if(O==l)  https://virgool.io/p/zc7yvdhiq3ec/a=O1;  https://virgool.io/p/zc7yvdhiq3ec/else  https://virgool.io/p/zc7yvdhiq3ec/l=01; The reader may think this a contrivance, but we have examined code where suchthings were abundant. In one case the author of the code suggested using a different fontso that the differences were more obvious, a solution that would have to be passed down toall future developers as oral tradition or in a written document. The problem is conqueredwith finality and without creating new work products by a simple renaming.Make Meaningful DistinctionsProgrammers create problems for themselves when they write code solely to satisfy a compiler or interpreter. For example, because you can’t use the same name to refer to two different things in the same scope, you might be tempted to change one name in an arbitrary way. Sometimes this is done by misspelling one, leading to the surprising situation where correcting spelling errors leads to an inability to compile.22. Consider, for example, the truly hideous practice of creating a variable named klass just because the name class was used for something else.It is not sufficient to add number series or noise words, even though the compiler is satisfied. If names must be different, then they should also mean something different.Number-series naming (a1, a2, .. aN) is the opposite of intentional naming. Such names are not disinformative—they are noninformative; they provide no clue to the author’s intention. Consider: https://virgool.io/p/zc7yvdhiq3ec/edit This function reads much better when source and destination are used for the argument names.Noise words are another meaningless distinction. Imagine that you have a Product class. If you have another called ProductInfo or ProductData, you have made the names different without making them mean anything different. Info and Data are indistinct noise words like a, an, and the.Note that there is nothing wrong with using prefix conventions like a and the so long as they make a meaningful distinction. For example you might use a for all local variables and the for all function arguments.3 The problem comes in when you decide to call a variable theZork because you already have another variable named zork.Noise words are redundant. The word variable should never appear in a variable name. The word table should never appear in a table name. How is NameString better than Name? Would a Name ever be a floating point number? If so, it breaks an earlier rule about disinformation. Imagine finding one class named Customer and another named CustomerObject. What should you understand as the distinction? Which one will represent the best path to a customer’s payment history?There is an application we know of where this is illustrated. we’ve changed the names to protect the guilty, but here’s the exact form of the error: https://virgool.io/p/zc7yvdhiq3ec/getActiveAccount();getActiveAccounts();getActiveAccountInfo(); How are the programmers in this project supposed to know which of these functions to call?In the absence of specific conventions, the variable moneyAmount is indistinguishable from money, customerInfo is indistinguishable from customer, accountData is indistinguishable from account, and theMessage is indistinguishable from message. Distinguish names in such a way that the reader knows what the differences offer.Use Pronounceable NamesHumans are good at words. A significant part of our brains is dedicated to the concept of words. And words are, by definition, pronounceable. It would be a shame not to take advantage of that huge portion of our brains that has evolved to deal with spoken language. So make your names pronounceable.If you can’t pronounce it, you can’t discuss it without sounding like an idiot. “Well, over here on the bee cee arr three cee enn tee we have a pee ess zee kyew int, see?” This matters because programming is a social activity.A company I know has genymdhms (generation date, year, month, day, hour, minute, and second) so they walked around saying “gen why emm dee aich emm ess”. I have an annoying habit of pronouncing everything as written, so I started saying “gen-yah-muddahims.” It later was being called this by a host of designers and analysts, and we still sounded silly. But we were in on the joke, so it was fun. Fun or not, we were tolerating poor naming. New developers had to have the variables explained to them, and then they spoke about it in silly made-up words instead of using proper English terms. Compare https://virgool.io/p/zc7yvdhiq3ec/classDtaRcrd102%7BprivateDategenymdhms;privateDatemodymdhms;privatefinalStringpszqint=%E2%80%9D102%E2%80%9D;/*%E2%80%A6*/%7D; to https://virgool.io/p/zc7yvdhiq3ec/classCustomer%7BprivateDategenerationTimestamp;privateDatemodificationTimestamp;;privatefinalStringrecordId=%E2%80%9D102%E2%80%9D;/*%E2%80%A6*/%7D; Intelligent conversation is now possible: “Hey, Mikey, take a look at this record! The generation timestamp is set to tomorrow’s date! How can that be?”Use Searchable NamesSingle-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text.One might easily grep for MAX_CLASSES_PER_STUDENT, but the number 7 could be more troublesome. Searches may turn up the digit as part of file names, other constant definitions, and in various expressions where the value is used with different intent. It is even worse when a constant is a long number and someone might have transposed digits, thereby creating a bug while simultaneously evading the programmer’s search.Likewise, the name e is a poor choice for any variable for which a programmer might need to search. It is the most common letter in the English language and likely to show up in every passage of text in every program. In this regard, longer names trump shorter names, and any searchable name trumps a constant in code.My personal preference is that single-letter names can ONLY be used as local variables inside short methods. The length of a name should correspond to the size of its scope [N5]. If a variable or constant might be seen or used in multiple places in a body of code, it is imperative to give it a search-friendly name. Once again compare https://virgool.io/p/zc7yvdhiq3ec/edit to https://virgool.io/p/zc7yvdhiq3ec/edit Note that sum, above, is not a particularly useful name but at least is searchable. The intentionally named code makes for a longer function, but consider how much easier it will be to find WORK_DAYS_PER_WEEK than to find all the places where 5 was used and filter the list down to just the instances with the intended meaning.Avoid EncodingsWe have enough encodings to deal with without adding more to our burden. Encoding type or scope information into names simply adds an extra burden of deciphering. It hardly seems reasonable to require each new employee to learn yet another encoding “language” in addition to learning the (usually considerable) body of code that they’ll be working in. It is an unnecessary mental burden when trying to solve a problem. Encoded names are seldom pronounceable and are easy to mis-type.Hungarian NotationIn days of old, when we worked in name-length-challenged languages, we violated this rule out of necessity, and with regret. Fortran forced encodings by making the first letter a code for the type. Early versions of BASIC allowed only a letter plus one digit. Hungarian Notation (HN) took this to a whole new level.HN was considered to be pretty important back in the Windows C API, when everything was an integer handle or a long pointer or a void pointer, or one of several implementations of “string” (with different uses and attributes). The compiler did not check types in those days, so the programmers needed a crutch to help them remember the types.In modern languages we have much richer type systems, and the compilers remember and enforce the types. What’s more, there is a trend toward smaller classes and shorter functions so that people can usually see the point of declaration of each variable they’re using.Java programmers don’t need type encoding. Objects are strongly typed, and editing environments have advanced such that they detect a type error long before you can run a compile! So nowadays HN and other forms of type encoding are simply impediments. They make it harder to change the name or type of a variable, function, or class. They make it harder to read the code. And they create the possibility that the encoding system will mislead the reader. https://virgool.io/p/zc7yvdhiq3ec/PhoneNumberphoneString;//namenotchangedwhentypechanged! Member PrefixesYou also don’t need to prefix member variables with m_ anymore. Your classes and functions should be small enough that you don’t need them. And you should be using an editing environment that highlights or colorizes members to make them distinct. https://virgool.io/p/zc7yvdhiq3ec/publicclassPart%7BprivateStringm_dsc;//ThetextualdescriptionvoidsetName(Stringname)%7Bm_dsc=name;%7D%7D_________________________________________________publicclassPart%7BStringdescription;voidsetDescription(Stringdescription)%7Bthis.description=description;%7D%7D Besides, people quickly learn to ignore the prefix (or suffix) to see the meaningful part of the name. The more we read the code, the less we see the prefixes. Eventually the prefixes become unseen clutter and a marker of older code.Interfaces and ImplementationsThese are sometimes a special case for encodings. For example, say you are building an ABSTRACT FACTORY for the creation of shapes. This factory will be an interface and will be implemented by a concrete class. What should you name them? IShapeFactory and ShapeFactory? I prefer to leave interfaces unadorned. The preceding I, so common in today’s legacy wads, is a distraction at best and too much information at worst. I don’t want my users knowing that I’m handing them an interface. I just want them to know that it’s a ShapeFactory. So if I must encode either the interface or the implementation, I choose the implementation. Calling it ShapeFactoryImp, or even the hideous CShapeFactory, is preferable to encoding the interface.Avoid Mental MappingReaders shouldn’t have to mentally translate your names into other names they already know. This problem generally arises from a choice to use neither problem domain terms nor solution domain terms.This is a problem with single-letter variable names. Certainly a loop counter may be named i or j or k (though never l!) if its scope is very small and no other names can conflict with it. This is because those single-letter names for loop counters are traditional. However, in most other contexts a single-letter name is a poor choice; it’s just a place holder that the reader must mentally map to the actual concept. There can be no worse reason for using the name c than because a and b were already taken.In general programmers are pretty smart people. Smart people sometimes like to show off their smarts by demonstrating their mental juggling abilities. After all, if you can reliably remember that r is the lower-cased version of the url with the host and scheme removed, then you must clearly be very smart.One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.Class NamesClasses and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class. A class name should not be a verb.Method NamesMethods should have verb or verb phrase names like postPayment, deletePage, or save. Accessors, mutators, and predicates should be named for their value and prefixed with get, set, and is according to the javabean standard.4 https://virgool.io/p/zc7yvdhiq3ec/stringname=employee.getName();customer.setName(%E2%80%9Dmike%E2%80%9D);if(paycheck.isPosted())%E2%80%A6 When constructors are overloaded, use static factory methods with names that describe the arguments. For example, https://virgool.io/p/zc7yvdhiq3ec/ComplexfulcrumPoint=Complex.FromRealNumber(23.0); is generally better than https://virgool.io/p/zc7yvdhiq3ec/ComplexfulcrumPoint=newComplex(23.0); Consider enforcing their use by making the corresponding constructors private.Don’t Be CuteIf names are too clever, they will be memorable only to people who share the author’s sense of humor, and only as long as these people remember the joke. Will they know what the function named HolyHandGrenade is supposed to do? Sure, it’s cute, but maybe in this case DeleteItems might be a better name. Choose clarity over entertainment value.Cuteness in code often appears in the form of colloquialisms or slang. For example, don’t use the name whack() to mean kill(). Don’t tell little culture-dependent jokes like eatMyShorts() to mean abort().Say what you mean. Mean what you say.Pick One Word per ConceptPick one word for one abstract concept and stick with it. For instance, it’s confusing to have fetch, retrieve, and get as equivalent methods of different classes. How do you remember which method name goes with which class? Sadly, you often have to remember which company, group, or individual wrote the library or class in order to remember which term was used. Otherwise, you spend an awful lot of time browsing through headers and previous code samples.Modern editing environments like Eclipse and IntelliJ provide context-sensitive clues, such as the list of methods you can call on a given object. But note that the list doesn’t usually give you the comments you wrote around your function names and parameter lists. You are lucky if it gives the parameter names from function declarations. The function names have to stand alone, and they have to be consistent in order for you to pick the correct method without any additional exploration.Likewise, it’s confusing to have a controller and a manager and a driver in the same code base. What is the essential difference between a DeviceManager and a Protocol-Controller? Why are both not controllers or both not managers? Are they both Drivers really? The name leads you to expect two objects that have very different type as well as having different classes.A consistent lexicon is a great boon to the programmers who must use your code.Don’t PunAvoid using the same word for two purposes. Using the same term for two different ideas is essentially a pun.If you follow the “one word per concept” rule, you could end up with many classes that have, for example, an add method. As long as the parameter lists and return values of the various add methods are semantically equivalent, all is well.However one might decide to use the word add for “consistency” when he or she is not in fact adding in the same sense. Let’s say we have many classes where add will create a new value by adding or concatenating two existing values. Now let’s say we are writing a new class that has a method that puts its single parameter into a collection. Should we call this method add? It might seem consistent because we have so many other add methods, but in this case, the semantics are different, so we should use a name like insert or append instead. To call the new method add would be a pun.Our goal, as authors, is to make our code as easy as possible to understand. We want our code to be a quick skim, not an intense study. We want to use the popular paperback model whereby the author is responsible for making himself clear and not the academic model where it is the scholar’s job to dig the meaning out of the paper.Use Solution Domain NamesRemember that the people who read your code will be programmers. So go ahead and use computer science (CS) terms, algorithm names, pattern names, math terms, and so forth. It is not wise to draw every name from the problem domain because we don’t want our coworkers to have to run back and forth to the customer asking what every name means when they already know the concept by a different name.The name AccountVisitor means a great deal to a programmer who is familiar with the VISITOR pattern. What programmer would not know what a JobQueue was? There are lots of very technical things that programmers have to do. Choosing technical names for those things is usually the most appropriate course.Use Problem Domain NamesWhen there is no “programmer-eese” for what you’re doing, use the name from the problem domain. At least the programmer who maintains your code can ask a domain expert what it means.Separating solution and problem domain concepts is part of the job of a good programmer and designer. The code that has more to do with problem domain concepts should have names drawn from the problem domain.Add Meaningful ContextThere are a few names which are meaningful in and of themselves—most are not. Instead, you need to place names in context for your reader by enclosing them in well-named classes, functions, or namespaces. When all else fails, then prefixing the name may be necessary as a last resort.Imagine that you have variables named firstName, lastName, street, houseNumber, city, state, and zipcode. Taken together it’s pretty clear that they form an address. But what if you just saw the state variable being used alone in a method? Would you automatically infer that it was part of an address?You can add context by using prefixes: addrFirstName, addrLastName, addrState, and so on. At least readers will understand that these variables are part of a larger structure. Of course, a better solution is to create a class named Address. Then, even the compiler knows that the variables belong to a bigger concept.Consider the method in Listing 2-1. Do the variables need a more meaningful context? The function name provides only part of the context; the algorithm provides the rest. Once you read through the function, you see that the three variables, number, verb, and pluralModifier, are part of the “guess statistics” message. Unfortunately, the context must be inferred. When you first look at the method, the meanings of the variables are opaque.Listing 2-1 Variables with unclear context. https://virgool.io/p/zc7yvdhiq3ec/privatevoidprintGuessStatistics(charcandidate,intcount)%7BStringnumber;Stringverb;StringpluralModifier;if(count==0)%7Bnumber=%E2%80%9Dno%E2%80%9D;verb=%E2%80%9Dare%E2%80%9D;pluralModifier=%E2%80%9Ds%E2%80%9D;%7Delseif(count==1)%7Bnumber=%E2%80%9D1%E2%80%9D;verb=%E2%80%9Dis%E2%80%9D;pluralModifier=%E2%80%9D%E2%80%9D;%7Delse%7Bnumber=Integer.toString(count);verb=%E2%80%9Dare%E2%80%9D;pluralModifier=%E2%80%9Ds%E2%80%9D;%7DStringguessMessage=String.format(%E2%80%9DThere%s%s%s%s%E2%80%9D,verb,number,candidate,pluralModifier);print(guessMessage);%7D The function is a bit too long and the variables are used throughout. To split the function into smaller pieces we need to create a GuessStatisticsMessage class and make the three variables fields of this class. This provides a clear context for the three variables. They are definitively part of the GuessStatisticsMessage. The improvement of context also allows the algorithm to be made much cleaner by breaking it into many smaller functions. (See Listing 2-2.)Listing 2-2 Variables have a context. https://virgool.io/p/zc7yvdhiq3ec/publicclassGuessStatisticsMessage%7BprivateStringnumber;privateStringverb;privateStringpluralModifier;publicStringmake(charcandidate,intcount)%7BcreatePluralDependentMessageParts(count);returnString.format( Don’t Add Gratuitous ContextIn an imaginary application called “Gas Station Deluxe,” it is a bad idea to prefix every class with GSD. Frankly, you are working against your tools. You type G and press the completion key and are rewarded with a mile-long list of every class in the system. Is that wise? Why make it hard for the IDE to help you?Likewise, say you invented a MailingAddress class in GSD’s accounting module, and you named it GSDAccountAddress. Later, you need a mailing address for your customer contact application. Do you use GSDAccountAddress? Does it sound like the right name? Ten of 17 characters are redundant or irrelevant.Shorter names are generally better than longer ones, so long as they are clear. Add no more context to a name than is necessary.The names accountAddress and customerAddress are fine names for instances of the class Address but could be poor names for classes. Address is a fine name for a class. If I need to differentiate between MAC addresses, port addresses, and Web addresses, I might consider PostalAddress, MAC, and URI. The resulting names are more precise, which is the point of all naming.Final WordsThe hardest thing about choosing good names is that it requires good descriptive skills and a shared cultural background. This is a teaching issue rather than a technical, business, or management issue. As a result many people in this field don’t learn to do it very well.People are also afraid of renaming things for fear that some other developers will object. We do not share that fear and find that we are actually grateful when names change (for the better). Most of the time we don’t really memorize the names of classes and methods. We use the modern tools to deal with details like that so we can focus on whether the code reads like paragraphs and sentences, or at least like tables and data structure (a sentence isn’t always the best way to display data). You will probably end up surprising someone when you rename, just like you might with any other code improvement. Don’t let it stop you in your tracks.Follow some of these rules and see whether you don’t improve the readability of your code. If you are maintaining someone else’s code, use refactoring tools to help resolve these problems. It will pay off in the short term and continue to pay in the long run.</description>
                <category>Majid</category>
                <author>Majid</author>
                <pubDate>Thu, 23 Dec 2021 16:47:35 +0330</pubDate>
            </item>
                    <item>
                <title>Chapter One  (Clean Code)</title>
                <link>https://virgool.io/@Majid_karimpanah/chapter-one-clean-code-r3jd3aqndjku</link>
                <description>You are reading this book for two reasons. First, you are a programmer. Second, you wantto be a better programmer. Good. We need better programmers.This is a book about good programming. It is filled with code. We are going to look atcode from every different direction. We’ll look down at it from the top, up at it from thebottom, and through it from the inside out. By the time we are done, we’re going to know alot about code. What’s more, we’ll be able to tell the difference between good code and badcode. We’ll know how to write good code. And we’ll know how to transform bad code intogood code.There Will Be CodeOne might argue that a book about code is somehow behind the times—that code is nolonger the issue; that we should be concerned about models and requirements instead.Indeed some have suggested that we are close to the end of code. That soon all code willbe generated instead of written. That programmers simply won’t be needed because businesspeople will generate programs from specifications.Nonsense! We will never be rid of code, because code represents the details of therequirements. At some level those details cannot be ignored or abstracted; they have to bespecified. And specifying requirements in such detail that a machine can execute them isprogramming. Such a specification is code.I expect that the level of abstraction of our languages will continue to increase. Ialso expect that the number of domain-specific languages will continue to grow. Thiswill be a good thing. But it will not eliminate code. Indeed, all the specifications writtenin these higher level and domain-specific language will be code! It will still need tobe rigorous, accurate, and so formal and detailed that a machine can understand andexecute it.The folks who think that code will one day disappear are like mathematicians whohope one day to discover a mathematics that does not have to be formal. They are hopingthat one day we will discover a way to create machines that can do what we want ratherthan what we say. These machines will have to be able to understand us so well that theycan translate vaguely specified needs into perfectly executing programs that precisely meetthose needs.This will never happen. Not even humans, with all their intuition and creativity,have been able to create successful systems from the vague feelings of their customers.Indeed, if the discipline of requirements specification has taught us anything, it is thatwell-specified requirements are as formal as code and can act as executable tests of thatcode!Remember that code is really the language in which we ultimately express the requirements.We may create languages that are closer to the requirements. We may create toolsthat help us parse and assemble those requirements into formal structures. But we willnever eliminate necessary precision—so there will always be code.Bad CodeI was recently reading the preface to Kent Beck’s book Implementation Patterns.1 He says, “… this book is based on a rather fragile premise: that good code matters….” A fragile premise? I disagree! I think that premise is one of the most robust, supported, and overloaded of all the premises in our craft (and I think Kent knows it). We know good code matters because we’ve had to deal for so long with its lack.I know of one company that, in the late 80s, wrote a killer app. It was very popular, and lots of professionals bought and used it. But then the release cycles began to stretch. Bugs were not repaired from one release to the next. Load times grew and crashes increased. I remember the day I shut the product down in frustration and never used it again. The company went out of business a short time after that.Two decades later I met one of the early employees of that company and asked him what had happened. The answer confirmed my fears. They had rushed the product to market and had made a huge mess in the code. As they added more and more features, the code got worse and worse until they simply could not manage it any longer. It was the bad code that brought the company down.Have you ever been significantly impeded by bad code? If you are a programmer of any experience then you’ve felt this impediment many times. Indeed, we have a name for it. We call it wading. We wade through bad code. We slog through a morass of tangled brambles and hidden pitfalls. We struggle to find our way, hoping for some hint, some clue, of what is going on; but all we see is more and more senseless code.Of course you have been impeded by bad code. So then—why did you write it?Were you trying to go fast? Were you in a rush? Probably so. Perhaps you felt that you didn’t have time to do a good job; that your boss would be angry with you if you took the time to clean up your code. Perhaps you were just tired of working on this program and wanted it to be over. Or maybe you looked at the backlog of other stuff that you had promised to get done and realized that you needed to slam this module together so you could move on to the next. We’ve all done it.We’ve all looked at the mess we’ve just made and then have chosen to leave it for another day. We’ve all felt the relief of seeing our messy program work and deciding that a working mess is better than nothing. We’ve all said we’d go back and clean it up later. Of course, in those days we didn’t know LeBlanc’s law: Later equals never.The Total Cost of Owning a MessIf you have been a programmer for longer than two or three years, you have probably been slowed down by messy code. The degree of the slowdown can be significant. Over the span of a year or two, teams that were moving very fast at the beginning of a project can find themselves moving at a snail’s pace. Every change they make to the code breaks two or three other parts of the code. No change is trivial. Every addition or modification to the system requires that the tangles, twists, and knots be “understood” so that more tangles, twists, and knots can be added. Over time the mess becomes so big and so deep and so tall, they can not clean it up. There is no way at all.As the mess builds, the productivity of the team continues to decrease, asymptotically approaching zero. As productivity decreases, management does the only thing they can; they add more staff to the project in hopes of increasing productivity. But that new staff is not versed in the design of the system. They don’t know the difference between a change that matches the design intent and a change that thwarts the design intent. Furthermore, they, and everyone else on the team, are under horrific pressure to increase productivity. So they all make more and more messes, driving the productivity ever further toward zero.The Grand Redesign in the SkyEventually the team rebels. They inform management that they cannot continue to develop in this odious code base. They demand a redesign. Management does not want to expend the resources on a whole new redesign of the project, but they cannot deny that productivity is terrible. Eventually they bend to the demands of the developers and authorize the grand redesign in the sky.A new tiger team is selected. Everyone wants to be on this team because it’s a green-field project. They get to start over and create something truly beautiful. But only the best and brightest are chosen for the tiger team. Everyone else must continue to maintain the current system.Now the two teams are in a race. The tiger team must build a new system that does everything that the old system does. Not only that, they have to keep up with the changes that are continuously being made to the old system. Management will not replace the old system until the new system can do everything that the old system does.This race can go on for a very long time. I’ve seen it take 10 years. And by the time it’s done, the original members of the tiger team are long gone, and the current members are demanding that the new system be redesigned because it’s such a mess.If you have experienced even one small part of the story I just told, then you already know that spending time keeping your code clean is not just cost effective; it’s a matter of professional survival.AttitudeHave you ever waded through a mess so grave that it took weeks to do what should have taken hours? Have you seen what should have been a one-line change, made instead in hundreds of different modules? These symptoms are all too common.Why does this happen to code? Why does good code rot so quickly into bad code? We have lots of explanations for it. We complain that the requirements changed in ways that thwart the original design. We bemoan the schedules that were too tight to do things right. We blather about stupid managers and intolerant customers and useless marketing types and telephone sanitizers. But the fault, dear Dilbert, is not in our stars, but in ourselves. We are unprofessional.This may be a bitter pill to swallow. How could this mess be our fault? What about the requirements? What about the schedule? What about the stupid managers and the useless marketing types? Don’t they bear some of the blame?No. The managers and marketers look to us for the information they need to make promises and commitments; and even when they don’t look to us, we should not be shy about telling them what we think. The users look to us to validate the way the requirements will fit into the system. The project managers look to us to help work out the schedule. We are deeply complicit in the planning of the project and share a great deal of the responsibility for any failures; especially if those failures have to do with bad code!“But wait!” you say. “If I don’t do what my manager says, I’ll be fired.” Probably not. Most managers want the truth, even when they don’t act like it. Most managers want good code, even when they are obsessing about the schedule. They may defend the schedule and requirements with passion; but that’s their job. It’s your job to defend the code with equal passion.To drive this point home, what if you were a doctor and had a patient who demanded that you stop all the silly hand-washing in preparation for surgery because it was taking too much time?2 Clearly the patient is the boss; and yet the doctor should absolutely refuse to comply. Why? Because the doctor knows more than the patient about the risks of disease and infection. It would be unprofessional (never mind criminal) for the doctor to comply with the patient.2. When hand-washing was first recommended to physicians by Ignaz Semmelweis in 1847, it was rejected on the basis that doctors were too busy and wouldn’t have time to wash their hands between patient visits.So too it is unprofessional for programmers to bend to the will of managers who don’t understand the risks of making messes.The Primal ConundrumProgrammers face a conundrum of basic values. All developers with more than a few years experience know that previous messes slow them down. And yet all developers feel the pressure to make messes in order to meet deadlines. In short, they don’t take the time to go fast!True professionals know that the second part of the conundrum is wrong. You will not make the deadline by making the mess. Indeed, the mess will slow you down instantly, and will force you to miss the deadline. The only way to make the deadline—the only way to go fast—is to keep the code as clean as possible at all times.The Art of Clean Code?Let’s say you believe that messy code is a significant impediment. Let’s say that you accept that the only way to go fast is to keep your code clean. Then you must ask yourself: “How do I write clean code?” It’s no good trying to write clean code if you don’t know what it means for code to be clean!The bad news is that writing clean code is a lot like painting a picture. Most of us know when a picture is painted well or badly. But being able to recognize good art from bad does not mean that we know how to paint. So too being able to recognize clean code from dirty code does not mean that we know how to write clean code!Writing clean code requires the disciplined use of a myriad little techniques applied through a painstakingly acquired sense of “cleanliness.” This “code-sense” is the key. Some of us are born with it. Some of us have to fight to acquire it. Not only does it let us see whether code is good or bad, but it also shows us the strategy for applying our discipline to transform bad code into clean code.A programmer without “code-sense” can look at a messy module and recognize the mess but will have no idea what to do about it. A programmer with “code-sense” will look at a messy module and see options and variations. The “code-sense” will help that programmer choose the best variation and guide him or her to plot a sequence of behavior preserving transformations to get from here to there.In short, a programmer who writes clean code is an artist who can take a blank screen through a series of transformations until it is an elegantly coded system.What Is Clean Code?There are probably as many definitions as there are programmers. So I asked some very well-known and deeply experienced programmers what they thought.Bjarne Stroustrup, inventor of C++ and author of The C++ Programming LanguageI like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.Bjarne uses the word “elegant.” That’s quite a word! The dictionary in my MacBook® provides the following definitions: pleasingly graceful and stylish in appearance or manner; pleasingly ingenious and simple. Notice the emphasis on the word “pleasing.” Apparently Bjarne thinks that clean code is pleasing to read. Reading it should make you smile the way a well-crafted music box or well-designed car would.Bjarne also mentions efficiency—twice. Perhaps this should not surprise us coming from the inventor of C++; but I think there’s more to it than the sheer desire for speed. Wasted cycles are inelegant, they are not pleasing. And now note the word that Bjarne uses to describe the consequence of that inelegance. He uses the word “tempt.” There is a deep truth here. Bad code tempts the mess to grow! When others change bad code, they tend to make it worse.Pragmatic Dave Thomas and Andy Hunt said this a different way. They used the metaphor of broken windows.3 A building with broken windows looks like nobody cares about it. So other people stop caring. They allow more windows to become broken. Eventually they actively break them. They despoil the facade with graffiti and allow garbage to collect. One broken window starts the process toward decay.3. http://www.pragmaticprogrammer.com/booksellers/2004-12.htmlBjarne also mentions that error handling should be complete. This goes to the discipline of paying attention to details. Abbreviated error handling is just one way that programmers gloss over details. Memory leaks are another, race conditions still another. Inconsistent naming yet another. The upshot is that clean code exhibits close attention to detail.Bjarne closes with the assertion that clean code does one thing well. It is no accident that there are so many principles of software design that can be boiled down to this simple admonition. Writer after writer has tried to communicate this thought. Bad code tries to do too much, it has muddled intent and ambiguity of purpose. Clean code is focused. Each function, each class, each module exposes a single-minded attitude that remains entirely undistracted, and unpolluted, by the surrounding details.Grady Booch, author of Object Oriented Analysis and Design with ApplicationsClean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.Grady makes some of the same points as Bjarne, but he takes a readability perspective. I especially like his view that clean code should read like well-written prose. Think back on a really good book that you’ve read. Remember how the words disappeared to be replaced by images! It was like watching a movie, wasn’t it? Better! You saw the characters, you heard the sounds, you experienced the pathos and the humor.Reading clean code will never be quite like reading Lord of the Rings. Still, the literary metaphor is not a bad one. Like a good novel, clean code should clearly expose the tensions in the problem to be solved. It should build those tensions to a climax and then give the reader that “Aha! Of course!” as the issues and tensions are resolved in the revelation of an obvious solution.I find Grady’s use of the phrase “crisp abstraction” to be a fascinating oxymoron! After all the word “crisp” is nearly a synonym for “concrete.” My MacBook’s dictionary holds the following definition of “crisp”: briskly decisive and matter-of-fact, without hesitation or unnecessary detail. Despite this seeming juxtaposition of meaning, the words carry a powerful message. Our code should be matter-of-fact as opposed to speculative. It should contain only what is necessary. Our readers should perceive us to have been decisive.“Big” Dave Thomas, founder of OTI, godfather of the Eclipse strategyClean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.Big Dave shares Grady’s desire for readability, but with an important twist. Dave asserts that clean code makes it easy for other people to enhance it. This may seem obvious, but it cannot be overemphasized. There is, after all, a difference between code that is easy to read and code that is easy to change.Dave ties cleanliness to tests! Ten years ago this would have raised a lot of eyebrows. But the discipline of Test Driven Development has made a profound impact upon our industry and has become one of our most fundamental disciplines. Dave is right. Code, without tests, is not clean. No matter how elegant it is, no matter how readable and accessible, if it hath not tests, it be unclean.Dave uses the word minimal twice. Apparently he values code that is small, rather than code that is large. Indeed, this has been a common refrain throughout software literature since its inception. Smaller is better.Dave also says that code should be literate. This is a soft reference to Knuth’s literate programming.4 The upshot is that the code should be composed in such a form as to make it readable by humans.4. [Knuth92].Michael Feathers, author of Working Effectively with Legacy CodeI could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought about by the code’s author, and if you try to imagine improvements, you’re led back to where you are, sitting in appreciation of the code someone left for you—code left by someone who cares deeply about the craft.One word: care. That’s really the topic of this book. Perhaps an appropriate subtitle would be How to Care for Code.Michael hit it on the head. Clean code is code that has been taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.Ron Jeffries, author of Extreme Programming Installed and Extreme Programming Adventures in C#Ron began his career programming in Fortran at the Strategic Air Command and has written code in almost every language and on almost every machine. It pays to consider his words carefully.In recent years I begin, and nearly end, with Beck’s rules of simple code. In priority order, simple code:• Runs all the tests;• Contains no duplication;• Expresses all the design ideas that are in the system;• Minimizes the number of entities such as classes, methods, functions, and the like.Of these, I focus mostly on duplication. When the same thing is done over and over, it’s a sign that there is an idea in our mind that is not well represented in the code. I try to figure out what it is. Then I try to express that idea more clearly.Expressiveness to me includes meaningful names, and I am likely to change the names of things several times before I settle in. With modern coding tools such as Eclipse, renaming is quite inexpensive, so it doesn’t trouble me to change. Expressiveness goes beyond names, however. I also look at whether an object or method is doing more than one thing. If it’s an object, it probably needs to be broken into two or more objects. If it’s a method, I will always use the Extract Method refactoring on it, resulting in one method that says more clearly what it does, and some submethods saying how it is done.Duplication and expressiveness take me a very long way into what I consider clean code, and improving dirty code with just these two things in mind can make a huge difference. There is, however, one other thing that I’m aware of doing, which is a bit harder to explain.After years of doing this work, it seems to me that all programs are made up of very similar elements. One example is “find things in a collection.” Whether we have a database of employee records, or a hash map of keys and values, or an array of items of some kind, we often find ourselves wanting a particular item from that collection. When I find that happening, I will often wrap the particular implementation in a more abstract method or class. That gives me a couple of interesting advantages.I can implement the functionality now with something simple, say a hash map, but since now all the references to that search are covered by my little abstraction, I can change the implementation any time I want. I can go forward quickly while preserving my ability to change later.In addition, the collection abstraction often calls my attention to what’s “really” going on, and keeps me from running down the path of implementing arbitrary collection behavior when all I really need is a few fairly simple ways of finding what I want.Reduced duplication, high expressiveness, and early building of simple abstractions. That’s what makes clean code for me.Here, in a few short paragraphs, Ron has summarized the contents of this book. No duplication, one thing, expressiveness, tiny abstractions. Everything is there.Ward Cunningham, inventor of Wiki, inventor of Fit, coinventor of eXtreme Programming. Motive force behind Design Patterns. Smalltalk and OO thought leader. The godfather of all those who care about code.You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem.Statements like this are characteristic of Ward. You read it, nod your head, and then go on to the next topic. It sounds so reasonable, so obvious, that it barely registers as something profound. You might think it was pretty much what you expected. But let’s take a closer look.“… pretty much what you expected.” When was the last time you saw a module that was pretty much what you expected? Isn’t it more likely that the modules you look at will be puzzling, complicated, tangled? Isn’t misdirection the rule? Aren’t you used to flailing about trying to grab and hold the threads of reasoning that spew forth from the whole system and weave their way through the module you are reading? When was the last time you read through some code and nodded your head the way you might have nodded your head at Ward’s statement?Ward expects that when you read clean code you won’t be surprised at all. Indeed, you won’t even expend much effort. You will read it, and it will be pretty much what you expected. It will be obvious, simple, and compelling. Each module will set the stage for the next. Each tells you how the next will be written. Programs that are that clean are so profoundly well written that you don’t even notice it. The designer makes it look ridiculously simple like all exceptional designs.And what about Ward’s notion of beauty? We’ve all railed against the fact that our languages weren’t designed for our problems. But Ward’s statement puts the onus back on us. He says that beautiful code makes the language look like it was made for the problem! So it’s our responsibility to make the language look simple! Language bigots everywhere, beware! It is not the language that makes programs appear simple. It is the programmer that make the language appear simple!Schools of ThoughtWhat about me (Uncle Bob)? What do I think clean code is? This book will tell you, in hideous detail, what I and my compatriots think about clean code. We will tell you what we think makes a clean variable name, a clean function, a clean class, etc. We will present these opinions as absolutes, and we will not apologize for our stridence. To us, at this point in our careers, they are absolutes. They are our school of thought about clean code.Martial artists do not all agree about the best martial art, or the best technique within a martial art. Often master martial artists will form their own schools of thought and gather students to learn from them. So we see Gracie Jiu Jistu, founded and taught by the Gracie family in Brazil. We see Hakkoryu Jiu Jistu, founded and taught by Okuyama Ryuho in Tokyo. We see Jeet Kune Do, founded and taught by Bruce Lee in the United States.Students of these approaches immerse themselves in the teachings of the founder. They dedicate themselves to learn what that particular master teaches, often to the exclusion of any other master’s teaching. Later, as the students grow in their art, they may become the student of a different master so they can broaden their knowledge and practice. Some eventually go on to refine their skills, discovering new techniques and founding their own schools.None of these different schools is absolutely right. Yet within a particular school we act as though the teachings and techniques are right. After all, there is a right way to practice Hakkoryu Jiu Jitsu, or Jeet Kune Do. But this rightness within a school does not invalidate the teachings of a different school.Consider this book a description of the Object Mentor School of Clean Code. The techniques and teachings within are the way that we practice our art. We are willing to claim that if you follow these teachings, you will enjoy the benefits that we have enjoyed, and you will learn to write code that is clean and professional. But don’t make the mistake of thinking that we are somehow “right” in any absolute sense. There are other schools and other masters that have just as much claim to professionalism as we. It would behoove you to learn from them as well.Indeed, many of the recommendations in this book are controversial. You will probably not agree with all of them. You might violently disagree with some of them. That’s fine. We can’t claim final authority. On the other hand, the recommendations in this book are things that we have thought long and hard about. We have learned them through decades of experience and repeated trial and error. So whether you agree or disagree, it would be a shame if you did not see, and respect, our point of view.We Are AuthorsThe @author field of a Javadoc tells us who we are. We are authors. And one thing about authors is that they have readers. Indeed, authors are responsible for communicating well with their readers. The next time you write a line of code, remember you are an author, writing for readers who will judge your effort.You might ask: How much is code really read? Doesn’t most of the effort go into writing it?Have you ever played back an edit session? In the 80s and 90s we had editors like Emacs that kept track of every keystroke. You could work for an hour and then play back your whole edit session like a high-speed movie. When I did this, the results were fascinating.The vast majority of the playback was scrolling and navigating to other modules!Bob enters the module.He scrolls down to the function needing change.He pauses, considering his options.Oh, he’s scrolling up to the top of the module to check the initialization of a variable.Now he scrolls back down and begins to type.Ooops, he’s erasing what he typed!He types it again.He erases it again!He types half of something else but then erases that!He scrolls down to another function that calls the function he’s changing to see how it is called.He scrolls back up and types the same code he just erased.He pauses.He erases that code again!He pops up another window and looks at a subclass. Is that function overridden?…You get the drift. Indeed, the ratio of time spent reading vs. writing is well over 10:1. We are constantly reading old code as part of the effort to write new code.Because this ratio is so high, we want the reading of code to be easy, even if it makes the writing harder. Of course there’s no way to write code without reading it, so making it easy to read actually makes it easier to write.There is no escape from this logic. You cannot write code if you cannot read the surrounding code. The code you are trying to write today will be hard or easy to write depending on how hard or easy the surrounding code is to read. So if you want to go fast, if you want to get done quickly, if you want your code to be easy to write, make it easy to read.The Boy Scout RuleIt’s not enough to write the code well. The code has to be kept clean over time. We’ve all seen code rot and degrade as time passes. So we must take an active role in preventing this degradation.The Boy Scouts of America have a simple rule that we can apply to our profession.Leave the campground cleaner than you found it.55. This was adapted from Robert Stephenson Smyth Baden-Powell’s farewell message to the Scouts: “Try and leave this world a little better than you found it…”If we all checked-in our code a little cleaner than when we checked it out, the code simply could not rot. The cleanup doesn’t have to be something big. Change one variable name for the better, break up one function that’s a little too large, eliminate one small bit of duplication, clean up one composite if statement.Can you imagine working on a project where the code simply got better as time passed? Do you believe that any other option is professional? Indeed, isn’t continuous improvement an intrinsic part of professionalism?Prequel and PrinciplesIn many ways this book is a “prequel” to a book I wrote in 2002 entitled Agile Software Development: Principles, Patterns, and Practices (PPP). The PPP book concerns itself with the principles of object-oriented design, and many of the practices used by professional developers. If you have not read PPP, then you may find that it continues the story told by this book. If you have already read it, then you’ll find many of the sentiments of that book echoed in this one at the level of code.In this book you will find sporadic references to various principles of design. These include the Single Responsibility Principle (SRP), the Open Closed Principle (OCP), and the Dependency Inversion Principle (DIP) among others. These principles are described in depth in PPP.ConclusionBooks on art don’t promise to make you an artist. All they can do is give you some of the tools, techniques, and thought processes that other artists have used. So too this book cannot promise to make you a good programmer. It cannot promise to give you “code-sense.” All it can do is show you the thought processes of good programmers and the tricks, techniques, and tools that they use.Just like a book on art, this book will be full of details. There will be lots of code. You’ll see good code and you’ll see bad code. You’ll see bad code transformed into good code. You’ll see lists of heuristics, disciplines, and techniques. You’ll see example after example. After that, it’s up to you.Remember the old joke about the concert violinist who got lost on his way to a performance? He stopped an old man on the corner and asked him how to get to Carnegie Hall. The old man looked at the violinist and the violin tucked under his arm, and said: “Practice, son. Practice!”Bibliography[Beck07]: Implementation Patterns, Kent Beck, Addison-Wesley, 2007.[Knuth92]: Literate Programming, Donald E. Knuth, Center for the Study of Language and Information, Leland Stanford Junior University, 1992.</description>
                <category>Majid</category>
                <author>Majid</author>
                <pubDate>Wed, 22 Dec 2021 15:33:46 +0330</pubDate>
            </item>
                    <item>
                <title>Introduction (Clean Code)</title>
                <link>https://virgool.io/@Majid_karimpanah/introduction-r8hdefnns3w5</link>
                <description>Which door represents your code? Which door represents your team or your company?Why are we in that room? Is this just a normal code review or have we found a stream ofhorrible problems shortly after going live? Are we debugging in a panic, poring over codethat we thought worked? Are customers leaving in droves and managers breathing downour necks? How can we make sure we wind up behind the right door when the going getstough? The answer is: craftsmanship.There are two parts to learning craftsmanship: knowledge and work. You must gainthe knowledge of principles, patterns, practices, and heuristics that a craftsman knows, andyou must also grind that knowledge into your fingers, eyes, and gut by working hard andpracticing.I can teach you the physics of riding a bicycle. Indeed, the classical mathematics isrelatively straightforward. Gravity, friction, angular momentum, center of mass, and soforth, can be demonstrated with less than a page full of equations. Given those formulae Icould prove to you that bicycle riding is practical and give you all the knowledge youneeded to make it work. And you’d still fall down the first time you climbed on that bike.Coding is no different. We could write down all the “feel good” principles of cleancode and then trust you to do the work (in other words, let you fall down when you get onthe bike), but then what kind of teachers would that make us, and what kind of studentwould that make you?No. That’s not the way this book is going to work.Learning to write clean code is hard work. It requires more than just the knowledge ofprinciples and patterns. You must sweat over it. You must practice it yourself, and watchyourself fail. You must watch others practice it and fail. You must see them stumble andretrace their steps. You must see them agonize over decisions and see the price they pay formaking those decisions the wrong way.Be prepared to work hard while reading this book. This is not a “feel good” book thatyou can read on an airplane and finish before you land. This book will make you work, andwork hard. What kind of work will you be doing? You’ll be reading code—lots of code.And you will be challenged to think about what’s right about that code and what’s wrongwith it. You’ll be asked to follow along as we take modules apart and put them backtogether again. This will take time and effort; but we think it will be worth it.We have divided this book into three parts. The first several chapters describe the principles,patterns, and practices of writing clean code. There is quite a bit of code in thesechapters, and they will be challenging to read. They’ll prepare you for the second sectionto come. If you put the book down after reading the first section, good luck to you!The second part of the book is the harder work. It consists of several case studies ofever-increasing complexity. Each case study is an exercise in cleaning up some code—oftransforming code that has some problems into code that has fewer problems. The detail inthis section is intense. You will have to flip back and forth between the narrative and thecode listings. You will have to analyze and understand the code we are working with andwalk through our reasoning for making each change we make. Set aside some timebecause this should take you days.The third part of this book is the payoff. It is a single chapter containing a list of heuristicsand smells gathered while creating the case studies. As we walked through andcleaned up the code in the case studies, we documented every reason for our actions as aIntroduction heuristic or smell. We tried to understand our own reactions to the code we were readingand changing, and worked hard to capture why we felt what we felt and did what we did.The result is a knowledge base that desribes the way we think when we write, read, andclean code.This knowledge base is of limited value if you don’t do the work of carefully readingthrough the case studies in the second part of this book. In those case studies we have carefullyannotated each change we made with forward references to the heuristics. These forwardreferences appear in square brackets like this: [H22]. This lets you see the context inwhich those heuristics were applied and written! It is not the heuristics themselves that areso valuable, it is the relationship between those heuristics and the discrete decisions wemade while cleaning up the code in the case studies.To further help you with those relationships, we have placed a cross-reference at the endof the book that shows the page number for every forward reference. You can use it to lookup each place where a certain heuristic was applied.If you read the first and third sections and skip over the case studies, then you willhave read yet another “feel good” book about writing good software. But if you take thetime to work through the case studies, following every tiny step, every minute decision—ifyou put yourself in our place, and force yourself to think along the same paths that wethought, then you will gain a much richer understanding of those principles, patterns, practices,and heuristics. They won’t be “feel good” knowledge any more. They’ll have beenground into your gut, fingers, and heart. They’ll have become part of you in the same waythat a bicycle becomes an extension of your will when you have mastered how to ride it.AcknowledgmentsThank you to my two artists, Jeniffer Kohnke and Angela Brooks. Jennifer is responsiblefor the stunning and creative pictures at the start of each chapter and also for the portraitsof Kent Beck, Ward Cunningham, Bjarne Stroustrup, Ron Jeffries, Grady Booch, DaveThomas, Michael Feathers, and myself.Angela is responsible for the clever pictures that adorn the innards of each chapter.She has done quite a few pictures for me over the years, including many of the inside picturesin Agile Software Develpment: Principles, Patterns, and Practices. She is also myfirstborn in whom I am well pleased.A special thanks goes out to my reviewers Bob Bogetti, George Bullock, JeffreyOverbey, and especially Matt Heusser. They were brutal. They were cruel. They wererelentless. They pushed me hard to make necessary improvements.Thanks to my publisher, Chris Guzikowski, for his support, encouragement, and jovialcountenance. Thanks also to the editorial staff at Pearson, including Raina Chrobak forkeeping me honest and punctual.Thanks to Micah Martin, and all the guys at 8th Light (www.8thlight.com) for theirreviews and encouragement.Thanks to all the Object Mentors, past, present, and future, including: Bob Koss,Michael Feathers, Michael Hill, Erik Meade, Jeff Langr, Pascal Roy, David Farber, BrettSchuchert, Dean Wampler, Tim Ottinger, Dave Thomas, James Grenning, Brian Button,Ron Jeffries, Lowell Lindstrom, Angelique Martin, Cindy Sprague, Libby Ottinger, JoleenCraig, Janice Brown, Susan Rosso, et al.Thanks to Jim Newkirk, my friend and business partner, who taught me more thanI think he realizes. Thanks to Kent Beck, Martin Fowler, Ward Cunningham, BjarneStroustrup, Grady Booch, and all my other mentors, compatriots, and foils. Thanks to JohnVlissides for being there when it counted. Thanks to the guys at Zebra for allowing me torant on about how long a function should be.And, finally, thank you for reading these thank yous.On the CoverThe image on the cover is M104: The Sombrero Galaxy. M104 is located in Virgo and isjust under 30 million light-years from us. At it’s core is a supermassive black hole weighingin at about a billion solar masses.Does the image remind you of the explosion of the Klingon power moon Praxis? Ivividly remember the scene in Star Trek VI that showed an equatorial ring of debris flyingaway from that explosion. Since that scene, the equatorial ring has been a common artifactin sci-fi movie explosions. It was even added to the explosion of Alderaan in later editionsof the first Star Wars movie.What caused this ring to form around M104? Why does it have such a huge centralbulge and such a bright and tiny nucleus? It looks to me as though the central black holelost its cool and blew a 30,000 light-year hole in the middle of the galaxy. Woe befell anycivilizations that might have been in the path of that cosmic disruption.Supermassive black holes swallow whole stars for lunch, converting a sizeable fractionof their mass to energy. E = MC2 is leverage enough, but when M is a stellar mass:Look out! How many stars fell headlong into that maw before the monster was satiated?Could the size of the central void be a hint?The image of M104 on the cover is acombination of the famous visible light photographfrom Hubble (right), and the recentinfrared image from the Spitzer orbitingobservatory (below, right). It’s the infraredimage that clearly shows us the ring natureof the galaxy. In visible light we only see thefront edge of the ring in silhouette. The centralbulge obscures the rest of the ring.But in the infrared, the hot particles inthe ring shine through the central bulge. Thetwo images combined give us a view we’venot seen before and imply that long ago itwas a raging inferno of activity.</description>
                <category>Majid</category>
                <author>Majid</author>
                <pubDate>Wed, 22 Dec 2021 14:11:26 +0330</pubDate>
            </item>
                    <item>
                <title>سوالات مصاحبه ی لاراول و php</title>
                <link>https://virgool.io/@Majid_karimpanah/%D8%B3%D9%88%D8%A7%D9%84%D8%A7%D8%AA-%D9%85%D8%B5%D8%A7%D8%AD%D8%A8%D9%87-%DB%8C-%D9%84%D8%A7%D8%B1%D8%A7%D9%88%D9%84-%D9%88-php-phorbgx5rlfi</link>
                <description>مقدمههر برنامه نویسی که بخواهد در شرکتی مشغول بکار شود اولین غول ، رویارویی با مدیر فنی شرکت است که باید بتوانید اورا قانع کنیدبعضی از مدیران فنی هستند در زمان مصاحبه سوالی را میپرسند  ، اگر شما جوابی درست بدید قبول میکنند اما دسته ی دیگر مدیران فنی هستند که دنبال بهترین جواب هستند و اگر شما آن جواب بهینه را ندهید بدون شک میروند سراغ سوال بعد و بعد از اتمام مصاحبه چنان وانمود میکنند که از شما خوششان آمده اماتراژدی ماجرا اینجاست که وقتی میرسید خانه ایمیل می آید که با وجود توانمندی های شما فعلا از همکاری با شما معذوریم .اینجاست که این ایمیل مانند پتک چنان بر سر انسان فرود می آید که گویی تمام رویاهایش نابود شدهاما سوالات :اگر برای مصاحبه لاراول رفته باشید اصلی ترین سوال هایی که میپرسند:-مفاهیم شی گرایی؟کلاس ها -ارث بری – اینترفیس – ابسترک – متغیر ها -سطح دسترسی توابع و متغیر ها در کلاس و کلاس های ارث برده شده و…-دیزاین پترن ها؟ مثلامثلا میپرسند قبل از استفاده از فکتوری پترن ما چه مشکلاتی داشتیم که با استفاده از فکتوری مشکل حل شده؟باید بگید قبل فکتوری چه مشکلاتی بوده که با فکتوری حل شده-پایگاه داده و مفاهیم کلید اصلی کلید خارجی ،  ایندکس گذاری و دلیل انجامش؟مثلا از خود من پرسیدند بک گراند ایندکس در دیتابیس چه نوع الگوریتمی فعاله؟یا مثلا ردیس بخاطر چی سرعتش زیاده؟بخاطر استفاده از الگوریتم هش تیبل که به صورت key و value عمل میکند-بعضی شرکت ها هم هستند که یک مسئله طرح میکنند بر فرض مثال :ما دو تا سیستم مختلف از نظر تکنولوژی داریم مثلا یکی پایتون دیگری وردپرس حالا میخواهیم وقتی کاربر لاگین کرد در یکی از این سایت ها دیگر نخواهد دوباره برای ورودش به سیستم دیگری لاگین کند در اینجا راهکار شمارا میپرسند؟جواب استفاده از  rest api auth هستش. اما باید خودتان برید دنبالش ببینید چی هستش؟-بعضی شرکت ها هم هستند که فقط مسئله های الگوریتمی میپرسند:از درخت گرفته تا گراف – انواع مرتب سازی-بهینه سازی اجرای الگوریتم ها -کدام ساختمان داده سریع است -الگوریتم سرچ درون رشته و آرایه و….اول این دست سوالات پرسیده میشه اگر اوکی بود میرن سراغ php چون حقیقتا این مفاهیم خیلی مهم تر هستنداز php چی میپرسن؟بستگی داره به مدیر فنی یا مصاحبه کننده ، کلا مصاحبه های بک اند استاندارد مشخصی نداره هر کس هر چی دلش بخواد میپرسه :)))اما اصلی هاش ایناست:توابع پر استفاده در phpتریت ها چکار میکنند؟فرق pdo با mysqli چیه در php؟فرق include و  require_once چیه؟فرق کلاس استاتیک با نان استاتیک چیه؟ یا کلاس استاتیک با سینگل تون چه فرقی داره؟صف و جاب در لاراولمیدلور هااعتبارسنجی کاربر: jwt و انواع آنمایگریت ها در لاراولاستفاده از کش ها و سیستم کشینگ در لاراول (این خیلی مهم هستش تو بهینه کردن سایت)کنترل -مدل و ویو ، همان mvc چیه؟ و هر کدام کارشان چیه؟ایجاد سرویس – رویداد ها در لاراول</description>
                <category>Majid</category>
                <author>Majid</author>
                <pubDate>Mon, 10 May 2021 18:37:40 +0430</pubDate>
            </item>
                    <item>
                <title>لاراول میکس</title>
                <link>https://virgool.io/@Majid_karimpanah/%D9%84%D8%A7%D8%B1%D8%A7%D9%88%D9%84-%D9%85%DB%8C%DA%A9%D8%B3-tu2aaog0hm2l</link>
                <description>در این پست میخوام در مورد یکی از اخبار جدیدی که در رابطه با لاراول ارائه شده صحبت کنم . که شاید برای دوستداران لاراول جالب باشه . در اکتبر سال ۲۰۱۴ بود که لاراول ابزاری به اسم Elixir رو برای اولین بار در لاراول قرار داد تا توسعه دهنده ها بتونن خیلی از کارهای Frontend رو بصورت اتوماتیک انجام بدن . این ابزار بر پایه Gulp ایجاد شده و اگر با Gulp آشنا باشین میدونید که این ابزار برای اتوماتیک کردن خیلی از کارها Frontend مورد استفاده قرار میگیره و کار توسعه دهنده ها رو خیلی خیلی ساده تر میکنه .حالا Elixir بعد از حدود ۲ سال ، پیشرفت های زیادی کرده و به یک ابزار محبوب در بین لاراولی ها تبدیل شده.در ورژن بعدی لاراول ، Elixir قراره تغییر پیدا کنه و بجای استفاده از Gulp از Webpack برای پیاده سازی استفاده کنه . این یعنی اینکه ، قراره اکوسیستم پلاگین هاش تغییر پیدا کنه . چون قراره از پایه عوض بشه ، برای همین اسمش هم تغییر پیدا کرده .اسم جدیدش هست لاراول Mix که قرار همراه لاراول ۵.۴ ارائه بشه .اگر تا الان از لاراول Elixir استفاده میکردین و بهش عادت کردین پس شاید این خبر خوبی برای شما نباشه ولی تا اومدن لاراول ۵.۴ باید صبر کرد و دید که دلیل اینکار لاراول چی میتونه باشه . از گشت و گذاری که درباره لاراول Mix کردم این رو فهمیدم که این ابزار توسط Jeffrey Way در حال توسعه است و اگر میخواین لاراول Mix رو حتی قبل از ارائه توسط خود لاراول ببینید میتونید به اکانت گیت هاب Jeffrey Way مراجعه کنید . یا مستقیم برین به repository لاراول Mix. یا حتی مثال کامل لاراول به همراه لاراول Mix رو در این repository مشاهده کنید.این یکی از بهترین خبر هایی هست که میتونه در مورد Frontend لاراول اتفاق افتاده باشه.</description>
                <category>Majid</category>
                <author>Majid</author>
                <pubDate>Mon, 05 Apr 2021 14:40:48 +0430</pubDate>
            </item>
                    <item>
                <title>composition api</title>
                <link>https://virgool.io/VueFramework/composition-api-n60ip59yn0yb</link>
                <description>Composition APIشاید به جرات میتونم بگم بزرگترین تغییر Vuejs 3 نسبت به برادر بزرگترش (Vue 2) همین Composition API باشه که تو این مقاله قرار مفصل راجبش حرف بزنیم.Composition API چیست؟فقط برای رفع نگرانی ، این API جدید جایگزین سینتکس قبلی Vue 2.x نشده که API Options نام داره ! حتی می توانیم از API Options در Vue 3 استفاده کنیم. Composition API فقط مدلیه که برای رفع محدودیتهای API Options در Vue 2 ایجاد شده. در بخش بعدی این محدودیت ها را بررسی خواهیم کرد .خیلی ساده بخام واستون بگم با Composition API دیگه نیازی نیس که data  هر رو یه جا  function  ها رو یه جا تعریف کنید با این مدل میتونیم خوانایی کدمون رو بیشتر کنیم مثلا هر data رو کنار function اون تعریف کنیم و اینجوری نظم و خوانایی کد خیلی بالاتر میره البته این فقط یه نمونه کوچیک بود که من گفتم کاریی های فوق العاده دیگه ای هم داره که بهش میپردازیم.چرا اصلا تغییر ؟!!حالا شاید واستون سوال پیش بیاد چرا باید با این روش کد بزنم مگه روش قبلی چه مشکلی داشت اینجاست که باید بگم :۱ توسعه و سازماندهی بهتر۲ پشتیبانی بهتر از TypeScriptداخل عکس زیر مشاهده میکنید روش کد زنی Composition API و API Options:</description>
                <category>Majid</category>
                <author>Majid</author>
                <pubDate>Tue, 22 Sep 2020 18:38:08 +0330</pubDate>
            </item>
            </channel>
</rss>