投稿時間:2021-06-27 01:16:29 RSSフィード2021-06-27 01:00 分まとめ(21件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita Twitterの工ロ系フォローをpythonを使って別垢に移行する方法 https://qiita.com/danbo_ru_sama/items/2e80ada979d742f6c6be 選別してから少しフォローを増やしたので移行元と移行先にある分のフォローだけを選別します。 2021-06-27 00:20:38
python Pythonタグが付けられた新着投稿 - Qiita Discord読み上げbot自作ノウハウ① 入室コマンド編 https://qiita.com/akira_splatoon/items/519f4f7ce58e3c28e379 elseawaitctxvoiceclientdisconnect切断awaitasynciosleepconnectコマンドは急いで発動させるとバグる時があるので、ちょっと待つawaitctxauthorvoicechannelconnect接続elseawaitctxauthorvoicechannelconnect接続最後にマニアックなところですが、実はbotにDMを送ってもコマンドは実行できてしまいます。 2021-06-27 00:20:08
js JavaScriptタグが付けられた新着投稿 - Qiita スライドショーの文字列ver-PGM https://qiita.com/shizuoka_miyako_19911118/items/fdc7c66c5ef971925417 スライドショーの文字列verPGMスライドショーの文字列verPGM行ごとにスライドする時間を設定できるスライドショーのhtmlタグ付き文字列版PGMを作ってみましたサンプルPGMGitHubサンプルページ使い方スライド文字列ファイルをロードしてからスライド文字列ショーの自動再生ボタンを押すと再生します。 2021-06-27 00:31:36
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) sql booleanカラムのデータの値変換について https://teratail.com/questions/346324?rss=all bignbspquery 2021-06-27 00:52:51
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) カスタムキーボードとは別の方法?でキーボードを作成したい https://teratail.com/questions/346323?rss=all カスタムキーボードとは別の方法でキーボードを作成したいこちらのアプリ『スゴイ便利帳』AppnbspStoreでは入学卒業年を調べる機能があります。 2021-06-27 00:49:17
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) pythonの行列計算の結果が思うようにならない https://teratail.com/questions/346322?rss=all pythonの行列計算の結果が思うようにならない発生している問題pythonで重回帰分析のプログラムを書いているのですが、なかなか思った結果になりません。 2021-06-27 00:48:41
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) ボタンのidを記入する箇所で「Task :app:compileDebugKotlin FAILED」というエラーが表示される https://teratail.com/questions/346321?rss=all ボタンのidを記入する箇所で「TaskappcompileDebugKotlinFAILED」というエラーが表示される前提・実現したいことこちらのサイトを参考にして、AndroidnbspStudioを用いてQRコードを読み込むアプリを作成しようとしています。 2021-06-27 00:45:00
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) PHPの複数ページにわたりデータをSESSIONに格納する方法 https://teratail.com/questions/346320?rss=all ただ、SESSIONメソッドを使って複数ページにわたるデータを格納したいと思っていますが、ページ目のデータしかSESSIONメソッドに格納できません。 2021-06-27 00:41:44
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) windows用ソフトをプログラムしてマイクとして認識させたい https://teratail.com/questions/346319?rss=all windows用ソフトをプログラムしてマイクとして認識させたい前提・実現したいことWindows用のリアルタイムボイスチェンジャーソフトを自作しようと考えているのですが作成したソフトの音声をシステム側にマイク入力と同等に認識させる方法が思いつきません。 2021-06-27 00:39:05
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) forで使うiとかの変数は1回ごと初期化されるのか? https://teratail.com/questions/346318?rss=all 部分 2021-06-27 00:34:28
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) TODOリストvalueが反応しません。 https://teratail.com/questions/346317?rss=all TypeScriptnbspnbspReactでTODOリストを作成中なのですが、追加ボタン押しても下に追加されません。 2021-06-27 00:29:21
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 参照渡し ベクトル計算 https://teratail.com/questions/346316?rss=all 参照渡しベクトル計算参照渡しについてvoidnbspcrossproductdoublenbspadoublenbspbdoublenbspcでCのijk成分cがicがjcがk成分を計算してprintfquotCnbspnbsplfilfjlfknquotCCCで表示させたいのですが、以下のようなエラーが出て実行できません。 2021-06-27 00:07:08
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) サイトの演出を、初回訪問時のみに制御したい https://teratail.com/questions/346315?rss=all サイトの演出を、初回訪問時のみに制御したい前提・実現したいことこちらのサイトにサンプルのある「背景色が伸びる」演出を、初回セッション時のみ作動するように実装を試みています。 2021-06-27 00:05:55
Ruby Rubyタグが付けられた新着投稿 - Qiita RubyとRuby on Rails の特徴 https://qiita.com/W2020T/items/a6032d1e7fa489d93f03 Rubyを使うメリット文法や書式がシンプルに構成されており読みやすい動的型付の言語のため変数に型宣言が不要Rubyを使うデメリットコードを実行する際に行ずつコンピュータが読み取りやすいように機械語に翻訳していくインタプリタ言語であるため実行速度が遅い複数人などでWebシステムの開発などのプロジェクトを進める際に同一コードベースに複数のコーディングスタイルが混在してしまうRubyonRailsの特徴DRYDontRepeatYourselfRubyonRailsでは同じコードを繰り返し書くことを避け、保守管理しやすい状態に保ちバグを減らすことができます。 2021-06-27 00:04:34
Linux Ubuntuタグが付けられた新着投稿 - Qiita 軽量なKubernetes「K3s」でクラスタを組んでみる(Ubuntu Server) https://qiita.com/otsukousan/items/5d7a786aa7a2e7335368 ホスト名を指定したUbuntuServerを台用意各サーバでetchostsを設定マスターノードでKsインストールamp起動ワーカーノードでKsインストールampクラスタに追加リソースのデプロイホスト名を一意にしたUbuntuServerを台用意するクラウドVMでも、ローカルマシン上にVMを立てても、物理マシンを用意しても大丈夫です。 2021-06-27 00:36:08
海外TECH DEV Community What is Linux 🤔 https://dev.to/cenacr007_harsh/what-is-linux-4d8h What is Linux I have recently started learning Linux and so I decided to document my journey along the way so I would be writing a Blog series where I will cover everything that I have learned The entire content credits goes to my instructor Brian Holt So without further ado let s get on with todays blog Let s get started with a little bit of backstory about Linux ‍To learn about how Linux came to be let s go back to the beginning to where Ken Thompson and Dennis Ritchie of Bell Laboratories developed the UNIX operating system It was later rewritten in C to make it more portable and eventually became a widely used operating system A decade or so later Richard Stallman started working on the GNU GNU is Not UNIX project the GNU kernel called Hurd which unfortunately never came to completion The GNU General Public License GPL a free software license was also created as a result of this The kernel is the most important piece in the operating system It allows the hardware to talk to the software It also does a whole lot of other cool things For now just know that the kernel controls pretty much everything that happens on your system During this time other efforts such as BSD MINIX etc were developed to be UNIX like systems However one thing that all these UNIX like systems had in common was the lack of a unified kernel Then in a young fellow named Linus Torvalds started developing what we now know today as the Linux kernel If at this you are wondering why I am giving you a history lesson its because I think it s useful to know why something was created to understand what problems it can solve for you Let s talk a bit more about UNIX so that we can understand UNIX like systems better UNIXLinux is considered a Unix like operating system which basically means that Linux derives heavy inspiration from Unix without actually conforming to be a full Unix operating system macOS and FreeBSD would be two more examples of a Unix like operating system Unix was created in the s and has pretty much inspired every operating system created since then Nearly everything you re going to learn today was originated in Unix itself A big part of Unix software is the idea of the Unix philosophy which is a sort of digital minimalism when it comes to coding The idea is instead of having a few very specialized tools or programs we should have many small composable tools that we can use to compose to solve larger problems The influence of this is still felt and talked about today Here s what they originally wrote Make each program do one thing well To do a new job build afresh rather than complicate old programs by adding new features Expect the output of every program to become the input to another as yet unknown program Don t clutter output with extraneous information Avoid stringently columnar or binary input formats Don t insist on interactive input Design and build software even operating systems to be tried early ideally within weeks Don t hesitate to throw away the clumsy parts and rebuild them Use tools in preference to unskilled help to lighten a programming task even if you have to detour to build the tools and expect to throw some of them out after you ve finished using them LinuxLinux isn t directly Unix just directly inspired by it and incorporates many of its ideas and interfaces into it It was created in by Linus Torvalds who is still an influential figure today and still runs the Linux project He created Linux because at the time there was no single free open source reimplementation of the Unix operating system the BSD kernel wasn t yet available yet so he wrote his own kernel which became known as the Linux kernel From here the project took off and was adopted far and wide As of writing all of the top super computers run on Linux much of the mobile phone market share thanks to Android being based on Linux and many of the servers running your favorite websites Suffice to say Linux is incredibly important to the modern computing world TIME has come to answer the most important Question Why Linux So why Linux over other operating systems First it s free Anyone can use Linux to do anything without paying anyone a dime This is useful for college students who don t have any money but it s also critical for large businesses running thousands or tens of thousands of servers It can save them millions of dollars to not have to pay for an operating system It s very well maintained Because Linux is such a popular operating system it has a lot of eyes on it Engineers from all over the world and all over the industry are constantly contributing fixes and new features to Linux both on their own free time and during the course of their jobs It runs just about anywhere Linux not only runs on x the Intel AMD processor architecture your computer is likely using but it runs on Internet of Things devices phones fridges cars etc If it has a processor in it chances are you can get Linux running on it already Most of the the things you need already exist for it Linux already has many of the tools one would need to run servers devices media etc all on it already meaning you wouldn t need to create it Linux has a rich ecosystem of programs available that are also likely free The knowledgebase for Linux is enormous Having a problem Chances are someone else already had the same problem and you can find the solution on StackOverflow or someone s blog Because the knowledgebase is so large it s really easy to hire someone with deep knowledge of Linux and for you it s profitable to learn Linux because so many jobs demand the skillset At its core Linux is the kernel Anything based on this Linux kernel is a considered a Linux distribution or distro for short Choosing a Linux Distribution We learned about the Linux kernel which powers millions of devices a day One thing before we move forward the term Linux is actually quite a misnomer since it actually refers to the Linux kernel However many distributions use the Linux kernel so therefore are commonly known as Linux operating systems A Linux system is divided into three main parts Hardware This includes all the hardware that your system runs on as well as memory CPU disks etc Linux Kernel As we discussed above the kernel is the core of the operating system It manages the hardware and tells it how to interact with the system User Space This is where users like yourself will be directly interacting with the system So the first step we ll need to take is to install Linux on your machine There are many Linux distributions to choose from we ll just go over the most popular options DebianDebian is an overall great operating system for any platform UbuntuGreat for any platform desktop laptop and server Linux MintGreat for desktop and laptopRed Hat Enterprise LinuxAs described by the name it s mostly used in enterprise so if you need a solid server OS this would be a good one Arch LinuxGreat for desktop and laptop If you also have a small device such as a Raspberry Pi and need to stick a lightweight OS on it you can t go wrong with Arch Few more popular ones KaliAlpineCentOSGentooFedoraopenSUSE Let s Run Linux So enough chit chat let s run Linux Which operating system are you using right now If you re using a desktop running Linux of some variety you re already set For Windows and MacOS users we have some options VirtualizationWe re going to running our Linux through a process call virtualization We ll be running a virtual machine which is frequently abbreviated as VMs VMs are an operating system running within another operating system called the host machine The host machine will create a virtual environment with virtual access to its hardware to the VM The VM will have no idea that it s not actually running on real hardware all it can see is the resources that the host is providing it I ll give you several options so you can do what s best fit for you For either macOS or Windows MultipassMultipass is a great new tool from the folks at Canonical who make Ubuntu It s a super easy way to spin up and spin down little VMs to try things out You can even spin up multiple and play with them together I d recommend this for most users of macOS and Windows since it just sort of works without a lot of effort and you don t have to install everything yourself If you are on Windows Home you need to install VirtualBox too in addition to Multipass Multipass will use VirtualBox if it can t use Microsoft Hyper V a feature only available in Windows Pro If you are on MacOS or Windows Pro you do not need VirtualBox Here are the Windows instructionsHere are the MacOS instructionsOnce you have Multipass installed you should be able to run it and open a new shell You should be here It has you logged in as the user ubuntu who has password less root privileges For either macOS or Windows VirtualBoxOracle makes a product called VirtualBox VirtualBox is a hosted hypervisor which is another way of saying that this is a program that allows you to run VMs It can run Windows Linux macOS and many other VMs You ll need to download VirtualBox and you ll need to download the Ubuntu Server Installer as well and go through the whole process It bears mentioning that VirtualBox isn t the only option VMWare Fusion and Parallels macOS only are two great options too They just aren t FREE Here is a YouTube Video I found useful while installing Ubuntu on my Windows VirtualBox For Windows Users WSLIf you re a Windows user you can install and use WSL I d strongly recommend installing WSL It allows you to run Linux natively inside of Windows At this point you should have a shell prompt ready to go so we can start learning Linux BonusMany people me included worship Linus Torvalds and I encourage you to find out more about him and how Linux came to be and how that led to Git being developed Yes you read it right this man was the mind behind Git as well and now you know why I worship him Here is a great Ted Talk that you should listen to What do you think are the best Linux Distros Let me know in the comments I hope you found this article valuable If yes do let me know in the comments Also if you got any question feel free to ping me on Twitter or Linkedin Thank You 2021-06-26 15:37:14
海外TECH DEV Community Using json-server as a Mock Server https://dev.to/leepzig/using-json-server-as-a-mock-server-25jf Using json server as a Mock Server OverviewWe re going to look at using json server as a mock server to practice interacting with a server We are also going to be using fetch to do both GET and POST requests Before we get started make sure you have an index html and an index js file ready to display our data Let s get started Install and Set UpTo install json server run npm install g json server in the terminal Then create a file called db json you can type touch db json in the terminal Mock DataNow we re going to put some mock data in db json to make sure everything is working JSON files resemble JavaScript objects and arrays so it should look familiar blogs title title example content content example author Your favorite author id title another title example content more content example author Your friend s favorite author id title title example number content even better content author me id Starting the ServerAfter we have some data ready we re going to start the server by running json server watch db json in the terminal You should see something like this user user Development practice project json server watch db json hi Loading db json Done Resources http localhost blogs Home http localhost Type s enter at any time to create a snapshot of the database Watching If you ctr click on the link under resources http localhost Your db json file should open up in your browser It ll look something like this Excellent now we have a server running and ready to go Fetch How to GET Data from Your ServerTo access our server in JavaScript we are going to be using fetch It s fairly simple We call fetch on our server s URL as you see below that returns a promise which we call then which returns a HTTP response now to change the HTTP response from the server to something we can use we call another then and that gives us something we are familiar with a JavaScript object Once we have the data we can then do whatever we want with it most likely display it but for now we re going to check to make sure it s working and log it to the console Make sure your index js is linked to your index html like this lt body gt lt script src index js gt lt script gt lt body gt Put this code in your index js file and open index html in your browserfetch http localhost blogs then response gt response json then data gt console log data Then you should see something like the image below in the console in the developer tools It works Now what you can do is write a function such as displayBlog and call the function on data like this fetch http localhost blogs then response gt response json then data gt displayBlog data How to POST data to json serverSo we ve made a GET request to the server and we are able to display the data from our server now let s learn how to send data to the server We re going to use fetch again but there s a little more to it this time We also need to include configuration for our fetch Fetch ConfigurationThere are a lot of different options for the fetch configuration but for our purpose we re only going to need three method headers and body The method is what type of request we re going to make which will be a POST headers are telling fetch what type of data we ll be interacting with and for us it ll be Content Type application json And lastly body is the data that we re going to be posting to the server const newBlog title Learning JavaScirpt content I learned about objects today author Java const fetchPostConfig method POST headers Content Type application json Accept appication json body JSON stringify newBlog fetch http localhost blogs fetchPostConfig then response gt response json then data gt console log data You can of course also write the configuration directly into the fetch instead of storing in a variable After we send a POST request to our server it will send a response back which we handle the same as we did our GET request We should receive exactly what we sent And it added the id for us Perfect And that s it I hope you enjoyed this post Now get out there and learn how to interact with a server 2021-06-26 15:36:41
海外TECH DEV Community Clean Code - Guia e Exemplos https://dev.to/andrebaltieri/clean-code-guia-e-exemplos-1nd0 Clean Code Guia e Exemplos ÍndiceÍndiceO que éo Clean Code Regras geraisSiga as convençõesKISSRegra do escoteiroCausa raizRegras de designMantenha dados de configuração em alto nívelExemploPolimorfismo no lugar de IFsExemploMult threadExemploSepare os códigos mult threadExemploUtilize Async como sufixoEvite configurações desnecessáriasExemploUtilize injeção de dependênciaExemploLei de DemeterExemploRegras sobre entendimento do códigoSeja consistenteExemploUtilize variáveis concisasExemploObsessão primitivaExemploEvite dependências lógicasExemploEvite condicionais negativasExemploRegras de nomesEscolha nomes descritivosExemploFaça distinções significantesExemploUtilize nomes pronunciáveis e buscáveisExemploEvite uso excessivo de stringsExemploNão use prefixo ou caracteres especiaisExemploRegras para funções ou métodosPequenas e com apenas um objetivoExemploUtilize nomes descritivosExemploOpte por poucos parâmetrosExemploCuidado com efeitos colateraisExemploNão tome decisões desnecessáriasExemploRegras de comentáriosUm código bom éexpressivoNão seja redundanteExemploNão feche os comentáriosExemploEvite códigos comentadosExemploInteçãoExemploEsclarecimentoExemploConsequênciasExemploEstrutura do códigoSepare conceitos verticalmenteExemploDeclare variáveis próximas de seu usoExemploAgrupe funcionalidades similaresExemploDeclare funções de cima para baixoExemploMantenha poucas e curtas linhasExemploNão use alinhamento horizontalExemploUse os espaços em branco corretamenteExemploNão quebre a identaçãoExemploObjetos e estruturasEsconda estruturas internasExemploOpte por estrutura de dadosExemploEvite usar dados e objetos juntosInstanciar poucas variáveisExemploClasse base não deve saber sobre suas derivadasExemploMais métodos menos tomadas de decisãoExemploEvite métodos estáticosTestesUm assert por testeLegívelExemploRápidoExemploIndependentesExemploRepetitívelExemploCode smellsRigidezFragilidadeImobilidadeComplexidade desnecessáriaRepetição desnecessáriaOpacidadeFontes O que éo Clean Code Por que estamos falando tanto sobre código limpo Clean Code e por que isto étão importante para nós De fato a manutenção de um software étão importante quanto sua construção Como relatado por Robert C Martin em seu livro clássico Clean Code um Best Seller da nossa área algumas práticas e visões são importantíssimas para mantermos a vida do nosso software IMPORTANTE Este artigo não descarta a leitura do livro que émuito mais denso e profundo sobre o assunto As empresas investem milhões em softwares todo ano mas com tantas mudanças no time e nas tecnologias como fazer este investimento durar Como garantir uma boa manutenção durabilidade vida ao software Segundo Uncle Bob as práticas abaixo são o caminho Regras gerais Siga as convençõesSe vocêcomeçou agora em um projeto ou acabaram de definir suas convenções siga as Se utilizam por exemplo constantes em maiúsculo enumeradores com E como prefixo não importa Siga sempre os padrões do projeto KISSMantenha as coisas simples Este conceito vem atéde outro livro e particularmente acho que éa base de uma boa solução Normalmente tendemos a complicar as coisas que poderiam ser muito mais simples Então Keep It Stupid Simple Mantenha isto estupidamente simples KISS Regra do escoteiro Deixe sempre o acamapamento mais limpo do que vocêencontrou O mesmo vale para nosso código Devolva Check in sempre o código melhor do que vocêo obteve Se todo desenvolvedor no time tiver esta visão e devolver um pedacinho de código melhor do que estava antes em pouco temos teremos uma grande mudança Causa raizSempre procure a causa raiz do problema nunca resolva as coisas superficialmente No dia a dia na correria tendemos a corrigir os problemas superficialmente e não adentrar neles o que muitas vezes causa o re trabalho Tente sempre procurar a causa raiz e resolver assim o problema de uma vez por todas Regras de design Mantenha dados de configuração em alto nívelAlgo que toda aplicação tem são suas configurações como as conhecidas ConnectionStrings Tente sempre deixar estas configurações ou o parse delas em um nível mais alto possível Evite sobrescrever configurações em métodos dentro de Controllers ou algo do tipo Se possível mantenha esta passagem no método principal no início da aplicação e não mexa mais nisto ExemploEm diversas aplicações que trabalho crio sempre uma classe Settings no projeto base e depois no Startup das aplicações populo ela com as configurações Isto garante que não teremos estas configurações sendo escritas em todo lugar e também que não precisaremos do IConfiguration que fica no ASP NET em projetos que não são Web MeuProjeto Domainpublic static class Settings public static string ConnectionString get set MeuProjeto Apipublic Startup IConfiguration configuration Configuration configuration Settings ConnectionString Configuration GetConnectionString connectionString MeuProjeto Infrausing var connection new SqlConnection Settings ConnectionString Polimorfismo no lugar de IFsUm IF ou condicional como o nome diz traz uma tomada de decisão a nossa aplicação o que implica no aumento da complexidade da mesma No geral devemos evitar o uso excessivo destes Nestes cenários opte sempre pelo polimorfismo ao invés de tomar decisão em todo método que cria ExemploVamos tomar como base uma classe Pagamento onde temos pagamento via Boleto ou Cartão de Crédito porém nos pagamentos via Boleto caso o dia do vencimento seja sábado ou domingo Final de semana o mesmo pode ser pago no próximo dia útil IMPORTANTE Esta regra não está correta ou eficiente éapenas uma demonstraçãopublic class Pagamento public bool PodeSerPago if tipo ETipoPagamento Boleto if vencimento Day IsWeekend return true if tipo ETipoPagamento CartaoCredito Note que temos duas tomadas de decisão dentro do método PodeSerPago onde a primeira se refere apenas a pagamentos do tipo Boleto Caso hajam mais formas de pagamento futuramente como tratariamos este código Encheriamos de IF A solução mais plausível éderivar da classe base Pagamento criando o PagamentoBoleto que sobrescreve o método PodeSerPago dando uma nova funcionalidade a ele public class Pagamento public virtual bool PodeSerPago public class PagamentoBoleto Pagamento public override bool PodeSerPago if vencimento Day IsWeekend return true Mult threadSempre que necessário utilize processamento em Threads separadas Játemos suporte a multi threads e paralelismo no C faz um bom tempo e o próprio Async Await jáajudam nisso ExemploSem async await HttpGet cursos public IActionResult Index FromServices IContentRepository repository ViewBag Courses repository GetContents EContentType Course return View Com async await HttpGet cursos public async Task lt IActionResult gt Index FromServices IContentRepository repository ViewBag Courses await repository GetContentsAsync EContentType Course return View Separe os códigos mult threadSeguindo o mesmo exemplo acima éuma boa prática manter o que éassíncrono separado do que ésíncrono para não forçar um método a ser ou não assíncrono por conta de outro trecho de código Exemplopublic async Task lt IEnumerable lt Model gt gt GetAsync var model new Model model Courses await context Courses ToListAsync model Tags context Courses ToList Não async return model Utilize Async como sufixoSe um método éassíncrono utilize sempre o sufixo async para identificá lo public async Task lt IEnumerable lt Model gt gt GetAsync Evite configurações desnecessáriasEvite deixar configurações no sistema sópor que alguém ainda não definiu como aquilo deve ser Isto polui o código e traz uma complexidade desnecessária Exemplopublic void ConfiguraUsoMySql ainda não sabemos se vamos ou não suportar MySQL também throw new NotImplementedException Utilize injeção de dependênciaSempre que possível utilize injeção de dependência ele vai tornar seu código mais limpo e desacoplado Exemplo Lei de DemeterA Lei de Demeter LoD ou princípio do menor conhecimento éum princípio que prega os seguintes pontos Cada unidade deve ter conhecimento limitado sobre outras unidades apenas unidades próximas se relacionam Cada unidade deve apenas conversar com seus amigos Não fale com estranhos apenas fale com seus amigos imediatos Exemplopublic class Order public Discount Discount get set public class Discount public decimal Amount get set public void Apply Mau exemplopublic class OrderHandler var order new Order order Discount Apply lt Bom exemplopublic class Order public Discount Discount get set public void Place Discount Apply public class OrderHandler var order new Order order Place Regras sobre entendimento do código Seja consistenteSe vocêexecuta algo de uma forma execute todo o resto desta mesma forma Seja consistente na forma com que aplica o código Siga sempre o padrão definido Exemplo Codificando em inglêspublic class CustomerRepository Agora mudou para portuglês public class ProdutoRepository Agora éportuguêspublic class RepositorioUnidadeMedida Utilizou sufixo ASYNC no método assíncronopublic async Task lt Product gt GetAsync Agora não usou mais public async Task lt Course gt Get Utilize variáveis concisasOpte por variáveis concisas mesmo que resultem em um nome maior Elas devem ser auto explicativas sem a necessidade de comentários ou informações adicionais Exemplo Total do que decimal total Total do carrinho de comprasdecimal shoppingCartTotal Obsessão primitivaNo dia a dia tendemos a nos focar apenas em tipos primitivos Built in causando uma obsessão pelos mesmos Podemos criar e usar objetos de valor Value Objects para suprir melhor esta necessidade ExemploMau exemplopublic class Customer public string Email get set public Customer Valida E mail public class Employee public string Email get set public Customer Valida E mail novamente Bom exemplo Value Objectpublic class Email public string Address get set public Email Valida E mail public class Customer public Email Email get set public class Employee public Email Email get set Evite dependências lógicasNão escreva métodos cujo funcionamento correto dependa de algo contido em sua classe ExemploMau exemplopublic class Student public bool IsSubscriber get set public void Xpto if IsSubscriber Sóexecuta se for assinante Bom exemplopublic class Student public class Subscriber Student public void Xpto Evite condicionais negativasNo C a negação édada por um sinal de exclamação que muitas vezes pode ser imperceptível ocasionando na máleitura do código Exemplo Eviteif IsSubscriber Utilizeif IsSubscriber Regras de nomes Escolha nomes descritivosEsolher bons nomes para classes variáveis e métodos éessencial para um código limpo Lembre se que se vocêprecisa explicar seu código então algo pode ser melhorado nele Exemplo Evitevar x Duração do que Qual a métrica int duration Muito mais expressivoint durationInMinutes Faça distinções significantesUtilize sempre nomes nos quais quem estiver lendo seu código possa diferenciar seu significado de outros possíveis nomes Exemplo Evitevar salario M Tem um significado maiorvar salarioEmReais M Utilize nomes pronunciáveis e buscáveisEvite utilizar nomes difíceis de pronunciar ou inventar nomes e conveções para variáveis classes e métodos Lembre se sempre da linguagem ubíquoa e da importância dela no código Exemplo Evitevar strTexto Meu texto aqui Evitepublic void GenerateBoletoInLote Evitepublic void Cadastry Evite uso excessivo de stringsQuem nunca perdeu horas procurando um BUG que era apenas um problema de comparação de string Evite digitar a mesma string várias vezes utilize constantes para isto Exemplo Eviteif environment PROD Utilizeconst string ENV PROD if environment ENV Não use prefixo ou caracteres especiaisNão utilize prefixo com o tipo da variável classe ou método e NUNCA use espaços ou caracteres especiais nestes itens Exemplo Evitepublic class clsCustomer Evitestring strNome André Evitevar situação Pendente Regras para funções ou métodos Pequenas e com apenas um objetivoMantenha suas funções ou métodos o menor possível Émais fácil ter métodos menores e reutilizáveis do que tudo dentro de um método só Exemplo Evitepublic void RealizarPedido Cadastra o cliente Aplica o desconto Atualiza o estoque Salva o pedido Utilizepublic void SaveCustomer public void ApplyDiscount public void UpdateInventoy public void PlaceOrder Utilize nomes descritivosA mesma regra dos nomes anteriormente vista aqui se aplica para este cenário Mantenha nomes concisos sem caracteres especiais Exemplo Evite Calcular o que public void Calcular Utilize Calcula o ICMSpublic void CalcularICMS Opte por poucos parâmetrosEvite exigir muitos parâmetros para construção do objeto assim como use e abuse dos Optional Parameters do C Exemplo Evitepublic void SaveCustomer string street string number string neighborhood string city string state string country string zipCode Melhorandopublic void SaveCustomer Address address Cuidado com efeitos colateraisEvite que uma função altere valores de outra classe sem ser a dela Isto échamado de efeito colateral Exemplo Evitepublic class Order public decimal Total get set var order new Order Qualquer um fora da classe Order pode atualizar seu totalorder Total Utilizepublic class Order public decimal Total get private set public void CalculateTotal var order new Order Total éprivado ninguém de fora consegue modificá lo evitando efeitos colateraisorder Total ERRO Não tome decisões desnecessáriasNão utilize os famosos flags para tomar decisões dentro dos métodos divida os em vários métodos ou atémesmo outras classes Exemplo Evitepublic class CustomerRepository public void CreateOrUpdate Customer customer bool create if create else Utilizepublic class CustomerRepository public void Create Customer customer public void Update Customer customer Regras de comentários Um código bom éexpressivoTeoricamente se vocêprecisa comentar uma parte do seu código épor que algo estáerrado com ele ele não estáexpressivo o suficiente Não seja redundanteEvite comentários que não fazem sentido algum ao contexto ou cenário Exemplo Evite Função principal do sistemapublic void Main Não feche os comentáriosNão hánecessidade de fechar os comentários Exemplo Evite Comentário lt Desnecessáriopublic void Main Evite códigos comentadosNão deixe sujeira em seu código ao invés de deixar algo comentado remova ele Hoje temos versionadores de código vocêpode voltar no tempo facilmente Exemplo Evitepublic void MinhaFuncao string texto public void Metodo InteçãoUm bom uso de comentários ésobre a intenção de um método classe ou variável Variável nem tanto Exemplo Utilize Retorna a lista de produtos inativos para o relatório de fechamento mensalpublic IList lt Product gt ObtemProdutosInativos EsclarecimentoOutro uso interessante para os comentários são esclarecimentos sobre o código Exemplo Utilizepublic void CancelarPedido Caso o pedido játenha sido enviado ele não pode mais ser cancelado if DataEnvio gt DateTime Now AddNotification O pedido jáfoi enviado e não pode ser cancelado ConsequênciasPodemos utilizar comentários para alertar sobre trechos do código que podem ter consequências mais sérias Neste caso recomendo o uso de um comentário em XML mais elaborado Exemplo Utilize lt summary gt ATENÇÃO Este método cancela o pedido e estorna o pagamento lt summary gt public void CancelarPedido Estrutura do código Separe conceitos verticalmenteMantenha uma estrutura de pastas saudável e organizada Não precisa criar uma pasta para cada arquivo mas pode haver uma separação por contexto ou feature ExemploMeuAppMeuApp DomainMeuApp Domain ContextsMeuApp Domain Contexts PaymentContextMeuApp Domain Contexts PaymentContexts EntitiesMeuApp Domain Contexts PaymentContexts ValueObjectsMeuApp Domain Contexts PaymentContexts EnumsMeuApp Domain Contexts AccountContextMeuApp Domain Contexts AccountContext EntitiesMeuApp Domain Contexts AccountContext ValueObjectsMeuApp Domain Contexts AccountContext Enums Declare variáveis próximas de seu usoNão crie todas as variáveis juntas no começo da class ou método defina as próximas de onde serão utilizadas Exemplo Evitevar total public void CreateCustomer public void CreateOrder public void UpdateCustomer public void CalculateTotal total lt Sóéutilizada aqui Utilizepublic void CreateCustomer public void CreateOrder public void UpdateCustomer var total public void CalculateTotal total Agrupe funcionalidades similaresSe uma função pertence a um grupo dentro de um objeto mantenha as sempre por perto Exemplo Evitepublic void CreateCustomer public void CheckInventory public void CreateOrder public void UpdateCustomer public void CalculateTotal Utilizepublic void CreateCustomer public void UpdateCustomer public void CheckInventory public void CreateOrder public void CalculateTotal Declare funções de cima para baixoOrdenar as funções também éimportante Além da sua ordem de grandeza suas assinaturas também devem ter uma boa oganização Exemplo Utilizepublic void CreateCustomer string name public void CreateCustomer string name int age public void CreateCustomer string name int age Address address public void CreateCustomer string name int age Address address bool active Mantenha poucas e curtas linhasEvite funções com linhas longas ou muitas linhas Não existe um número correto mas com certeza quanto mais código em uma função mais difícil de mantê la será Exemplo Utilizepublic void CreateCustomer string name var customer new Customer name repository Customers Add customer repository SaveChanges Não use alinhamento horizontalNão hánecessidade de alinhar horizontalmente variáveis constantes ou mesmo propriedades Exemplo Eviteprivate Long requestParsingTimeLimit protected Request request private FitNesseContent context this context context input s getInputStream requestParsingTimeLimit Use os espaços em branco corretamenteUtilize espaço em branco para associar ou não itens relacionados Uma boa IDE jáfaráeste trabalho por você Exemplo Utilizeprivate void meuMetodo String parametro variavel int outraVariavel algumArray length total algumMetodo outraClasse algumMetodo variavel total outroMetodo total Não quebre a identaçãoEste item dispensa comentários Um código não identado não pode ser enviado para o projeto Exemplo Evitepublic class MinhaClasse var valor Console WriteLine valor Objetos e estruturas Esconda estruturas internasEste tópico abrange uma discussão extensa Esconder a estrutura de um objeto ou seja privar as propridades relacioadas a dados dele vai sempre trazer resultados positivos e negativos Particularmente gosto de tornar os SET privados mas não éuma regra do meu código e não aplico em todas as propriedades Como consequência sempre precisamos de mais métodos para manipulação destes valores Se os dados não fazem sentido para os objetos externos não hádiscussão mantenha os privados Exemplopublic class NotificationContext private List lt string gt notifications public void Add string notification notifications Add notification public bool IsValid gt notifications Any public IEnumerable Notifications get gt notifications AsEnumerable Opte por estrutura de dadosEstruturas de dados representam a forma como os dados são organizados podendo ser uma class ou um struct Normalmente associamos as struct mais a estrutura de dados do que as classes mas podemos estruturar dados com qualquer uma delas A diferença éque ao usar class OOP temos recursos como abstração herança polimorfismo dentre outros Particularmente acho que a segmentação em objetos de valor éum ponto chave neste item Exemplo Usando estruturaspublic struct Email public Email string address Permite apenas E mails hotmail gmail yahoo public string Address get private set public class Customer public Email Email get private set Usando classespublic class Email public Email string address Permite qualquer tipo de E mail public string Address get private set public class CommonEmail Email public Email string address base address Permite apenas E mails hotmail gmail yahoo public class Customer public Email Email get private set Nos dois casos temos estruturas representando um E mail como objeto de valor porém no segundo cenário podemos criar extensões e ter uma maior flexibilidade Evite usar dados e objetos juntosEste éoutro ponto polêmico que muitos interpretam como manter nos objetos apenas propriedades enquanto seus comportamentos ficam em outros objetos Particularmente acho que a essência de um objeto éjustamente o agrupamento de variáveis e funções Propriedades e métodos Neste ponto eu sempre mantenho os comportamentos nas entidades Em relação a manter parte com object e parte com struct eu confesso que a maior parte dos meus casos eu uso apenas o object Pode ser vício ou puro comodismo mas acho estranho esta mistura Talvez uma abordagem que aplique estes conceitos de uma forma legal seja novamente o uso dos value objects Objeto de valor representa um endereço sua estrutura de dadospublic class Address public string ZipCode get set public string Street get set public string Number get set public string Neighborhood get set public string City get set public string State get set public string Country get set Objeto do cliente com seus comportamentospublic class Customer public Address BillingAddress get private set public Address ShippingAddress get private set public void ChangeBillingAddress Address address public void ChangeShippingAddress Address address Instanciar poucas variáveisEvite instanciar muitas variáveis nos objetos e seus métodos Faz uso maior das propriedades se possível Exemplopublic class ShoppingCart public decimal Total get private set public decimal CalculateTotal var total Desnecessário foreach var item in Items total item Price Melhorandopublic class ShoppingCart public decimal Total get private set private decimal CalculateTotal foreach var item in Items Total item Price Classe base não deve saber sobre suas derivadasUma classe não deve saber sobre detalhes dos seus filhos Nas verdade isto me soa tão estranho que não vejo um cenário onde uma classe pai consiga saber detalhes de seus filhos Exemplo N A Mais métodos menos tomadas de decisãoJácomentamos bastante isto na parte de OOP dos cursos mas fica aqui o reforço sempre opte por ter mais métodos mais sobrecargas do que tomadas de decisão Exemplo Evitepublic class Order public void Pay CreditCard card if card null Pagamento via boleto Pagamento via cartão Utilizepublic class Order public void Pay Pagamento via boleto public void Pay CreditCard card Pagamento via cartão de crédito Evite métodos estáticosClasses e métodos estáticos são difíceis de gerenciar além de serem compartilhados entre a aplicação como um todo Imagina que vocêtem uma classe estática que tem uma lista de notificações esta lista seria compartilhada entre todas as requisições Diversos usuários em seu sistema Evitepublic static class NotificationContext public static IList lt Notification gt Notifications get set Utilizepublic class NotificationContext public IList lt Notification gt Notifications get set Testes Um assert por testeUtilize um e apenas um assert por teste Mais de um assert pode confundir vocêe comprometer a escrita do seu teste Evite TestMethod public void ShouldReturnTrue Assert AreEqual true Assert AreEqual Utilize TestMethod public void ShouldReturnTrue Assert AreEqual true LegívelTrate seus testes como parte fundamental do seu código não secundária Os testes tem que ser organizados e bem escritos assim como o resto do seu software Exemplo N A RápidoUm dos objetivos principais de um teste écobrir uma pequena porção do nosso código Normalmente estendemos esta ideia para a maior parte do código possível ocasionando uma ampla gama de testes de unidade Dados estes testes os mesmo são executados antes da publicação das nossas aplicações garantindo que não enviaremos nada com bugs para produção Porém em cenários mais críticos o tempo dos deploys Publicações éextremamente importante e se nossos testes demoram muito podem impactar negativamente nisto Exemplo N A IndependentesOs testes não devem depender de entidades externas nem de outros testes Neste exemplo volto a salientar o uso do DI e DIP Exemplo RepetitívelDevemos ter a possibilidade de repetir o mesmo teste mas com parâmetros diferentes Exemplo TestMethod DataRow email valido com email balta io public void ShouldValidateEmail string email Assert IsTrue new Email email IsValid Code smellsCode Smells são alguns sintomas que podemos identificar e que nos remetem a uma máaplicação do Clean Code de uma forma geral RigidezSeu software édifícil de mudar Qualquer mudança por mínima que seja causa uma cascata de outras mudanças FragilidadeUma simples mudança quebra seu software em diversos locais Éo famosos cobre o pé descobre a cabeça ImobilidadeVocênão consegue reutilizar partes do seu código em outros projetos por que isto requer um esforço gigantes Em resumo tudo estámuito acoplado Complexidade desnecessáriaVocêusa padrões e arquiteturas que tornam seu código mais burocrático do que efetivo Éo famoso e se onde pensamos em tudo que o software pode ter um dia e já deixamos tudo pronto E se eu quiser voar com meu carro um dia bem se um dia vocêquiser voar aívocêconstrói as asas mas se não vai precisar voar agora foca em construir apenas o carro Repetição desnecessáriaVocêprecisa repetir o mesmo código em diversos lugares OpacidadeSeu código édifícil de entender FontesPost em InglêsLivro Clean Code 2021-06-26 15:09:19
Apple AppleInsider - Frontpage News iPhone hotspots in iOS 15 to gain WPA3 security https://appleinsider.com/articles/21/06/26/iphone-hotspots-in-ios-15-to-gain-wpa3-security?utm_medium=rss iPhone hotspots in iOS to gain WPA securityThe rollout of iOS and iPadOS this fall will help improve the security of iPhones and iPads as a Wi Fi hotspot with Apple including support for the improved WPA protocol for the feature in the operating systems Users of iPhones and iPads on iOS and iPadOS will be familiar with using their devices as a Wi Fi hotspot connecting their other devices to share their iPhone s cellular connection However these impromptu hotspots are currently only able to offer connectivity over WPA With the introduction of iOS and iPadOS the inclusion of WPA support should help make the wireless hotspots more secure reports MacRumors While Apple devices are capable of connecting to existing WPA networks the hotspot feature of iPhones didn t offer the option to use the protocol which will change in the next milestone operating system release Read more 2021-06-26 15:57:55
ニュース BBC News - Home Covid-19: 'Grab a jab' for all over-18s opens in England https://www.bbc.co.uk/news/uk-57620771 englandany 2021-06-26 15:15:02
ニュース BBC News - Home Alaphilippe wins crash-affected stage one of Tour de France https://www.bbc.co.uk/sport/cycling/57624647 crashes 2021-06-26 15:43:23

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)