teleren/devto huggingface dataset:
Setting private properties in tests
Tags: php, tdd
Published: 2019-09-08 08:31:14

---
title: Setting private properties in tests
published: true
tags: php, tdd
canonical_url: https://matthewdaly.co.uk/blog/2019/09/07/setting-private-properties-in-tests/
---

Sometimes when writing a test, you come across a situation where you need to set a private field that’s not accessible through any existing route. For instance, I’ve been working with Doctrine a bit lately, and since the ID on an entity is generated automatically, it should not be possible to change it via a setter, but at the same time, we sometimes have the need to set it in a test.

Fortunately, there is a way to do that. Using PHP’s reflection API, you can temporarily mark a property on an object as accessible, so as to be able to set it without either passing it to the constructor or creating a setter method that will only ever be used by the test. We first create a `ReflectionClass` instance from the object, then get the property. We mark it as accessible, and then set the value on the instance, as shown below:

```
<?php

declare(strict_types = 1);

namespace Tests\Unit;

use Tests\TestCase;
use Project\Document;
use ReflectionClass;

final class DocumentTest extends TestCase
{
    public function testGetId()
    {
        $doc = new Document();
        $reflect = new ReflectionClass($doc);
        $id = $reflect->getProperty('id');
        $id->setAccessible(true);
        $id->setValue($doc, 1);
        $this->assertEquals(1, $doc->getId());
    }
}
```

If you’re likely to need this in more than one place, you may want to pull this functionality out into a trait for reuse:

```
<?php

declare(strict_types = 1);

namespace Tests\Traits;

use ReflectionClass;

trait SetsPrivateProperties
{
    /**
     * Sets a private property
     *
     * @param mixed $object
     * @param string $property
     * @param mixed $value
     * @return void
     */
    public function setPrivateProperty($object, string $property, $value)
    {
        $reflect = new ReflectionClass($object);
        $prop = $reflect->getProperty($property);
        $prop->setAccessible(true);
        $prop->setValue($object, $value);
        $prop->setAccessible(false);
    }
}
```

Then your test can be simplified as follows:

```
<?php

declare(strict_types = 1);

namespace Tests\Unit;

use Tests\TestCase;
use Project\Document;
use Tests\Traits\SetsPrivateProperties;

final class DocumentTest extends TestCase
{
    use SetsPrivateProperties;

    public function testGetId()
    {
        $doc = new Document();
        $this->setPrivateProperty($doc, 'id', 1);
        $this->assertEquals(1, $doc->getId());
    }
}
```

While this is a slightly contrived and limited example, and this situation is quite rare, I’ve found it to be a useful technique under certain circumstances.
Strive to get things wrong as soon as possible
Tags: failing
Published: 2019-09-07 18:56:47

---
title: Strive to get things wrong as soon as possible
published: true
description: It's the yin-yang of the creator
tags: failing
---

Quite often people get stuck on a particular development problem and just sit there, staring at the screen for hours, hoping for the right solution to pop and enlighten their day.

And…it never does.

It turns out that developing software is far more different than solving problems in school.

In school you have a _correct_ answer. That’s how teachers grade students (which is flawed by nature). In programming (and in life in general), you always have _many_ right answers. That’s the beauty of it (and that’s why the school doesn’t work in practice).

So, instead of just sitting there and thinking about the big problem in front of you, what you could easily do is __start experimenting__. And more importantly – __start failing as soon as possible__.

I know, it sounds counterintuitive, but think about it for a second. You know the saying that every time you fail to do “the thing,” you discover a new way how not to do “the thing”. Therefore, why are you afraid of breaking things? Why are you afraid of being wrong?

In fact, being _wrong_ is the inevitable step of the process to becoming _right_.

So, once again, what are you waiting for? You just waste precious time.

Start building, start breaking, start being wrong and get comfortable failing. It’s the yin-yang of the creator. __You must be wrong in order to become right__. So, please get things wrong. You’re not in school anymore.
[Video] The State of the Web: Developing with a global mindset
Tags: webdev
Published: 2019-09-07 18:55:14

---
title: [Video] The State of the Web: Developing with a global mindset
published: true
description: Interview with Andrey Sitnik, creator of globalization tools like PostCSS, Autoprefixer, and Browserslist, about developing for the global web.
tags: webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/gnixuektqp15ggt0cpvd.jpg
---

To many web developers, having a global mindset just means translating the content into various languages. There are also cultural differences that may make a website difficult or even impossible to use. In this video with [Andrey Sitnik](https://twitter.com/sitnikcode), he and I talk about some of the tools and techniques for inclusivity.

Some highlights:

- Users' names can be _anything_ and might not fit the template of your sign up form. Rather than forcing a first and last name, allow them to enter their name into a single "Name" field. And whatever you do, don't enforce minimum character limits!
- The browsers you support and test with can have a big effect on who is able to use your website. There are pockets of the world where some browsers are more popular than others and the distribution of popularity is not evenly spread.
- Having fast and reliable access to the internet can be a luxury in some parts of the world. Even in developed countries, connectivity can be intermittent, so building offline resilience lowers the barrier to use.
- Expand your global mindset by busting out of your tech bubble. If you have the means, attend conferences in parts of the world where you wouldn't normally go. Something everyone can do is simply follow underrepresented people on social media to be exposed to new and different ideas. When you reshare other people's content, think twice about creating an echo chamber and instead consider amplifying underrepresented voices.

What other takeaways resonated with you? 

{% youtube F2N-evGOcxc %}
2019 Book Haul
Tags: learning, productivity, blog, reading
Published: 2020-02-26 00:52:27

---
title: 2019 Book Haul
published: true
date: 2019-09-07 18:22:58 UTC
tags: learning,productivity,blog,reading
canonical_url: https://medium.com/@JMSPACE/2019-book-haul-f82e06adc136
---

I made a goal in 2017 to read more. I had more time on my hands. I read 2 books in 2018. Here we are in 2019 and I have read 11 books. Reading can be a good thing. It can pass the time. One moment you are reading a page, next thing you know, you are 50% done with the book.

Finding a good book can be hard. Getting access to new books without breaking your pockets, can make it harder. I have been using the app, Libby. It’s a digital loan system through your local library, where you can borrow books and read. It works just like going into a library but without the late fees. If you use Kindle, books that you are borrowing can be read in the Kindle app.

![](https://cdn-images-1.medium.com/max/1024/0*9rRcFm16BAMcz9lZ)<figcaption>Photo by <a href="https://unsplash.com/@jruscello?utm_source=medium&amp;utm_medium=referral">Jessica Ruscello</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption>

### **The Books that I have Read So Far**

The books that are _italics_ are books that I did not finish. The books that are **bold** are books that I started and will have to come back to. The rest I have finished reading.

1. _Friday Black_
2. **The Alchemyst**
3. On the Come Up
4. **Thunderhead**
5. **Becoming**
6. The Hazel Wood
7. She Would Be King
8. Dark Matter
9. Monday’s Not Coming
10. _Jump_
11. Scythe
12. **The President is Missing**
13. The Sun is Also a Star
14. The Hate You Give
15. Born A Crime
16. Kindred
17. Scorpion

There are a ton more books that I want to read. Libby allow me to put books on hold or I can just create tags so that I can keep up with books that I want to read in the future.

**Download Libby and check for your local library. All you need is a library card to get started, hopefully your library uses Libby.**

[App Store](https://itunes.apple.com/us/app/libby-by-overdrive-labs/id1076402606?pt=211483&ct=meetLibby&mt=8)

[Google Play](https://play.google.com/store/apps/details?id=com.overdrive.mobile.android.libby&referrer=utm_source%3Dmeet_libby)

[Windows 10](https://www.microsoft.com/en-us/store/p/libby-by-overdrive/9p6g3tcr4hzr)
Creating a simple Vue pluralize filter
Tags: vue, beginners, javascript, webdev
Published: 2019-09-07 17:50:14

---
title: Creating a simple Vue pluralize filter
published: true
description: How to create a simple VueJS pluralize filter
tags: vue, beginners, javascript, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/xkgm4i5rjksl5wjhnwog.jpg
---

There are many options how to create a pluralize function but in Vue you should probably use filters. Let's create one as it's always handy to have one.

## Step 1: Add pluralize package

Let's use https://github.com/blakeembrey/pluralize to do the heavy lifting:

```
yarn add pluralize
```

## Step 2: Register filter

Our pluralize filter will take two arguments - first one is the left variable in the filter and second is the filter function argument (depends on your code structure, but it's usually *main.js* or a dedicated filters file):

```javascript
// .. your other imports
import pluralize from 'pluralize'

// .. your other code

Vue.filter('pluralize', function (value, number) {
  return pluralize(value, number)
})
```

## Step 3: Use the filter!

Now, to use the filter on the left we give it the word we want to pluralize and as an argument we pass the count:

```html
{{ tunnels }} {{ 'tunnel' | pluralize(tunnels) }}
```

That's it :) Now, based on **tunnels** variable it will be either '1 tunnel' or '50 tunnels'.


I hope this will be useful to you once you need it!
Should I Use "Popular" Frameworks If I Prefer Something Else?
Tags: javascript, react, opensource, choo
Published: 2019-09-07 17:45:48

One of my biggest struggles as a web developer is the pull between making an app that's as lightweight as possible and one that's as understandable and portable as possible.

My desire for extremely lightweight apps stems from the fact that most of the computers I've owned in my life have been hand-me-downs from family and friends and are therefore not remarkably powerful. My very first personal computer was a tiny Asus EEE PC with Windows XP on it, and I spent countless hours trying to tweak it to run as efficiently as possible on the hardware before I finally gave up to find the lightest Linux distro possible for it to run instead.

At the same time, my desire to write understandable and portable (by which I mean "portable knowledge" as in the requirements are common and widely known) stems from my love of open source development. I have thrived on open source software all my life because I've never been able to afford the "real" versions that are always so expensive. Now that I'm experienced enough, I want to give back and add to that pool of open source software, and I feel that the best way to do that and foster an environment of knowledge sharing, the code should be written in a way that people who want to contribute will be able to generally understand.

The reason I feel that these desires are at odds is that often the most popular solution (in my case, React or Angular) is frequently bulky and resource-intensive compared to other lesser-known frameworks (like [Choo](https://choo.io), which I adore, or Svelte). I like React as much as the next dev, but it's just so much bigger than Choo, which means that it takes up significantly more memory in the browser and can cause major slowdowns on less powerful devices or devices on slow data plans. But React is _the_ framework right now (or Angular or Vue or whatever), so I want to use it to make sure the most people can understand my source code (plus FOMO is probably involved).

There's also the fact that a lot of new dev jobs are looking for people with experience in those popular frameworks. I can personally make it work a lot of the time because I have a pretty firm grasp on JavaScript in general and can learn frameworks quickly, but that's not helpful when they want you to _already_ have the experience. Should I cater my open source projects to the kind of job I want to get or should I use what I enjoy using most?

I unfortunately don't have an answer to any of the questions I've asked, and I'm sure it's mostly a matter of personal opinion, but I really want to hear what this community thinks. I'm starting a project that I think might get some community involvement, and I want to make sure it's both easy to contribute to _and_ lightweight for servers and users to run.

What do you think? Is this a false dichotomy? Is there a good way to handle the opposing options?
5 easy ways to get started with JavaScript .reduce()
Tags: beginners, tutorial, webdev, javascript
Published: 2019-09-07 17:40:48

As a completely new developer, my favorite JavaScript tools were .map() and for loops. But recently, I've been determined to understand more complex methods like .reduce. 

Working through the Callbacks & Higher-order Functions challenges in [CSX](https://csx.codesmith.io/units/callbacks) has been the perfect introduction to reduce, which was intimidating for me to get started with. But reduce is a powerful method and definitely worth the effort.

The first .reduce() method I was exposed to was via [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
`arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])`
The [W3Schools definition](https://www.w3schools.com/jsref/jsref_reduce.asp) was better, but not by much.

####So what's the best way to get over this intimidation factor?

1) start small with basic examples
  - Most newbies are familiar with using .reduce() to aggregate the elements in an array

```javascript
const theOG = (array) => {
  return array.reduce((acc, el) => {
    return acc + el
  })
}
```
2) remove any confusing terminology-- accumulator? What callback?
  - I played with simple reduce applications using just x and y.
  - But it might make more sense for you to use total and current or total and item
  - Doesn't this syntax look familiar?
```javascript
return array.reduce((x, y) =>  x + y % 2)
return array.reduce((x, y) =>  x - y)
```

3) console.log a lot
  - If you're not sure what reduce is doing, console.log and see how that matches with your expectation.
```javascript
const reduces = (array) => {
return array.reduce((acc, num) => {
  console.log(acc, num)
  return acc + num
  })
}
```
4) add other arguments and console.log those
```javascript
array.reduce((acc, num, index, array) => {
    console.log(num, index)
```
5) practice + repetition
  - Challenge yourself to solve different problems using .reduce() instead of the more obvious loops or methods. 
  - Solve the same problems over and over until they become second nature
  - For me, the CSX challenges did a great job of that, but you can also make up your own challenges

As with every topic, FreeCodeCamp has a straightforward [article](https://www.freecodecamp.org/news/reduce-f47a7da511a9/) you can reference when stuck. 

You can also view my reduce challenges [here](https://repl.it/@jasterix/CSX-reduce)
Which Tech Companies provide H1B Sponsorship in the US?
Tags: discuss
Published: 2019-09-07 17:35:47

### What is H1B Visa?
The H-1B is a visa in the United States under the Immigration and Nationality Act, section 101(a)(15)(H) that allows U.S. employers to temporarily employ foreign workers in specialty occupations. A specialty occupation requires the application of specialized knowledge and a bachelor's degree or the equivalent of work experience. The duration of stay is three years, extendable to six years; after which the visa holder may need to reapply. Laws limit the number of H-1B visas that are issued each year: 180,440 new and initial H-1B visas were issued in 2017. Employers must generally withhold Social Security and Medicare taxes from the wages paid to employees in H-1B status.

[https://en.wikipedia.org/wiki/H-1B_visa](https://en.wikipedia.org/wiki/H-1B_visa)

Its a question and i need help with that too and maybe a lot of people can be helped as well.
Weekly Links #4
Tags: weekly, distributedsystems, devops, sre
Published: 2019-09-07 17:21:13

* [Operating a Large, Distributed System in a Reliable Way: Practices I Learned](https://blog.pragmaticengineer.com/operating-a-high-scale-distributed-system/) by Gergely Orosz
* [The Product-Minded Software Engineer](https://blog.pragmaticengineer.com/the-product-minded-engineer/) by Gergely Orosz
* [What to do once you admit that decentralizing everything never seems to work](https://hackernoon.com/decentralizing-everything-never-seems-to-work-2bb0461bd168) by Nathan Schneider
* [The Pipeline Driven Organization - Enabling True Continuous Delivery](https://www.infoq.com/articles/pipeline-driven-organization/) by Roy Osherove
* ["It's dead, Jim": How we write an incident postmortem](https://www.hostedgraphite.com/blog/its-dead-jim-how-we-write-an-incident-postmortem) by Fran Garcia
* [Great Twitter Thread about scaling teams, distributed systems etc.](https://twitter.com/tacertain/status/1166039929354240002) by Andrew Certain @tacertain
* [Applying the Universal Scalability Law to organisations](https://blog.acolyer.org/2015/04/29/applying-the-universal-scalability-law-to-organisations/) by Adrian Colyer
* [A Brief History of “The Span”: Hard to Love, Hard to Kill](https://lightstep.com/blog/a-brief-history-of-the-span-hard-to-love-hard-to-kill/) by Ben Sigelman 
* [Don’t force allocations on the callers of your API](https://dave.cheney.net/2019/09/05/dont-force-allocations-on-the-callers-of-your-api) by Dave Cheney
* [Google's Engineering Practices documentation](https://google.github.io/eng-practices/) by Google
* [Elasticsearch is a great example of a modern monolithic application](https://twitter.com/dvassallo/status/1169798034110025728) by 
Daniel Vassallo
* [Daily Stand-up Injection of Guilt](https://www.yegor256.com/2019/09/03/injection-of-guilt.html) by Yegor Bugayenko, "A 'daily morning stand-up meeting', as it is currently performed, is just a way to manage otherwise undisciplined, non-compliant 'talent', who are reluctant to be organized for the sake of their perceived artistic merit."
* [Docker: Critical Infrastructure Upgrade Process](https://engineering.docker.com/2019/09/critical-infrastructure-upgrade-process/) by Alex Hokanson
* [8 New Rules of Open Source Infrastructure](https://thenewstack.io/8-new-rules-of-open-source-infrastructure/) by Stephan Fabel
* [Announcing Maesh, a Lightweight and Simpler Service Mesh Made](https://blog.containo.us/announcing-maesh-a-lightweight-and-simpler-service-mesh-made-by-the-traefik-team-cb866edc6f29) by the Traefik Team
* [Introducing Fine-Grained IAM Roles for Service Accounts](https://aws.amazon.com/blogs/opensource/introducing-fine-grained-iam-roles-service-accounts/) by AWS
Wrapping text input with non editable element at front
Tags: javascript
Published: 2019-09-07 16:37:56

---
title: Wrapping text input with non editable element at front
published: true
description: Wrapping text input with non editable element at front
tags: JavaScript
---

I recently had to build text input that wraps to the next line but has non editable element at the start. Apparently it is quite easy to build with content editable here is the code snippet that does that


```react
import React, { useCallback } from "react";

const WrappingInput = () => {
  const handlePaste = useCallback(event => {
    event.preventDefault();
    const value = event.clipboardData.getData("text/plain");
    document.execCommand("insertHTML", false, value);
  }, []);

  return (
    <div className="wrapping-input">
      <span>Label</span>
      <span contentEditable onPaste={handlePaste} />
    </div>
  );
};

export default WrappingInput;

```


and the corresponding css


```css
.wrapping-input > span:first-child {
  padding: 0.1em 0.5em;
  background: #ccc;
}

.wrapping-input > span:last-child {
  padding: 0.1em 0.5em;
  outline: none;
}
```

and you get text input like this.


![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/xmjeitpkbe7zspcaj94p.PNG)
How Do You Decide When To Get Your Next Computer?
Tags: anonymous, help, linux, hardware
Published: 2019-09-07 17:04:04

---
title: How Do You Decide When To Get Your Next Computer?
description: Looking to get a new laptop, but not quite sure if now is the time... and there are so many options!
published: true
tags: anonymous, help, linux, hardware
---

_This is an anonymous post sent in by a member who does not want their name disclosed. Please be thoughtful with your responses, as these are usually tough posts to write. Email sloan@dev.to if you'd like to leave an anonymous comment._

I've had my Windows 10 x64 laptop for about 7 years now. It's definitely slowed down within the last year. I don't know if I'm rushing into looking for another laptop too soon or not. So I want to know of other's experiences on this. I'm not as knowledgeable on hardware as I'd like to be, so thinking of searching for a new computer stresses me out. Plus, I'm kinda interested in using Linux but worried I'll regret that decision in case there's a bigger learning curve than I think there will be. 

Also, I have a lot of PC games that I don't think will work on Linux...

Has someone ever tried using a new OS and realized it wasn't working for you?

In terms of improving my current laptop, is there anything I can do to speed things up? I looked up some advice on [Computer Hope](https://www.computerhope.com/), but I don't want to try anything too risky.


Thanks!
Which US state has the best tech?
Tags: discuss, watercooler
Published: 2019-09-07 16:43:12

I've adjusted some of New York State DMV-related info lately through the web and I've been fairly pleasantly surprised by the experience in a few cases.

It didn't blow me away, but my expectations were pretty low and I felt pretty happy with things.

Does anyone have any insight into which states have the best software solutions?
Rust looks awesome
Tags: rust, go, productivity
Published: 2019-09-07 16:42:44

---
title: Rust looks awesome
published: true
description: Starting to look at Rust and it seems to have hit the nail on the head.
canonical_url: https://medium.com/@dlugos.ivan/rust-looks-awesome-60788a4a7e27
cover_image: https://thepracticaldev.s3.amazonaws.com/i/qzm8rx83eqqwb2q1j872.png
tags: rust, cpp, go, productivity
---

I'm (finally) starting to look at Rust and it seems to have hit the nail on the head. Actually I haven't written any code yet (shame on me) but from reading ["The Book"](https://doc.rust-lang.org/book/), it looks wonderful and I had to share :). Solving almost every major pain point I can think of in the programming languages I've used for any reasonable length of time (namely C/C++, Go if we're talking system langugages).

Like resource management for example… No automatic deep copying nor wondering who owns complex members data after a struct copy. Borrowing instead of reference/pointer management. Compile-time data race prevention? Seriously?! Seems to good to be true. I guess it does have some learning curve but if that means being able to worry less about correctness? Worth. every. minute.

Also, those value-containing ENUMs? Together with compiler-enforced complete matches. I can’t count how many times I’ve seen code not matching all possible cases in a switch/if-else…

Needless to say I’m getting really excited to start putting Rust through its paces. Please share your thoughts on this :)