0
Started
Andrew Boyko 1 month ago • updated by Alexander Shvets 1 month ago 2

Было бы здорово, показывать примеры (табы) под разные языки программирования (java, ruby, python, php, javascript, golang)

0
Fixed
arxell 2 months ago • updated by Alexander Shvets 2 months ago 1

In

https://refactoring.guru/replace-method-with-method-object

private fields representing all variables from the main method are unnecessary - in method object we still use local variables

Answer
Alexander Shvets 2 months ago

Thanks for reporting this. It's rather a bug in example. We'll upload the fix later this week.

0
Under review
jeiti 3 months ago • updated 3 months ago 2

Здравствуйте, почему только сейчас набрел на Ваш сайт, хотя он уже давно, сразу хочу сказать спасибо разработчикам, очень содержательно и поучительно, нигде такого еще не встречал. Хотелось бы, что бы был такой же сайт, только по тестированию, если такого еще нет.

0
Completed
Mahendra 3 months ago • updated by Alexander Shvets 3 months ago 7

Hello Sir,

Please look the below code and suggest me the best way to avoid this kind of condition.

if (obj.Attributes[PropertyName.Name.ToString()].Equals(objToFind.Attributes[PropertyName.Name.ToString()])){

if (obj.Attributes[PropertyName.Role.ToString()].Equals(objToFind.Attributes[PropertyName.Role.ToString()])){

if (obj.Attributes[PropertyName.Value.ToString()].Equals(objToFind.Attributes[PropertyName.Value.ToString()])){

if (obj.Attributes[PropertyName.Class.ToString()].Equals(objToFind.Attributes[PropertyName.Class.ToString()])){

if (obj.Attributes[PropertyName.Top.ToString()].Equals(objToFind.Attributes[PropertyName.Top.ToString()])){

if (obj.Attributes[PropertyName.Left.ToString()].Equals(objToFind.Attributes[PropertyName.Left.ToString()])){

if (obj.Attributes[PropertyName.Height.ToString()].Equals(objToFind.Attributes[PropertyName.Height.ToString()])){

if (obj.Attributes[PropertyName.Width.ToString()].Equals(objToFind.Attributes[PropertyName.Width.ToString()]))

{

//some operation

}


Thanks

Mahendra

Answer
Alexander Shvets 3 months ago

Sorry, C# is not my "native" programming language, but as far as I know, C# has almost the same reflection capabilities as Java. It should be easy to convert the code above to C# by looking at examples at MSDN:

https://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.getvalue(v=vs.110).aspx

for instance:

PropertyName.class.getField(fieldName) will become typeof(PropertyName).GetField(fieldName). And attributeField.get(PropertyName).toString() will probably become attribute.getValue(PropertyName). Check the MSDN article for the list of exceptions you need to handle while doing this.


0
Planned
Miranda 4 months ago • updated by Alexander Shvets 4 months ago 1

I think one way to make this site even better is to have treatments apply more directly to the problem they are addressing. For example "extract method" is a treatment for many of the code smells however it is always the same example. I'd love to be able to see how extract method is specifically helping the code smell that I am learning about.

Answer
Alexander Shvets 4 months ago

Thanks for the idea, Miranda. I'll add it to my backlog.

0
Fixed
Artanov Dmitry 4 months ago • updated by Alexander Shvets 4 months ago 1

Нужно в псевдокод

static method getInstance() is

        if (this.instance == null) then
            acquireThreadLock() and then
                this.instance = new Singleton()

добавить ещё одну проверку

static method getInstance() is

        if (this.instance == null) then
            acquireThreadLock() and then
                if (this.instance == null) then
                    this.instance = new Singleton()
Answer
Alexander Shvets 4 months ago

Исправил, спасибо!

0
Answered
Mahendra 5 months ago • updated by Alexander Shvets 5 months ago 1

Hello sir,

Does every class has interface? We are following such technique when i have behavior which use for only one client just create interface.It is due to only write unit test case.

Is it right approach to create interface for every behavior ?

Please suggest me the best practice to create interface.In refactoring i found the interface need to create when same behavior use by more then one client.


Thanks


Answer
Alexander Shvets 5 months ago

Hello Mahendra,


The main purpose of interfaces is to establish a "contract" between parts of your program—it's the way for client code to say "In this method I need any objects which can do this, this and that (described in interface). I don't really care about the class of that object, as long as it does what I need."



Let's see how this can be helpful using the analogy from real life:


You inherited a bar from your grandpa. There works a bartender named Joe. Some day Joe got drunk on the job and you decided to fire him. But there's a gotcha, only Joe knows how to handle the bar. You don't know how to replace him, because you don't know what potential candidate should be capable of doing.


So, your bar (client code) is coupled to the concrete class (Joe). In such case, you could only replace Joe with his son (subclass), who used to help Joe before and learned the ropes. But he's alcoholic too (inherited the behavior from Joe), so you have to think of something else.


Finally, you asked around and managed to write a job description for a bartender position (created the interface). And suddenly it seems that you can fill the position with anyone, who's capable of doing things listed in that document—be that experienced bartender or a part-time student.



Irony aside, here's how I decide whether or not I need an interface in particular situation:


  • Would I need to replace this class in some client code with some other class in the future?
  • Or do I have to provide some extension point for other people using this code, so that they could pass their own classes instead of default one?

If the answer is yes (for any of above), I create the interface and link the client code to the interface rather to a concrete class.


If the answer is no, I don't create interface and tie the code to a class. But even if in the future it turns out that I actually need some flexibility, I can use the Extract Interface refactoring to create a common interface.



Please note, that like any real life contract, interfaces create the burden of bureaucracy. Plus, the complexity: you create several entities (interface + class) instead of just one (a class). That's why I would not suggest creating interfaces for each class in the program.


Hope this makes sense!

0
Completed
Mahendra 5 months ago • updated by Alexander Shvets 3 months ago 2

Hello Sir,


A your suggestion i do agree with you create new class for very long method as u suggested.

In this case how do you write unit test?

Is it possible to create interface instead of calss ?

Please give explanation.


Answer
Alexander Shvets 5 months ago

Hey Mahendra,


Nice question! Here's what I think:

1. You need a class anyway, since you have to put the extracted method body somewhere. You can not put it inside interface, right?

2. You can always extract interface from a resulting class later (see Extract Interface refactoring).

0
Completed
telefragged 5 months ago • updated by Alexander Shvets 5 months ago 1

Здравствуйте, скажите пожалуйста, курс подойдет новичку? То есть, следует ли учиться подобным вещам сразу или сначала стоит набраться опыта? Спасибо!

Answer
Alexander Shvets 5 months ago

Добрый день.


Хороший вопрос, спасибо. Мне кажется, что новичку курс будет полезен, особенно секция с запахами плохого кода, т.к. обычно первый год в профессии люди только такой код и пишут.


Думаю, для себя это легче всего это понять полистав каталог рефакторинга, доступный на сайте. Если вы понимаете о чем там идёт речь, то я думаю, что курс будет вам полезен. В крайнем случае, вы всегда можете поросить возврат денег, если поймете, что материал для вас слишком сложный.


С уважением,

Александр Швец

0
Completed
irisha_mur 5 months ago • updated by Alexander Shvets 5 months ago 1

Паттерн Стратегия предлагает вынести поведения, зависящие от состояния в отдельные классы. Причём каждому состоянию должен соответствовать свой класс, а все эти классы должны иметь общий интерфейс.- ошибка? здесь должно быть паттерн состояние, нет?

Answer
Alexander Shvets 5 months ago

Да, действительно, там была опечатка. Спасибо, исправил.