Search this Blog. Ищите что то конкретное? Воспользуйтесь поиском! Например введите "иммиграция"
Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts
How to approach programming
Posted by
Alexander Hvastovich
Lesson 3
Value translation
Task description
Distance in a program may be represented in two units of measurement: miles and in kilometers. One set of algorithms/functions accepts value in miles while another in kilometers. In order to use the same distance value in both, value needs to be “translated” between miles and kilometers. Provide a way to ensure that correct parameter value is provided in both set of interface functions.
Solution
2.1 Type definitions
Separate types/classes need to be defined for each different units of measurement to be used as parameters in different API functions. In our case there are two of those units – kilometers and miles but in other cases may be more. So, these types are DistanceInKilometers and DistanceInMiles. These types are to be used to pass values as parameters into APIs
Then, a main class needs to be defined which will hold the
value of distance in the program – Distance. Value will be only one but there
are accessor methods (empty operators) that will return values of this distance
held by this object internally in different units.
Class UnsignedInteger
{
public:
UnsignedInteger(unsigned
int val) { Value = val; }
protected:
unsigned int Value;
};
Class DistanceInMiles : public class UnsignedInteger
{
DistanceInMiles(unsigned
int value) // constructor – takes initial value in
miles
{ Value = value; } //
assigns parameter value to a member Value
};
Class DistanceInKilometers : public class UnsignedInteger
{
DistanceInKilometers(unsigned
int value) // constructor – takes initial value in
kilometers
{ Value = value; } //
assigns parameter value to a member Value
};
Class Distance : public class UnsignedInteger
{
Distance(DistanceInKilometers Val)
// constructor – takes initial value in kilometers
{ Value = Val.Value; } // assigns parameter value to a member Value
operator DistanceInMiles
() // empty operator method to get in miles
{ return DistanceInMiles(Value
* 10 /16); }
operator DistanceInKilometers
() // empty operator method to get in kilometers
{ return DistanceInKilometers(Value);
}
};
2.2 Usage in APIs
Now we will explain the usage of those classes in the
program. Let's imagine we have two APIs – taking distance in different units.
These APIs need to use these defined types sa parameters in their APIs.
Class APIUsingKilometers
{
static Void API1Method(
DistanceInKilometers dist);
}
Class APIUsingMiles
{
static Void API2Method(
DistanceInMiles dist);
}
2.3 Usage in program
Here will be the usage of the whole thing together. Let's
say we calculated the distance in the program and then use it to pass to
different APIs.
Class123::Method123
{
Distance distanceToSomething(DistanceInKilometers(2345)); // initialize with kilometers
APIUsingKilometers::API1Method(distanceToSomething); // call API which accepts kilometers, the value will be
automatically given in kilometers
APIUsingMiles::API2Method(distanceToSomething); // call API which accepts miles, the value will be
automatically given in miles
}
As we see in the example above, all these class/type
definitions were made just in order to be able to call these two APIs with
“transparent” Distance value and so that each API will get automatically translated correct value. It is
assumed, of course, that in real life the number of times that those APIs are
called are much much bigger and there will be a lot of savings in programmer's
effort on calling those APIs, so that all this “preparation” work on defining
special classes/types is not wasted.
How to approach programming 1,2
Posted by
Alexander Hvastovich
How to approach programming
Intro (lesson 1 and 2)Those two videos more of an introduction to basic understanding on how to write good code and how it's connected to the real world.
Let me know if you have any suggestions.
Thank you very much!
Subscribe to:
Posts (Atom)
Поделиться "Америкой для успешных"
Тэги
09/11/01 Terrorist attack
1. О чем этот блог
9/11
Breakthrough Options for Families
dv lottery 2014
Educational commission for foreign medical graduates
English for kids
General blog Info
green card
How to Become an Attorney in NY
programming
Russian Facebook
USA
Visa L-1
Visa O-1
Vkontakte
Американская культура
Американские праздники
Американские товары. Заказ и доставка товаров из США
Английский для детей
Английский язык
Атака террористов
Беларусь
Бизнес
Бизнес в США
Взятки в России и бегство в Америку
Виза Л-1
Визы
водительские права в США
впечатления о США
Грин Кард лотерея
Демотиваторы
Для тех только собирается иммигрировать
Жизнь Иммигрантов в Америке
Здоровье и Спорт
Иммиграция в Америку
Истории Людей
Как избавиться от депрессии
Как стать врачем в США
Кредитная история
Купить iPad3 из Америки
Лос Анджелес
Маша Марки
Мы на радио
На каком этапе сейчас блог?
Неврозы и их разрешения.
Недвижимость
Нью Йорк
Образование в США
Одиночество в Америке
Онлайн консультации
оружие в США
Ответы на вопросы читателей
отправить письмо в Америку
Отправить письмо или посылку из Америки в Россию
отправить посылку в США
отсоединение Техаса от Америки
Поиски жилья в Америке
Полезная информация
полит убежище в Америке
Политика
Политическое убежище в США
Пора валить
Путешествие из России в Америку
Путешествия
Работа в Америке
Развал США
русские блоги об Америке
Саморазвитие / Психология
свалить из Рашки
Сдача на американские права
силиконовая долина
смерть в США
события 11 сентября
стартап
Теория иммиграционной психологии
Философия
Финансы
Что делать новеньким в США
Это интересно